Ye-old pgindent run. Same 4-space tabs.
authorBruce Momjian <[email protected]>
Wed, 12 Apr 2000 17:17:23 +0000 (17:17 +0000)
committerBruce Momjian <[email protected]>
Wed, 12 Apr 2000 17:17:23 +0000 (17:17 +0000)
434 files changed:
contrib/array/array_iterator.c
contrib/array/array_iterator.h
contrib/bit/varbit.c
contrib/bit/varbit.h
contrib/bit/varbit_glue.c
contrib/bit/vartest.c
contrib/datetime/datetime_functions.c
contrib/datetime/datetime_functions.h
contrib/miscutil/misc_utils.c
contrib/miscutil/misc_utils.h
contrib/os2client/config.h
contrib/pgbench/pgbench.c
contrib/string/string_io.c
contrib/string/string_io.h
contrib/userlock/user_locks.c
contrib/userlock/user_locks.h
src/backend/access/common/heaptuple.c
src/backend/access/common/indextuple.c
src/backend/access/common/tupdesc.c
src/backend/access/gist/gist.c
src/backend/access/gist/gistscan.c
src/backend/access/hash/hash.c
src/backend/access/hash/hashfunc.c
src/backend/access/hash/hashscan.c
src/backend/access/hash/hashsearch.c
src/backend/access/heap/heapam.c
src/backend/access/heap/hio.c
src/backend/access/heap/tuptoaster.c
src/backend/access/index/genam.c
src/backend/access/index/indexam.c
src/backend/access/index/istrat.c
src/backend/access/nbtree/nbtcompare.c
src/backend/access/nbtree/nbtinsert.c
src/backend/access/nbtree/nbtpage.c
src/backend/access/nbtree/nbtree.c
src/backend/access/nbtree/nbtscan.c
src/backend/access/nbtree/nbtsearch.c
src/backend/access/nbtree/nbtsort.c
src/backend/access/nbtree/nbtutils.c
src/backend/access/rtree/rtree.c
src/backend/access/rtree/rtscan.c
src/backend/access/transam/rmgr.c
src/backend/access/transam/transam.c
src/backend/access/transam/varsup.c
src/backend/access/transam/xact.c
src/backend/access/transam/xlog.c
src/backend/bootstrap/bootstrap.c
src/backend/catalog/aclchk.c
src/backend/catalog/catalog.c
src/backend/catalog/heap.c
src/backend/catalog/index.c
src/backend/catalog/indexing.c
src/backend/catalog/pg_aggregate.c
src/backend/catalog/pg_proc.c
src/backend/catalog/pg_type.c
src/backend/commands/_deadcode/recipe.c
src/backend/commands/async.c
src/backend/commands/cluster.c
src/backend/commands/command.c
src/backend/commands/comment.c
src/backend/commands/copy.c
src/backend/commands/creatinh.c
src/backend/commands/dbcommands.c
src/backend/commands/define.c
src/backend/commands/explain.c
src/backend/commands/indexcmds.c
src/backend/commands/remove.c
src/backend/commands/rename.c
src/backend/commands/sequence.c
src/backend/commands/trigger.c
src/backend/commands/user.c
src/backend/commands/vacuum.c
src/backend/commands/variable.c
src/backend/executor/execAmi.c
src/backend/executor/execMain.c
src/backend/executor/execQual.c
src/backend/executor/execTuples.c
src/backend/executor/execUtils.c
src/backend/executor/functions.c
src/backend/executor/nodeAgg.c
src/backend/executor/nodeAppend.c
src/backend/executor/nodeGroup.c
src/backend/executor/nodeIndexscan.c
src/backend/executor/nodeSort.c
src/backend/executor/nodeSubplan.c
src/backend/executor/nodeTidscan.c
src/backend/executor/nodeUnique.c
src/backend/lib/dllist.c
src/backend/lib/stringinfo.c
src/backend/libpq/auth.c
src/backend/libpq/be-dumpdata.c
src/backend/libpq/be-fsstubs.c
src/backend/libpq/hba.c
src/backend/libpq/portalbuf.c
src/backend/libpq/pqcomm.c
src/backend/libpq/pqformat.c
src/backend/libpq/pqpacket.c
src/backend/nodes/copyfuncs.c
src/backend/nodes/equalfuncs.c
src/backend/nodes/freefuncs.c
src/backend/nodes/list.c
src/backend/nodes/makefuncs.c
src/backend/nodes/nodes.c
src/backend/nodes/outfuncs.c
src/backend/nodes/print.c
src/backend/nodes/read.c
src/backend/nodes/readfuncs.c
src/backend/optimizer/geqo/geqo_eval.c
src/backend/optimizer/path/_deadcode/predmig.c
src/backend/optimizer/path/allpaths.c
src/backend/optimizer/path/clausesel.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/prepqual.c
src/backend/optimizer/prep/preptlist.c
src/backend/optimizer/prep/prepunion.c
src/backend/optimizer/util/clauses.c
src/backend/optimizer/util/pathnode.c
src/backend/optimizer/util/plancat.c
src/backend/optimizer/util/relnode.c
src/backend/optimizer/util/tlist.c
src/backend/optimizer/util/var.c
src/backend/parser/analyze.c
src/backend/parser/keywords.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/parser.c
src/backend/parser/scansup.c
src/backend/port/isinf.c
src/backend/port/qnx4/ipc.h
src/backend/port/qnx4/isnan.c
src/backend/port/qnx4/rint.c
src/backend/port/qnx4/sem.c
src/backend/port/qnx4/sem.h
src/backend/port/qnx4/shm.c
src/backend/port/qnx4/shm.h
src/backend/port/qnx4/tstrint.c
src/backend/port/qnx4/tstsem.c
src/backend/port/qnx4/tstshm.c
src/backend/postmaster/postmaster.c
src/backend/rewrite/locks.c
src/backend/rewrite/rewriteDefine.c
src/backend/rewrite/rewriteHandler.c
src/backend/rewrite/rewriteManip.c
src/backend/rewrite/rewriteRemove.c
src/backend/storage/buffer/buf_init.c
src/backend/storage/buffer/bufmgr.c
src/backend/storage/buffer/localbuf.c
src/backend/storage/file/buffile.c
src/backend/storage/file/fd.c
src/backend/storage/ipc/ipc.c
src/backend/storage/ipc/ipci.c
src/backend/storage/ipc/shmem.c
src/backend/storage/ipc/sinval.c
src/backend/storage/ipc/sinvaladt.c
src/backend/storage/ipc/spin.c
src/backend/storage/large_object/inv_api.c
src/backend/storage/lmgr/lmgr.c
src/backend/storage/lmgr/proc.c
src/backend/storage/page/bufpage.c
src/backend/storage/smgr/md.c
src/backend/storage/smgr/smgr.c
src/backend/tcop/fastpath.c
src/backend/tcop/postgres.c
src/backend/tcop/utility.c
src/backend/tioga/tgRecipe.h
src/backend/utils/adt/acl.c
src/backend/utils/adt/cash.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/geo_selfuncs.c
src/backend/utils/adt/int.c
src/backend/utils/adt/int8.c
src/backend/utils/adt/like.c
src/backend/utils/adt/lztext.c
src/backend/utils/adt/nabstime.c
src/backend/utils/adt/name.c
src/backend/utils/adt/network.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/pg_lzcompress.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/tid.c
src/backend/utils/adt/timestamp.c
src/backend/utils/adt/varbit.c
src/backend/utils/adt/varchar.c
src/backend/utils/adt/varlena.c
src/backend/utils/cache/catcache.c
src/backend/utils/cache/fcache.c
src/backend/utils/cache/inval.c
src/backend/utils/cache/lsyscache.c
src/backend/utils/cache/relcache.c
src/backend/utils/cache/syscache.c
src/backend/utils/cache/temprel.c
src/backend/utils/error/elog.c
src/backend/utils/fmgr/dfmgr.c
src/backend/utils/hash/dynahash.c
src/backend/utils/init/globals.c
src/backend/utils/init/miscinit.c
src/backend/utils/init/postinit.c
src/backend/utils/mb/conv.c
src/backend/utils/mb/wchar.c
src/backend/utils/misc/database.c
src/backend/utils/misc/trace.c
src/backend/utils/mmgr/aset.c
src/backend/utils/mmgr/oset.c
src/backend/utils/mmgr/portalmem.c
src/backend/utils/sort/logtape.c
src/backend/utils/sort/tuplesort.c
src/bin/pg_dump/common.c
src/bin/pg_dump/pg_dump.c
src/bin/pg_dump/pg_dump.h
src/bin/pg_id/pg_id.c
src/bin/pg_passwd/pg_passwd.c
src/bin/psql/command.c
src/bin/psql/command.h
src/bin/psql/common.c
src/bin/psql/common.h
src/bin/psql/copy.c
src/bin/psql/describe.c
src/bin/psql/describe.h
src/bin/psql/help.c
src/bin/psql/input.c
src/bin/psql/input.h
src/bin/psql/large_obj.c
src/bin/psql/mainloop.c
src/bin/psql/mainloop.h
src/bin/psql/print.c
src/bin/psql/print.h
src/bin/psql/prompt.c
src/bin/psql/prompt.h
src/bin/psql/settings.h
src/bin/psql/startup.c
src/bin/psql/stringutils.c
src/bin/psql/tab-complete.c
src/bin/psql/tab-complete.h
src/bin/psql/variables.c
src/bin/psql/variables.h
src/include/access/gist.h
src/include/access/heapam.h
src/include/access/htup.h
src/include/access/ibit.h
src/include/access/nbtree.h
src/include/access/rmgr.h
src/include/access/strat.h
src/include/access/tupdesc.h
src/include/access/tuptoaster.h
src/include/access/xlog.h
src/include/c.h
src/include/catalog/catalog.h
src/include/catalog/catversion.h
src/include/catalog/heap.h
src/include/catalog/index.h
src/include/catalog/indexing.h
src/include/catalog/pg_aggregate.h
src/include/catalog/pg_am.h
src/include/catalog/pg_amop.h
src/include/catalog/pg_attribute.h
src/include/catalog/pg_description.h
src/include/catalog/pg_inheritproc.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_trigger.h
src/include/catalog/pg_type.h
src/include/catalog/pg_version.h
src/include/commands/command.h
src/include/commands/comment.h
src/include/commands/copy.h
src/include/commands/trigger.h
src/include/commands/user.h
src/include/commands/vacuum.h
src/include/executor/nodeGroup.h
src/include/executor/nodeSubplan.h
src/include/executor/nodeTidscan.h
src/include/lib/dllist.h
src/include/lib/stringinfo.h
src/include/libpq/hba.h
src/include/libpq/libpq-be.h
src/include/libpq/libpq.h
src/include/libpq/pqsignal.h
src/include/miscadmin.h
src/include/nodes/execnodes.h
src/include/nodes/makefuncs.h
src/include/nodes/nodes.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/pathnode.h
src/include/optimizer/paths.h
src/include/optimizer/plancat.h
src/include/optimizer/planmain.h
src/include/optimizer/subselect.h
src/include/optimizer/tlist.h
src/include/parser/gramparse.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_relation.h
src/include/parser/parse_target.h
src/include/port/alpha.h
src/include/port/bsd.h
src/include/port/linux.h
src/include/port/netbsd.h
src/include/port/qnx4.h
src/include/postgres.h
src/include/rewrite/rewriteManip.h
src/include/storage/buf_internals.h
src/include/storage/buffile.h
src/include/storage/bufmgr.h
src/include/storage/fd.h
src/include/storage/itempos.h
src/include/storage/lock.h
src/include/storage/proc.h
src/include/storage/s_lock.h
src/include/storage/sinvaladt.h
src/include/storage/smgr.h
src/include/tcop/tcopprot.h
src/include/utils/acl.h
src/include/utils/array.h
src/include/utils/builtins.h
src/include/utils/catcache.h
src/include/utils/date.h
src/include/utils/datetime.h
src/include/utils/elog.h
src/include/utils/formatting.h
src/include/utils/geo_decls.h
src/include/utils/hsearch.h
src/include/utils/int8.h
src/include/utils/logtape.h
src/include/utils/lsyscache.h
src/include/utils/lztext.h
src/include/utils/memutils.h
src/include/utils/nabstime.h
src/include/utils/numeric.h
src/include/utils/pg_locale.h
src/include/utils/pg_lzcompress.h
src/include/utils/portal.h
src/include/utils/ps_status.h
src/include/utils/rel.h
src/include/utils/syscache.h
src/include/utils/temprel.h
src/include/utils/timestamp.h
src/include/utils/tqual.h
src/include/utils/trace.h
src/include/utils/tuplesort.h
src/include/utils/varbit.h
src/interfaces/cli/example1.c
src/interfaces/cli/example2.c
src/interfaces/cli/sqlcli.h
src/interfaces/ecpg/include/ecpgerrno.h
src/interfaces/ecpg/include/ecpglib.h
src/interfaces/ecpg/include/ecpgtype.h
src/interfaces/ecpg/include/sql3types.h
src/interfaces/ecpg/include/sqlca.h
src/interfaces/ecpg/lib/connect.c
src/interfaces/ecpg/lib/data.c
src/interfaces/ecpg/lib/descriptor.c
src/interfaces/ecpg/lib/error.c
src/interfaces/ecpg/lib/execute.c
src/interfaces/ecpg/lib/extern.h
src/interfaces/ecpg/lib/misc.c
src/interfaces/ecpg/lib/prepare.c
src/interfaces/ecpg/lib/typename.c
src/interfaces/ecpg/preproc/descriptor.c
src/interfaces/ecpg/preproc/ecpg.c
src/interfaces/ecpg/preproc/ecpg_keywords.c
src/interfaces/ecpg/preproc/extern.h
src/interfaces/ecpg/preproc/output.c
src/interfaces/ecpg/preproc/type.c
src/interfaces/ecpg/preproc/type.h
src/interfaces/ecpg/preproc/variable.c
src/interfaces/ecpg/test/header_test.h
src/interfaces/libpgeasy/halt.c
src/interfaces/libpgeasy/libpgeasy.h
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-print.c
src/interfaces/libpq/libpq-fe.h
src/interfaces/libpq/libpq-int.h
src/interfaces/libpq/pqexpbuffer.c
src/interfaces/libpq/pqexpbuffer.h
src/interfaces/libpq/win32.h
src/pl/plperl/eloglvl.c
src/pl/plperl/eloglvl.h
src/pl/plperl/plperl.c
src/pl/plpgsql/src/pl_comp.c
src/pl/plpgsql/src/pl_exec.c
src/pl/tcl/pltcl.c
src/test/regress/regress.c
src/utils/version.c
src/win32/endian.h
src/win32/un.h

index cadda58a8f47973b84c836450a6c2664cbf71ebf..aa8697fb037f1dbbda196e543f710ae2a9c52912 100644 (file)
@@ -144,7 +144,7 @@ array_texteq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 25,     /* text */
                          (Oid) 67,     /* texteq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -153,7 +153,7 @@ array_all_texteq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 25,     /* text */
                          (Oid) 67,     /* texteq */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -162,7 +162,7 @@ array_textregexeq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 25,     /* text */
                          (Oid) 1254,   /* textregexeq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -171,7 +171,7 @@ array_all_textregexeq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 25,     /* text */
                          (Oid) 1254,   /* textregexeq */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -185,7 +185,7 @@ array_varchareq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1043,   /* varchar */
                          (Oid) 1070,   /* varchareq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -194,7 +194,7 @@ array_all_varchareq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1043,   /* varchar */
                          (Oid) 1070,   /* varchareq */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -203,7 +203,7 @@ array_varcharregexeq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1043,   /* varchar */
                          (Oid) 1254,   /* textregexeq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -212,7 +212,7 @@ array_all_varcharregexeq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1043,   /* varchar */
                          (Oid) 1254,   /* textregexeq */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -226,7 +226,7 @@ array_bpchareq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1042,   /* bpchar */
                          (Oid) 1048,   /* bpchareq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -235,7 +235,7 @@ array_all_bpchareq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1042,   /* bpchar */
                          (Oid) 1048,   /* bpchareq */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -244,7 +244,7 @@ array_bpcharregexeq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1042,   /* bpchar */
                          (Oid) 1254,   /* textregexeq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -253,7 +253,7 @@ array_all_bpcharregexeq(ArrayType *array, char *value)
 {
    return array_iterator((Oid) 1042,   /* bpchar */
                          (Oid) 1254,   /* textregexeq */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -266,7 +266,7 @@ array_int4eq(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 65,     /* int4eq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -275,7 +275,7 @@ array_all_int4eq(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 65,     /* int4eq */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -284,7 +284,7 @@ array_int4ne(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 144,    /* int4ne */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -293,7 +293,7 @@ array_all_int4ne(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 144,    /* int4ne */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -302,7 +302,7 @@ array_int4gt(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 147,    /* int4gt */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -311,7 +311,7 @@ array_all_int4gt(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 147,    /* int4gt */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -320,7 +320,7 @@ array_int4ge(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 150,    /* int4ge */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -329,7 +329,7 @@ array_all_int4ge(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 150,    /* int4ge */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -338,7 +338,7 @@ array_int4lt(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 66,     /* int4lt */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -347,7 +347,7 @@ array_all_int4lt(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 66,     /* int4lt */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -356,7 +356,7 @@ array_int4le(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 149,    /* int4le */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -365,7 +365,7 @@ array_all_int4le(ArrayType *array, int4 value)
 {
    return array_iterator((Oid) 23,     /* int4 */
                          (Oid) 149,    /* int4le */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -376,7 +376,7 @@ array_oideq(ArrayType *array, Oid value)
 {
    return array_iterator((Oid) 26,     /* oid */
                          (Oid) 184,    /* oideq */
-                         0,            /* logical or */
+                         0,    /* logical or */
                          array, (Datum) value);
 }
 
@@ -385,7 +385,7 @@ array_all_oidne(ArrayType *array, Oid value)
 {
    return array_iterator((Oid) 26,     /* int4 */
                          (Oid) 185,    /* oidne */
-                         1,            /* logical and */
+                         1,    /* logical and */
                          array, (Datum) value);
 }
 
@@ -393,8 +393,8 @@ array_all_oidne(ArrayType *array, Oid value)
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index 9a386abd2c7959dea151a0e2cfcb8408f56cbc5f..68da385c9a4b48895d5875420dbcae9b21cc5bad 100644 (file)
@@ -2,7 +2,7 @@
 #define ARRAY_ITERATOR_H
 
 static int32 array_iterator(Oid elemtype, Oid proc, int and,
-                           ArrayType *array, Datum value);
+              ArrayType *array, Datum value);
 
 int32      array_texteq(ArrayType *array, char *value);
 int32      array_all_texteq(ArrayType *array, char *value);
@@ -32,14 +32,15 @@ int32       array_all_int4lt(ArrayType *array, int4 value);
 int32      array_int4le(ArrayType *array, int4 value);
 int32      array_all_int4le(ArrayType *array, int4 value);
 
-int32       array_oideq(ArrayType *array, Oid value);
-int32       array_all_oidne(ArrayType *array, Oid value);
+int32      array_oideq(ArrayType *array, Oid value);
+int32      array_all_oidne(ArrayType *array, Oid value);
+
 #endif
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index 2a677ec6040121657f1e35a4dc24c51891674e21..20caaf9f7cb170dd84d46bd3a88cfd95bfb91b72 100644 (file)
@@ -4,7 +4,7 @@
  *   Functions for the built-in type bit() and varying bit().
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/contrib/bit/Attic/varbit.c,v 1.2 2000/04/03 20:56:40 momjian Exp $
+ *   $Header: /cvsroot/pgsql/contrib/bit/Attic/varbit.c,v 1.3 2000/04/12 17:14:21 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
 /*#include "utils/builtins.h" */
 
 
-/* 
+/*
    Prefixes:
-     zp    -- zero-padded fixed length bit string
-     var   -- varying bit string
+    zp    -- zero-padded fixed length bit string
+    var   -- varying bit string
 
    attypmod -- contains the length of the bit string in bits, or for
-               varying bits the maximum length. 
+              varying bits the maximum length.
 
    The data structure contains the following elements:
-      header  -- length of the whole data structure (incl header)
-                 in bytes. (as with all varying length datatypes)
-      data section -- private data section for the bits data structures
-         bitlength -- lenght of the bit string in bits
+     header  -- length of the whole data structure (incl header)
+                in bytes. (as with all varying length datatypes)
+     data section -- private data section for the bits data structures
+        bitlength -- lenght of the bit string in bits
     bitdata   -- least significant byte first string
 */
 
  * zpbitin -
 
  *   converts a string to the internal representation of a bitstring.
- *        The length is determined by the number of bits required plus
- *        VARHDRSZ bytes or from atttypmod. 
- *   (XXX dummy is here because we pass typelem as the second argument 
- *        for array_in. copied this, no idea what it means??)
+ *       The length is determined by the number of bits required plus
+ *       VARHDRSZ bytes or from atttypmod.
+ *   (XXX dummy is here because we pass typelem as the second argument
+ *       for array_in. copied this, no idea what it means??)
  */
 bits8 *
-zpbitin(char *s, int dummy,  int32 atttypmod)
+zpbitin(char *s, int dummy, int32 atttypmod)
 {
-  bits8 *result;   /* the bits string that was read in   */ 
-  char  *sp;       /* pointer into the character string  */
-  bits8 *r;
-  int len,     /* Length of the whole data structure */
-    bitlen,        /* Number of bits in the bit string   */
-    slen;      /* Length of the input string         */
-  int bit_not_hex = 0;  /* 0 = hex string  1=bit string       */
-  int bc, ipad;
-  bits8 x = 0;
-
-
-  if (s == NULL)
-    return (bits8 *) NULL;
-
-  /* Check that the first character is a b or an x */
-  if (s[0]=='b' || s[0]=='B') 
-      bit_not_hex = 1;
-  else if (s[0]=='x' || s[0]=='X') 
-      bit_not_hex = 0;
-  else 
-    elog(ERROR, "zpbitin: %s is not a valid bitstring",s);
-
-  slen = strlen(s) - 1;
-  /* Determine bitlength from input string */
-  bitlen = slen;
-  if (!bit_not_hex)
-    bitlen *= 4;
-  
-  /* Sometimes atttypmod is not supplied. If it is supplied we need to make
-     sure that the bitstring fits. Note that the number of infered bits can
-     be larger than the number of actual bits needed, but only if we are 
-     reading a hex string and not by more than 3 bits, as a hex string gives 
-     and accurate length upto 4 bits */
-  if (atttypmod == -1)
-    atttypmod = bitlen;
-  else
-    if ((bitlen>atttypmod && bit_not_hex) || 
-   (bitlen>atttypmod+3 && !bit_not_hex))
-     elog(ERROR, "zpbitin: bit string of size %d cannot be written into bits(%d)",
-          bitlen,atttypmod);
-
-
-  len = VARBITDATALEN(atttypmod);
-
-  if (len > MaxAttrSize)
-    elog(ERROR, "zpbitin: length of bit() must be less than %ld",
-    (MaxAttrSize-VARHDRSZ-VARBITHDRSZ)*BITSPERBYTE);
-
-  result = (bits8 *) palloc(len);
-  /* set to 0 so that *r is always initialised and strin is zero-padded */
-  memset(result, 0, len);
-  VARSIZE(result) = len;
-  VARBITLEN(result) = atttypmod;
-
-  /* We need to read the bitstring from the end, as we store it least 
-     significant byte first. s points to the byte before the beginning
-     of the bitstring */
-  sp = s+1;
-  r = VARBITS(result);
-  if (bit_not_hex) 
-    {
-      /* Parse the bit representation of the string */
-      /* We know it fits, as bitlen was compared to atttypmod */
-      x = BITHIGH;
-      for (bc = 0; sp != s+slen+1; sp++, bc++)
+   bits8      *result;         /* the bits string that was read in   */
+   char       *sp;             /* pointer into the character string  */
+   bits8      *r;
+   int         len,            /* Length of the whole data structure */
+               bitlen,         /* Number of bits in the bit string   */
+               slen;           /* Length of the input string         */
+   int         bit_not_hex = 0;/* 0 = hex string  1=bit string       */
+   int         bc,
+               ipad;
+   bits8       x = 0;
+
+
+   if (s == NULL)
+       return (bits8 *) NULL;
+
+   /* Check that the first character is a b or an x */
+   if (s[0] == 'b' || s[0] == 'B')
+       bit_not_hex = 1;
+   else if (s[0] == 'x' || s[0] == 'X')
+       bit_not_hex = 0;
+   else
+       elog(ERROR, "zpbitin: %s is not a valid bitstring", s);
+
+   slen = strlen(s) - 1;
+   /* Determine bitlength from input string */
+   bitlen = slen;
+   if (!bit_not_hex)
+       bitlen *= 4;
+
+   /*
+    * Sometimes atttypmod is not supplied. If it is supplied we need to
+    * make sure that the bitstring fits. Note that the number of infered
+    * bits can be larger than the number of actual bits needed, but only
+    * if we are reading a hex string and not by more than 3 bits, as a
+    * hex string gives and accurate length upto 4 bits
+    */
+   if (atttypmod == -1)
+       atttypmod = bitlen;
+   else if ((bitlen > atttypmod && bit_not_hex) ||
+            (bitlen > atttypmod + 3 && !bit_not_hex))
+       elog(ERROR, "zpbitin: bit string of size %d cannot be written into bits(%d)",
+            bitlen, atttypmod);
+
+
+   len = VARBITDATALEN(atttypmod);
+
+   if (len > MaxAttrSize)
+       elog(ERROR, "zpbitin: length of bit() must be less than %ld",
+            (MaxAttrSize - VARHDRSZ - VARBITHDRSZ) * BITSPERBYTE);
+
+   result = (bits8 *) palloc(len);
+   /* set to 0 so that *r is always initialised and strin is zero-padded */
+   memset(result, 0, len);
+   VARSIZE(result) = len;
+   VARBITLEN(result) = atttypmod;
+
+   /*
+    * We need to read the bitstring from the end, as we store it least
+    * significant byte first. s points to the byte before the beginning
+    * of the bitstring
+    */
+   sp = s + 1;
+   r = VARBITS(result);
+   if (bit_not_hex)
+   {
+       /* Parse the bit representation of the string */
+       /* We know it fits, as bitlen was compared to atttypmod */
+       x = BITHIGH;
+       for (bc = 0; sp != s + slen + 1; sp++, bc++)
+       {
+           if (*sp == '1')
+               *r |= x;
+           if (bc == 7)
+           {
+               bc = 0;
+               x = BITHIGH;
+               r++;
+           }
+           else
+               x >>= 1;
+       }
+   }
+   else
    {
-     if (*sp=='1')
-       *r |= x;
-     if (bc==7) {
-       bc = 0;
-       x = BITHIGH;
-       r++;
-     } else 
-       x >>= 1;
+       /* Parse the hex representation of the string */
+       for (bc = 0; sp != s + slen + 1; sp++)
+       {
+           if (*sp >= '0' && *sp <= '9')
+               x = (bits8) (*sp - '0');
+           else if (*sp >= 'A' && *sp <= 'F')
+               x = (bits8) (*sp - 'A') + 10;
+           else if (*sp >= 'a' && *sp <= 'f')
+               x = (bits8) (*sp - 'a') + 10;
+           else
+               elog(ERROR, "Cannot parse %c as a hex digit", *sp);
+           if (bc)
+           {
+               bc = 0;
+               *r++ |= x;
+           }
+           else
+           {
+               bc++;
+               *r = x << 4;
+           }
+       }
    }
-     }
-  else 
-    {
-      /* Parse the hex representation of the string */
-      for (bc = 0; sp != s+slen+1; sp++)
+
+   if (bitlen > atttypmod)
    {
-     if (*sp>='0' && *sp<='9') 
-       x = (bits8) (*sp - '0');
-     else if (*sp>='A' && *sp<='F') 
-       x = (bits8) (*sp - 'A') + 10;
-     else if (*sp>='a' && *sp<='f') 
-       x = (bits8) (*sp - 'a') + 10;
-     else 
-       elog(ERROR,"Cannot parse %c as a hex digit",*sp);
-     if (bc) {
-       bc = 0;
-       *r++ |= x;
-     } else {
-       bc++;
-       *r = x<<4;
-     }
+       /* Check that this fitted */
+       r = (bits8 *) (result + len - 1);
+       ipad = VARBITPAD(result);
+
+       /*
+        * The bottom ipad bits of the byte pointed to by r need to be
+        * zero
+        */
+
+       /*
+        * printf("Byte %X  shift %X %d\n",*r,(*r << (8-ipad)) & BITMASK,
+        * (*r << (8-ipad)) & BITMASK > 0);
+        */
+       if (((*r << (BITSPERBYTE - ipad)) & BITMASK) > 0)
+           elog(ERROR, "zpbitin: bit string too large for bit(%d) data type",
+                atttypmod);
    }
-    }
-
-  if (bitlen > atttypmod) {
-    /* Check that this fitted */
-    r = (bits8 *) (result + len - 1);
-    ipad = VARBITPAD(result);
-    /* The bottom ipad bits of the byte pointed to by r need to be zero */
-    /*    printf("Byte %X  shift %X %d\n",*r,(*r << (8-ipad)) & BITMASK,
-      (*r << (8-ipad)) & BITMASK > 0);
-    */
-    if (((*r << (BITSPERBYTE-ipad)) & BITMASK) > 0)
-      elog(ERROR, "zpbitin: bit string too large for bit(%d) data type",
-      atttypmod);
-  }
-
-  return result;
+
+   return result;
 }
 
 /* zpbitout -
- *    for the time being we print everything as hex strings, as this is likely 
- *    to be more compact than bit strings, and consequently much more efficient
- *    for long strings
+ *   for the time being we print everything as hex strings, as this is likely
+ *   to be more compact than bit strings, and consequently much more efficient
+ *   for long strings
  */
 char *
 zpbitout(bits8 *s)
 {
-  char    *result, *r;
-  bits8    *sp;
-  int     i, len, bitlen;
-  
-  if (s == NULL)
-    {
-      result = (char *) palloc(2);
-      result[0] = '-';
-      result[1] = '\0';
-    }
-  else
-    {
-      bitlen = VARBITLEN(s);
-      len = bitlen/4 + (bitlen%4>0 ? 1 : 0);
-      result = (char *) palloc(len + 4);
-      sp = VARBITS(s);
-      r = result;
-      *r++ = 'X';
-      *r++ = '\'';
-      /* we cheat by knowing that we store full bytes zero padded */
-      for (i=0; i<len; i+=2, sp++) {
-   *r++ = HEXDIG((*sp)>>4);
-   *r++ = HEXDIG((*sp) & 0xF);
-      }
-      /* Go back one step if we printed a hex number that was not part
-    of the bitstring anymore */
-      if (i==len+1)
-   r--;
-      *r++ = '\'';
-      *r = '\0';
-    }
-  return result;
+   char       *result,
+              *r;
+   bits8      *sp;
+   int         i,
+               len,
+               bitlen;
+
+   if (s == NULL)
+   {
+       result = (char *) palloc(2);
+       result[0] = '-';
+       result[1] = '\0';
+   }
+   else
+   {
+       bitlen = VARBITLEN(s);
+       len = bitlen / 4 + (bitlen % 4 > 0 ? 1 : 0);
+       result = (char *) palloc(len + 4);
+       sp = VARBITS(s);
+       r = result;
+       *r++ = 'X';
+       *r++ = '\'';
+       /* we cheat by knowing that we store full bytes zero padded */
+       for (i = 0; i < len; i += 2, sp++)
+       {
+           *r++ = HEXDIG((*sp) >> 4);
+           *r++ = HEXDIG((*sp) & 0xF);
+       }
+
+       /*
+        * Go back one step if we printed a hex number that was not part
+        * of the bitstring anymore
+        */
+       if (i == len + 1)
+           r--;
+       *r++ = '\'';
+       *r = '\0';
+   }
+   return result;
 }
 
 /* zpbitsout -
- *    Prints the string a bits
+ *   Prints the string a bits
  */
 char *
 zpbitsout(bits8 *s)
 {
-  char    *result, *r;
-  bits8    *sp;
-  bits8    x;
-  int     i, k, len;
-  
-  if (s == NULL)
-    {
-      result = (char *) palloc(2);
-      result[0] = '-';
-      result[1] = '\0';
-    }
-  else
-    {
-      len = VARBITLEN(s);
-      result = (char *) palloc(len + 4);
-      sp = VARBITS(s);
-      r = result;
-      *r++ = 'B';
-      *r++ = '\'';
-      for (i=0; i<len-BITSPERBYTE; i+=BITSPERBYTE, sp++) {
-   x = *sp;
-   for (k=0; k<BITSPERBYTE; k++) 
-     {
-       *r++ = (x & BITHIGH) ? '1' : '0';
-       x <<= 1;
-     }
-      }
-      x = *sp;
-      for (k=i; k<len; k++)
+   char       *result,
+              *r;
+   bits8      *sp;
+   bits8       x;
+   int         i,
+               k,
+               len;
+
+   if (s == NULL)
    {
-     *r++ = (x & BITHIGH) ? '1' : '0';
-     x <<= 1;
+       result = (char *) palloc(2);
+       result[0] = '-';
+       result[1] = '\0';
    }
-      *r++ = '\'';
-      *r = '\0';
-    }
-  return result;
+   else
+   {
+       len = VARBITLEN(s);
+       result = (char *) palloc(len + 4);
+       sp = VARBITS(s);
+       r = result;
+       *r++ = 'B';
+       *r++ = '\'';
+       for (i = 0; i < len - BITSPERBYTE; i += BITSPERBYTE, sp++)
+       {
+           x = *sp;
+           for (k = 0; k < BITSPERBYTE; k++)
+           {
+               *r++ = (x & BITHIGH) ? '1' : '0';
+               x <<= 1;
+           }
+       }
+       x = *sp;
+       for (k = i; k < len; k++)
+       {
+           *r++ = (x & BITHIGH) ? '1' : '0';
+           x <<= 1;
+       }
+       *r++ = '\'';
+       *r = '\0';
+   }
+   return result;
 }
 
 
@@ -250,118 +277,133 @@ zpbitsout(bits8 *s)
  *   converts a string to the internal representation of a bitstring.
 */
 bits8 *
-varbitin(char *s, int dummy,  int32 atttypmod)
+varbitin(char *s, int dummy, int32 atttypmod)
 {
-  bits8 *result;   /* The resulting bit string           */
-  char *sp;        /* pointer into the character string  */
-  bits8 *r;
-  int len,     /* Length of the whole data structure */
-    bitlen,        /* Number of bits in the bit string   */
-    slen;      /* Length of the input string         */
-  int bit_not_hex = 0;
-  int bc, ipad;
-  bits8 x = 0;
-
-
-  if (s == NULL)
-    return (bits8 *) NULL;
-
-  /* Check that the first character is a b or an x */
-  if (s[0]=='b' || s[0]=='B') 
-      bit_not_hex = 1;
-  else if (s[0]=='x' || s[0]=='X') 
-      bit_not_hex = 0;
-  else 
-    elog(ERROR, "zpbitin: %s is not a valid bitstring",s);
-
-  slen = strlen(s) - 1;
-  /* Determine bitlength from input string */
-  bitlen = slen;
-  if (!bit_not_hex)
-    bitlen *= 4;
-  
-  /* Sometimes atttypmod is not supplied. If it is supplied we need to make
-     sure that the bitstring fits. Note that the number of infered bits can
-     be larger than the number of actual bits needed, but only if we are 
-     reading a hex string and not by more than 3 bits, as a hex string gives 
-     and accurate length upto 4 bits */
-  if (atttypmod > -1)
-    if ((bitlen>atttypmod && bit_not_hex) || 
-   (bitlen>atttypmod+3 && !bit_not_hex))
-     elog(ERROR, "varbitin: bit string of size %d cannot be written into varying bits(%d)",
-          bitlen,atttypmod);
-
-
-  len = VARBITDATALEN(bitlen);
-
-  if (len > MaxAttrSize)
-    elog(ERROR, "varbitin: length of bit() must be less than %ld",
-    (MaxAttrSize-VARHDRSZ-VARBITHDRSZ)*BITSPERBYTE);
-
-  result = (bits8 *) palloc(len);
-  /* set to 0 so that *r is always initialised and strin is zero-padded */
-  memset(result, 0, len);
-  VARSIZE(result) = len;
-  VARBITLEN(result) = bitlen;
-
-  /* We need to read the bitstring from the end, as we store it least 
-     significant byte first. s points to the byte before the beginning
-     of the bitstring */
-  sp = s + 1;
-  r = VARBITS(result);
-  if (bit_not_hex) 
-    {
-      /* Parse the bit representation of the string */
-      x = BITHIGH;
-      for (bc = 0; sp != s+slen+1; sp++, bc++)
+   bits8      *result;         /* The resulting bit string           */
+   char       *sp;             /* pointer into the character string  */
+   bits8      *r;
+   int         len,            /* Length of the whole data structure */
+               bitlen,         /* Number of bits in the bit string   */
+               slen;           /* Length of the input string         */
+   int         bit_not_hex = 0;
+   int         bc,
+               ipad;
+   bits8       x = 0;
+
+
+   if (s == NULL)
+       return (bits8 *) NULL;
+
+   /* Check that the first character is a b or an x */
+   if (s[0] == 'b' || s[0] == 'B')
+       bit_not_hex = 1;
+   else if (s[0] == 'x' || s[0] == 'X')
+       bit_not_hex = 0;
+   else
+       elog(ERROR, "zpbitin: %s is not a valid bitstring", s);
+
+   slen = strlen(s) - 1;
+   /* Determine bitlength from input string */
+   bitlen = slen;
+   if (!bit_not_hex)
+       bitlen *= 4;
+
+   /*
+    * Sometimes atttypmod is not supplied. If it is supplied we need to
+    * make sure that the bitstring fits. Note that the number of infered
+    * bits can be larger than the number of actual bits needed, but only
+    * if we are reading a hex string and not by more than 3 bits, as a
+    * hex string gives and accurate length upto 4 bits
+    */
+   if (atttypmod > -1)
+       if ((bitlen > atttypmod && bit_not_hex) ||
+           (bitlen > atttypmod + 3 && !bit_not_hex))
+           elog(ERROR, "varbitin: bit string of size %d cannot be written into varying bits(%d)",
+                bitlen, atttypmod);
+
+
+   len = VARBITDATALEN(bitlen);
+
+   if (len > MaxAttrSize)
+       elog(ERROR, "varbitin: length of bit() must be less than %ld",
+            (MaxAttrSize - VARHDRSZ - VARBITHDRSZ) * BITSPERBYTE);
+
+   result = (bits8 *) palloc(len);
+   /* set to 0 so that *r is always initialised and strin is zero-padded */
+   memset(result, 0, len);
+   VARSIZE(result) = len;
+   VARBITLEN(result) = bitlen;
+
+   /*
+    * We need to read the bitstring from the end, as we store it least
+    * significant byte first. s points to the byte before the beginning
+    * of the bitstring
+    */
+   sp = s + 1;
+   r = VARBITS(result);
+   if (bit_not_hex)
+   {
+       /* Parse the bit representation of the string */
+       x = BITHIGH;
+       for (bc = 0; sp != s + slen + 1; sp++, bc++)
+       {
+           if (*sp == '1')
+               *r |= x;
+           if (bc == 7)
+           {
+               bc = 0;
+               x = BITHIGH;
+               r++;
+           }
+           else
+               x >>= 1;
+       }
+   }
+   else
    {
-     if (*sp=='1')
-       *r |= x;
-     if (bc==7) {
-       bc = 0;
-       x = BITHIGH;
-       r++;
-     } else 
-       x >>= 1;
+       for (bc = 0; sp != s + slen + 1; sp++)
+       {
+           if (*sp >= '0' && *sp <= '9')
+               x = (bits8) (*sp - '0');
+           else if (*sp >= 'A' && *sp <= 'F')
+               x = (bits8) (*sp - 'A') + 10;
+           else if (*sp >= 'a' && *sp <= 'f')
+               x = (bits8) (*sp - 'a') + 10;
+           else
+               elog(ERROR, "Cannot parse %c as a hex digit", *sp);
+           if (bc)
+           {
+               bc = 0;
+               *r++ |= x;
+           }
+           else
+           {
+               bc++;
+               *r = x << 4;
+           }
+       }
    }
-     }
-  else 
-    {
-      for (bc = 0; sp != s+slen+1; sp++)
+
+   if (bitlen > atttypmod)
    {
-     if (*sp>='0' && *sp<='9') 
-       x = (bits8) (*sp - '0');
-     else if (*sp>='A' && *sp<='F') 
-       x = (bits8) (*sp - 'A') + 10;
-     else if (*sp>='a' && *sp<='f') 
-       x = (bits8) (*sp - 'a') + 10;
-     else 
-       elog(ERROR,"Cannot parse %c as a hex digit",*sp);
-     if (bc) {
-       bc = 0;
-       *r++ |= x;
-     } else {
-       bc++;
-       *r = x<<4;
-     }
+       /* Check that this fitted */
+       r = (bits8 *) (result + len - 1);
+       ipad = VARBITPAD(result);
+
+       /*
+        * The bottom ipad bits of the byte pointed to by r need to be
+        * zero
+        */
+       if (((*r << (BITSPERBYTE - ipad)) & BITMASK) > 0)
+           elog(ERROR, "varbitin: bit string too large for varying bit(%d) data type",
+                atttypmod);
    }
-    }
-
-  if (bitlen > atttypmod) {
-    /* Check that this fitted */
-    r = (bits8 *) (result + len - 1);
-    ipad = VARBITPAD(result);
-    /* The bottom ipad bits of the byte pointed to by r need to be zero */
-    if (((*r << (BITSPERBYTE-ipad)) & BITMASK) > 0)
-      elog(ERROR, "varbitin: bit string too large for varying bit(%d) data type",
-      atttypmod);
-  }
-
-  return result;
+
+   return result;
 }
 
 /*
-  the zpbitout routines are fine for varying bits as well 
+  the zpbitout routines are fine for varying bits as well
 */
 
 
@@ -369,228 +411,244 @@ varbitin(char *s, int dummy,  int32 atttypmod)
  * Comparison operators
  *
  * We only need one set of comparison operators for bitstrings, as the lengths
- * are stored in the same way for zero-padded and varying bit strings. 
+ * are stored in the same way for zero-padded and varying bit strings.
  *
- * Note that the standard is not unambiguous about the comparison between 
+ * Note that the standard is not unambiguous about the comparison between
  * zero-padded bit strings and varying bitstrings. If the same value is written
- * into a zero padded bitstring as into a varying bitstring, but the zero 
- * padded bitstring has greater length, it will be bigger. 
+ * into a zero padded bitstring as into a varying bitstring, but the zero
+ * padded bitstring has greater length, it will be bigger.
  *
  * Zeros from the beginning of a bitstring cannot simply be ignored, as they
  * may be part of a bit string and may be significant.
  */
 
 bool
-biteq (bits8 *arg1, bits8 *arg2)
+biteq(bits8 *arg1, bits8 *arg2)
 {
-  int bitlen1,
-    bitlen2;
-
-  if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
-    return (bool) 0;
-  bitlen1 = VARBITLEN(arg1);
-  bitlen2 = VARBITLEN(arg2);
-  if (bitlen1 != bitlen2)
-    return (bool) 0;
-  
-  /* bit strings are always stored in a full number of bytes */
-  return memcmp((void *)VARBITS(arg1),(void *)VARBITS(arg2),
-       VARBITBYTES(arg1)) == 0;
+   int         bitlen1,
+               bitlen2;
+
+   if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+       return (bool) 0;
+   bitlen1 = VARBITLEN(arg1);
+   bitlen2 = VARBITLEN(arg2);
+   if (bitlen1 != bitlen2)
+       return (bool) 0;
+
+   /* bit strings are always stored in a full number of bytes */
+   return memcmp((void *) VARBITS(arg1), (void *) VARBITS(arg2),
+                 VARBITBYTES(arg1)) == 0;
 }
 
 bool
-bitne (bits8 *arg1, bits8 *arg2)
+bitne(bits8 *arg1, bits8 *arg2)
 {
-  int bitlen1,
-    bitlen2;
-
-  if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
-    return (bool) 0;
-  bitlen1 = VARBITLEN(arg1);
-  bitlen2 = VARBITLEN(arg2);
-  if (bitlen1 != bitlen2)
-    return (bool) 1;
-  
-  /* bit strings are always stored in a full number of bytes */
-  return memcmp((void *)VARBITS(arg1),(void *)VARBITS(arg2),
-       VARBITBYTES(arg1)) != 0;
+   int         bitlen1,
+               bitlen2;
+
+   if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+       return (bool) 0;
+   bitlen1 = VARBITLEN(arg1);
+   bitlen2 = VARBITLEN(arg2);
+   if (bitlen1 != bitlen2)
+       return (bool) 1;
+
+   /* bit strings are always stored in a full number of bytes */
+   return memcmp((void *) VARBITS(arg1), (void *) VARBITS(arg2),
+                 VARBITBYTES(arg1)) != 0;
 }
 
 /* bitcmp
- * 
+ *
  * Compares two bitstrings and returns -1, 0, 1 depending on whether the first
  * string is smaller, equal, or bigger than the second. All bits are considered
  * and additional zero bits may make one string smaller/larger than the other,
  * even if their zero-padded values would be the same.
- *   Anything is equal to undefined.
+ *  Anything is equal to undefined.
  */
-int 
-bitcmp (bits8 *arg1, bits8 *arg2)
+int
+bitcmp(bits8 *arg1, bits8 *arg2)
 {
-  int bitlen1, bytelen1,
-    bitlen2, bytelen2;
-  int cmp;
-
-  if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
-    return (bool) 0;
-  bytelen1 = VARBITBYTES(arg1);  
-  bytelen2 = VARBITBYTES(arg2);
-  
-  cmp = memcmp(VARBITS(arg1),VARBITS(arg2),Min(bytelen1,bytelen2));
-  if (cmp==0) {
-    bitlen1 = VARBITLEN(arg1);
-    bitlen2 = VARBITLEN(arg2);
-    if (bitlen1 != bitlen2) 
-      return bitlen1 < bitlen2 ? -1 : 1;
-  }
-  return cmp;
+   int         bitlen1,
+               bytelen1,
+               bitlen2,
+               bytelen2;
+   int         cmp;
+
+   if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+       return (bool) 0;
+   bytelen1 = VARBITBYTES(arg1);
+   bytelen2 = VARBITBYTES(arg2);
+
+   cmp = memcmp(VARBITS(arg1), VARBITS(arg2), Min(bytelen1, bytelen2));
+   if (cmp == 0)
+   {
+       bitlen1 = VARBITLEN(arg1);
+       bitlen2 = VARBITLEN(arg2);
+       if (bitlen1 != bitlen2)
+           return bitlen1 < bitlen2 ? -1 : 1;
+   }
+   return cmp;
 }
 
 bool
-bitlt (bits8 *arg1, bits8 *arg2)
+bitlt(bits8 *arg1, bits8 *arg2)
 {
-  return (bool) (bitcmp(arg1,arg2) == -1);
+   return (bool) (bitcmp(arg1, arg2) == -1);
 }
 
 bool
-bitle (bits8 *arg1, bits8 *arg2)
+bitle(bits8 *arg1, bits8 *arg2)
 {
-  return (bool) (bitcmp(arg1,arg2) <= 0);
+   return (bool) (bitcmp(arg1, arg2) <= 0);
 }
 
 bool
-bitge (bits8 *arg1, bits8 *arg2)
+bitge(bits8 *arg1, bits8 *arg2)
 {
-  return (bool) (bitcmp(arg1,arg2) >= 0);
+   return (bool) (bitcmp(arg1, arg2) >= 0);
 }
 
 bool
-bitgt (bits8 *arg1, bits8 *arg2)
+bitgt(bits8 *arg1, bits8 *arg2)
 {
-  return (bool) (bitcmp(arg1,arg2) == 1);
+   return (bool) (bitcmp(arg1, arg2) == 1);
 }
 
 /* bitcat
  * Concatenation of bit strings
  */
 bits8 *
-bitcat (bits8 *arg1, bits8 *arg2)
+bitcat(bits8 *arg1, bits8 *arg2)
 {
-  int bitlen1, bitlen2, bytelen, bit1pad, bit2shift;
-  bits8 *result;
-  bits8 *pr, *pa;
-
-  if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
-    return NULL;
-
-  bitlen1 = VARBITLEN(arg1);
-  bitlen2 = VARBITLEN(arg2);
-
-  bytelen = VARBITDATALEN(bitlen1+bitlen2);
-  
-  result = (bits8 *) palloc(bytelen*sizeof(bits8));
-  VARSIZE(result) = bytelen;
-  VARBITLEN(result) = bitlen1+bitlen2;
-  printf("%d %d %d \n",VARBITBYTES(arg1),VARBITLEN(arg1),VARBITPAD(arg1));
-  /* Copy the first bitstring in */
-  memcpy(VARBITS(result),VARBITS(arg1),VARBITBYTES(arg1));
-  /* Copy the second bit string */
-  bit1pad = VARBITPAD(arg1);
-  if (bit1pad==0) 
-    {
-      memcpy(VARBITS(result)+VARBITBYTES(arg1),VARBITS(arg2),
-        VARBITBYTES(arg2));
-    }
-  else if (bitlen2>0)
-    {
-      /* We need to shift all the results to fit */
-      bit2shift = BITSPERBYTE - bit1pad;
-      pa = VARBITS(arg2);
-      pr = VARBITS(result)+VARBITBYTES(arg1)-1;
-      for ( ; pa < VARBITEND(arg2); pa++) {
-   *pr |= ((*pa >> bit2shift) & BITMASK);
-   pr++;
-   if (pr < VARBITEND(result))
-     *pr = (*pa << bit1pad) & BITMASK;
-      }
-    }
-
-  return result;
+   int         bitlen1,
+               bitlen2,
+               bytelen,
+               bit1pad,
+               bit2shift;
+   bits8      *result;
+   bits8      *pr,
+              *pa;
+
+   if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+       return NULL;
+
+   bitlen1 = VARBITLEN(arg1);
+   bitlen2 = VARBITLEN(arg2);
+
+   bytelen = VARBITDATALEN(bitlen1 + bitlen2);
+
+   result = (bits8 *) palloc(bytelen * sizeof(bits8));
+   VARSIZE(result) = bytelen;
+   VARBITLEN(result) = bitlen1 + bitlen2;
+   printf("%d %d %d \n", VARBITBYTES(arg1), VARBITLEN(arg1), VARBITPAD(arg1));
+   /* Copy the first bitstring in */
+   memcpy(VARBITS(result), VARBITS(arg1), VARBITBYTES(arg1));
+   /* Copy the second bit string */
+   bit1pad = VARBITPAD(arg1);
+   if (bit1pad == 0)
+   {
+       memcpy(VARBITS(result) + VARBITBYTES(arg1), VARBITS(arg2),
+              VARBITBYTES(arg2));
+   }
+   else if (bitlen2 > 0)
+   {
+       /* We need to shift all the results to fit */
+       bit2shift = BITSPERBYTE - bit1pad;
+       pa = VARBITS(arg2);
+       pr = VARBITS(result) + VARBITBYTES(arg1) - 1;
+       for (; pa < VARBITEND(arg2); pa++)
+       {
+           *pr |= ((*pa >> bit2shift) & BITMASK);
+           pr++;
+           if (pr < VARBITEND(result))
+               *pr = (*pa << bit1pad) & BITMASK;
+       }
+   }
+
+   return result;
 }
 
 /* bitsubstr
- * retrieve a substring from the bit string. 
+ * retrieve a substring from the bit string.
  * Note, s is 1-based.
  * SQL draft 6.10 9)
  */
-bits8 * 
-bitsubstr (bits8 *arg, int32 s, int32 l)
+bits8 *
+bitsubstr(bits8 *arg, int32 s, int32 l)
 {
-  int bitlen,
-    rbitlen,
-    len,
-    ipad = 0,
-    ishift,
-    i;
-  int e, s1, e1;
-  bits8 * result;
-  bits8 mask, *r, *ps;
-
-  if (!PointerIsValid(arg))
-    return NULL;
-
-  bitlen = VARBITLEN(arg);
-  e = s+l;
-  s1 = Max(s,1);
-  e1 = Min(e,bitlen+1);
-  if (s1>bitlen || e1<1) 
-    {
-      /* Need to return a null string */
-      len = VARBITDATALEN(0);
-      result = (bits8 *) palloc(len);
-      VARBITLEN(result) = 0;
-      VARSIZE(result) = len;
-    } 
-  else 
-    {
-      /* OK, we've got a true substring starting at position s1-1 and 
-    ending at position e1-1 */
-      rbitlen = e1-s1;
-      len = VARBITDATALEN(rbitlen);
-      result = (bits8 *) palloc(len);
-      VARBITLEN(result) = rbitlen;
-      VARSIZE(result) = len;
-      len -= VARHDRSZ + VARBITHDRSZ;
-      /* Are we copying from a byte boundary? */
-      if ((s1-1)%BITSPERBYTE==0) 
+   int         bitlen,
+               rbitlen,
+               len,
+               ipad = 0,
+               ishift,
+               i;
+   int         e,
+               s1,
+               e1;
+   bits8      *result;
+   bits8       mask,
+              *r,
+              *ps;
+
+   if (!PointerIsValid(arg))
+       return NULL;
+
+   bitlen = VARBITLEN(arg);
+   e = s + l;
+   s1 = Max(s, 1);
+   e1 = Min(e, bitlen + 1);
+   if (s1 > bitlen || e1 < 1)
    {
-     /* Yep, we are copying bytes */
-     memcpy(VARBITS(result),VARBITS(arg)+(s1-1)/BITSPERBYTE,len);
-   } 
-      else 
-   {
-     /* Figure out how much we need to shift the sequence by */
-     ishift = (s1-1)%BITSPERBYTE;
-     r = VARBITS(result);
-     ps = VARBITS(arg) + (s1-1)/BITSPERBYTE;
-     for (i=0; i<len; i++) 
-       {
-         *r = (*ps <<ishift) & BITMASK;
-         if ((++ps) < VARBITEND(arg))
-       *r |= *ps >>(BITSPERBYTE-ishift);
-         r++;
-       }
+       /* Need to return a null string */
+       len = VARBITDATALEN(0);
+       result = (bits8 *) palloc(len);
+       VARBITLEN(result) = 0;
+       VARSIZE(result) = len;
    }
-      /* Do we need to pad at the end? */
-      ipad = VARBITPAD(result);
-      if (ipad > 0) 
+   else
    {
-     mask = BITMASK << ipad;
-     *(VARBITS(result) + len - 1) &= mask;
+
+       /*
+        * OK, we've got a true substring starting at position s1-1 and
+        * ending at position e1-1
+        */
+       rbitlen = e1 - s1;
+       len = VARBITDATALEN(rbitlen);
+       result = (bits8 *) palloc(len);
+       VARBITLEN(result) = rbitlen;
+       VARSIZE(result) = len;
+       len -= VARHDRSZ + VARBITHDRSZ;
+       /* Are we copying from a byte boundary? */
+       if ((s1 - 1) % BITSPERBYTE == 0)
+       {
+           /* Yep, we are copying bytes */
+           memcpy(VARBITS(result), VARBITS(arg) + (s1 - 1) / BITSPERBYTE, len);
+       }
+       else
+       {
+           /* Figure out how much we need to shift the sequence by */
+           ishift = (s1 - 1) % BITSPERBYTE;
+           r = VARBITS(result);
+           ps = VARBITS(arg) + (s1 - 1) / BITSPERBYTE;
+           for (i = 0; i < len; i++)
+           {
+               *r = (*ps << ishift) & BITMASK;
+               if ((++ps) < VARBITEND(arg))
+                   *r |= *ps >> (BITSPERBYTE - ishift);
+               r++;
+           }
+       }
+       /* Do we need to pad at the end? */
+       ipad = VARBITPAD(result);
+       if (ipad > 0)
+       {
+           mask = BITMASK << ipad;
+           *(VARBITS(result) + len - 1) &= mask;
+       }
    }
-    }
 
-  return result;
+   return result;
 }
 
 /* bitand
@@ -598,32 +656,32 @@ bitsubstr (bits8 *arg, int32 s, int32 l)
  * truncated to the shorter bit string
  */
 bits8 *
-bitand (bits8 * arg1, bits8 * arg2)
+bitand(bits8 *arg1, bits8 *arg2)
 {
-  int len,
-    i;
-  bits8 *result;
-  bits8 *p1, 
-    *p2, 
-    *r;
-
-  if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
-    return (bool) 0;
-
-  len = Min(VARSIZE(arg1),VARSIZE(arg2));
-  result = (bits8 *) palloc(len);
-  VARSIZE(result) = len;
-  VARBITLEN(result) = Min(VARBITLEN(arg1),VARBITLEN(arg2));
-
-  p1 = (bits8 *) VARBITS(arg1);
-  p2 = (bits8 *) VARBITS(arg2);
-  r = (bits8 *) VARBITS(result);
-  for (i=0; i<Min(VARBITBYTES(arg1),VARBITBYTES(arg2)); i++)
-    *r++ = *p1++ & *p2++;
-  
-  /* Padding is not needed as & of 0 pad is 0 */
-  
-  return result;
+   int         len,
+               i;
+   bits8      *result;
+   bits8      *p1,
+              *p2,
+              *r;
+
+   if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+       return (bool) 0;
+
+   len = Min(VARSIZE(arg1), VARSIZE(arg2));
+   result = (bits8 *) palloc(len);
+   VARSIZE(result) = len;
+   VARBITLEN(result) = Min(VARBITLEN(arg1), VARBITLEN(arg2));
+
+   p1 = (bits8 *) VARBITS(arg1);
+   p2 = (bits8 *) VARBITS(arg2);
+   r = (bits8 *) VARBITS(result);
+   for (i = 0; i < Min(VARBITBYTES(arg1), VARBITBYTES(arg2)); i++)
+       *r++ = *p1++ & *p2++;
+
+   /* Padding is not needed as & of 0 pad is 0 */
+
+   return result;
 }
 
 /* bitor
@@ -631,35 +689,35 @@ bitand (bits8 * arg1, bits8 * arg2)
  * truncated to the shorter bit string.
  */
 bits8 *
-bitor (bits8 * arg1, bits8 * arg2)
+bitor(bits8 *arg1, bits8 *arg2)
 {
-  int len,
-    i;
-  bits8 *result;
-  bits8 *p1, 
-    *p2, 
-    *r;
-  bits8 mask;
-
-  if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
-    return (bool) 0;
-
-  len = Min(VARSIZE(arg1),VARSIZE(arg2));
-  result = (bits8 *) palloc(len);
-  VARSIZE(result) = len;
-  VARBITLEN(result) = Min(VARBITLEN(arg1),VARBITLEN(arg2));
-
-  p1 = (bits8 *) VARBITS(arg1);
-  p2 = (bits8 *) VARBITS(arg2);
-  r = (bits8 *) VARBITS(result);
-  for (i=0; i<Min(VARBITBYTES(arg1),VARBITBYTES(arg2)); i++)
-    *r++ = *p1++ | *p2++;
-
-  /* Pad the result */
-  mask = BITMASK << VARBITPAD(result);
-  *r &= mask;
-  
-  return result;
+   int         len,
+               i;
+   bits8      *result;
+   bits8      *p1,
+              *p2,
+              *r;
+   bits8       mask;
+
+   if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+       return (bool) 0;
+
+   len = Min(VARSIZE(arg1), VARSIZE(arg2));
+   result = (bits8 *) palloc(len);
+   VARSIZE(result) = len;
+   VARBITLEN(result) = Min(VARBITLEN(arg1), VARBITLEN(arg2));
+
+   p1 = (bits8 *) VARBITS(arg1);
+   p2 = (bits8 *) VARBITS(arg2);
+   r = (bits8 *) VARBITS(result);
+   for (i = 0; i < Min(VARBITBYTES(arg1), VARBITBYTES(arg2)); i++)
+       *r++ = *p1++ | *p2++;
+
+   /* Pad the result */
+   mask = BITMASK << VARBITPAD(result);
+   *r &= mask;
+
+   return result;
 }
 
 /* bitxor
@@ -667,160 +725,167 @@ bitor (bits8 * arg1, bits8 * arg2)
  * truncated to the shorter bit string.
  */
 bits8 *
-bitxor (bits8 * arg1, bits8 * arg2)
+bitxor(bits8 *arg1, bits8 *arg2)
 {
-  int len,
-    i;
-  bits8 *result;
-  bits8 *p1, 
-    *p2, 
-    *r;
-  bits8 mask;
-
-  if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
-    return (bool) 0;
-
-  len = Min(VARSIZE(arg1),VARSIZE(arg2));
-  result = (bits8 *) palloc(len);
-  VARSIZE(result) = len;
-  VARBITLEN(result) = Min(VARBITLEN(arg1),VARBITLEN(arg2));
-
-  p1 = (bits8 *) VARBITS(arg1);
-  p2 = (bits8 *) VARBITS(arg2);
-  r = (bits8 *) VARBITS(result);
-  for (i=0; i<Min(VARBITBYTES(arg1),VARBITBYTES(arg2)); i++)
-    {
-      *r++ = *p1++ ^ *p2++;
-    }
-
-  /* Pad the result */
-  mask = BITMASK << VARBITPAD(result);
-  *r &= mask;
-  
-  return result;
+   int         len,
+               i;
+   bits8      *result;
+   bits8      *p1,
+              *p2,
+              *r;
+   bits8       mask;
+
+   if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+       return (bool) 0;
+
+   len = Min(VARSIZE(arg1), VARSIZE(arg2));
+   result = (bits8 *) palloc(len);
+   VARSIZE(result) = len;
+   VARBITLEN(result) = Min(VARBITLEN(arg1), VARBITLEN(arg2));
+
+   p1 = (bits8 *) VARBITS(arg1);
+   p2 = (bits8 *) VARBITS(arg2);
+   r = (bits8 *) VARBITS(result);
+   for (i = 0; i < Min(VARBITBYTES(arg1), VARBITBYTES(arg2)); i++)
+       *r++ = *p1++ ^ *p2++;
+
+   /* Pad the result */
+   mask = BITMASK << VARBITPAD(result);
+   *r &= mask;
+
+   return result;
 }
 
 /* bitnot
  * perform a logical NOT on a bit strings.
  */
 bits8 *
-bitnot (bits8 * arg)
+bitnot(bits8 *arg)
 {
-  bits8 *result;
-  bits8 *p, 
-    *r;
-  bits8 mask;
-
-  if (!PointerIsValid(arg))
-    return (bool) 0;
-
-  result = (bits8 *) palloc(VARSIZE(arg));
-  VARSIZE(result) = VARSIZE(arg);
-  VARBITLEN(result) = VARBITLEN(arg);
-
-  p = (bits8 *) VARBITS(arg);
-  r = (bits8 *) VARBITS(result);
-  for ( ; p < VARBITEND(arg); p++, r++)
-    *r = ~*p;
-
-  /* Pad the result */
-  mask = BITMASK << VARBITPAD(result);
-  *r &= mask;
-  
-  return result;
+   bits8      *result;
+   bits8      *p,
+              *r;
+   bits8       mask;
+
+   if (!PointerIsValid(arg))
+       return (bool) 0;
+
+   result = (bits8 *) palloc(VARSIZE(arg));
+   VARSIZE(result) = VARSIZE(arg);
+   VARBITLEN(result) = VARBITLEN(arg);
+
+   p = (bits8 *) VARBITS(arg);
+   r = (bits8 *) VARBITS(result);
+   for (; p < VARBITEND(arg); p++, r++)
+       *r = ~*p;
+
+   /* Pad the result */
+   mask = BITMASK << VARBITPAD(result);
+   *r &= mask;
+
+   return result;
 }
 
 /* bitshiftleft
  * do a left shift (i.e. to the beginning of the string) of the bit string
  */
 bits8 *
-bitshiftleft (bits8 * arg, int shft)
+bitshiftleft(bits8 *arg, int shft)
 {
-  int byte_shift, ishift, len;
-  bits8 *result;
-  bits8 *p, 
-    *r;
-
-  if (!PointerIsValid(arg))
-    return (bool) 0;
-
-  /* Negative shift is a shift to the right */
-  if (shft < 0) 
-    return bitshiftright(arg, -shft);
-
-  result = (bits8 *) palloc(VARSIZE(arg));
-  VARSIZE(result) = VARSIZE(arg);
-  VARBITLEN(result) = VARBITLEN(arg);
-  r = (bits8 *) VARBITS(result);
-
-  byte_shift = shft/BITSPERBYTE;
-  ishift = shft % BITSPERBYTE;
-  p = ((bits8 *) VARBITS(arg)) + byte_shift;
-  
-  if (ishift == 0) {
-    /* Special case: we can do a memcpy */
-    len = VARBITBYTES(arg) - byte_shift;
-    memcpy(r, p, len);
-    memset(r+len, 0, byte_shift);
-  } else {
-    for ( ; p < VARBITEND(arg); r++) {
-      *r = *p <<ishift;
-      if ((++p) < VARBITEND(arg))
-   *r |= *p >>(BITSPERBYTE-ishift);
-    }
-    for ( ; r < VARBITEND(result) ; r++ ) 
-      *r = (bits8) 0;
-  }
-
-  return result;
+   int         byte_shift,
+               ishift,
+               len;
+   bits8      *result;
+   bits8      *p,
+              *r;
+
+   if (!PointerIsValid(arg))
+       return (bool) 0;
+
+   /* Negative shift is a shift to the right */
+   if (shft < 0)
+       return bitshiftright(arg, -shft);
+
+   result = (bits8 *) palloc(VARSIZE(arg));
+   VARSIZE(result) = VARSIZE(arg);
+   VARBITLEN(result) = VARBITLEN(arg);
+   r = (bits8 *) VARBITS(result);
+
+   byte_shift = shft / BITSPERBYTE;
+   ishift = shft % BITSPERBYTE;
+   p = ((bits8 *) VARBITS(arg)) + byte_shift;
+
+   if (ishift == 0)
+   {
+       /* Special case: we can do a memcpy */
+       len = VARBITBYTES(arg) - byte_shift;
+       memcpy(r, p, len);
+       memset(r + len, 0, byte_shift);
+   }
+   else
+   {
+       for (; p < VARBITEND(arg); r++)
+       {
+           *r = *p << ishift;
+           if ((++p) < VARBITEND(arg))
+               *r |= *p >> (BITSPERBYTE - ishift);
+       }
+       for (; r < VARBITEND(result); r++)
+           *r = (bits8) 0;
+   }
+
+   return result;
 }
 
 /* bitshiftright
  * do a right shift (i.e. to the beginning of the string) of the bit string
  */
 bits8 *
-bitshiftright (bits8 * arg, int shft)
+bitshiftright(bits8 *arg, int shft)
 {
-  int byte_shift, ishift, len;
-  bits8 *result;
-  bits8 *p, 
-    *r;
-
-  if (!PointerIsValid(arg))
-    return (bits8 *) 0;
-
-  /* Negative shift is a shift to the left */
-  if (shft < 0) 
-    return bitshiftleft(arg, -shft);
-
-  result = (bits8 *) palloc(VARSIZE(arg));
-  VARSIZE(result) = VARSIZE(arg);
-  VARBITLEN(result) = VARBITLEN(arg);
-  r = (bits8 *) VARBITS(result);
-
-  byte_shift = shft/BITSPERBYTE;
-  ishift = shft % BITSPERBYTE;
-  p = (bits8 *) VARBITS(arg);
-
-  /* Set the first part of the result to 0 */
-  memset(r, 0, byte_shift);
-  
-  if (ishift == 0) 
-    {
-      /* Special case: we can do a memcpy */
-      len = VARBITBYTES(arg) - byte_shift;
-      memcpy(r+byte_shift, p, len);
-    } 
-  else 
-    {
-      r += byte_shift;
-      *r = 0;    /* Initialise first byte */
-      for ( ; r < VARBITEND(result); p++) {
-   *r |= *p >> ishift;
-   if ((++r) < VARBITEND(result))
-     *r = (*p <<(BITSPERBYTE-ishift)) & BITMASK;
-      }
-    }
-
-  return result;
+   int         byte_shift,
+               ishift,
+               len;
+   bits8      *result;
+   bits8      *p,
+              *r;
+
+   if (!PointerIsValid(arg))
+       return (bits8 *) 0;
+
+   /* Negative shift is a shift to the left */
+   if (shft < 0)
+       return bitshiftleft(arg, -shft);
+
+   result = (bits8 *) palloc(VARSIZE(arg));
+   VARSIZE(result) = VARSIZE(arg);
+   VARBITLEN(result) = VARBITLEN(arg);
+   r = (bits8 *) VARBITS(result);
+
+   byte_shift = shft / BITSPERBYTE;
+   ishift = shft % BITSPERBYTE;
+   p = (bits8 *) VARBITS(arg);
+
+   /* Set the first part of the result to 0 */
+   memset(r, 0, byte_shift);
+
+   if (ishift == 0)
+   {
+       /* Special case: we can do a memcpy */
+       len = VARBITBYTES(arg) - byte_shift;
+       memcpy(r + byte_shift, p, len);
+   }
+   else
+   {
+       r += byte_shift;
+       *r = 0;                 /* Initialise first byte */
+       for (; r < VARBITEND(result); p++)
+       {
+           *r |= *p >> ishift;
+           if ((++r) < VARBITEND(result))
+               *r = (*p << (BITSPERBYTE - ishift)) & BITMASK;
+       }
+   }
+
+   return result;
 }
index 0b7e3308c482c20608d84cd17fbf170d7ab2a86c..ca7202b4c802dc64b414b54e142b9e79c2348b9a 100644 (file)
@@ -2,7 +2,7 @@
 #include <ctype.h>
 #include <errno.h>
 
-#include <float.h>                              /* faked on sunos4 */
+#include <float.h>             /* faked on sunos4 */
 
 #include <math.h>
 
@@ -10,7 +10,7 @@
 #ifdef HAVE_LIMITS_H
 #include <limits.h>
 #ifndef MAXINT
-#define MAXINT            INT_MAX
+#define MAXINT           INT_MAX
 #endif
 #else
 #ifdef HAVE_VALUES_H
@@ -22,7 +22,7 @@
 #include "utils/builtins.h"
 
 
-#define HEXDIG(z)    (z)<10 ? ((z)+'0') : ((z)-10+'A')
+#define HEXDIG(z)   (z)<10 ? ((z)+'0') : ((z)-10+'A')
 
 /* Modeled on struct varlena from postgres.h, bu data type is bits8 */
 struct varbita
@@ -49,25 +49,25 @@ struct varbita
 #define VARBITEND(PTR)     ((bits8 *) (PTR + VARSIZE(PTR)))
 /* Mask that will cover exactly one byte, i.e. BITSPERBYTE bits */
 #define BITMASK            0xFF
-#define BITHIGH                 0x80
+#define BITHIGH                    0x80
 
 
-bits8 * zpbitin(char *s, int dummy,  int32 atttypmod);
-char zpbitout(bits8 *s);
-char zpbitsout(bits8 *s);
-bits8 * varbitin(char *s, int dummy,  int32 atttypmod);
-bool biteq (bits8 *arg1, bits8 *arg2);
-bool bitne (bits8 *arg1, bits8 *arg2);
-bool bitge (bits8 *arg1, bits8 *arg2);
-bool bitgt (bits8 *arg1, bits8 *arg2);
-bool bitle (bits8 *arg1, bits8 *arg2);
-bool bitlt (bits8 *arg1, bits8 *arg2);
-int bitcmp (bits8 *arg1, bits8 *arg2);
-bits8 * bitand (bits8 * arg1, bits8 * arg2);
-bits8 * bitor (bits8 * arg1, bits8 * arg2);
-bits8 * bitxor (bits8 * arg1, bits8 * arg2);
-bits8 * bitnot (bits8 * arg);
-bits8 * bitshiftright (bits8 * arg, int shft);
-bits8 * bitshiftleft (bits8 * arg, int shft);
-bits8 * bitcat (bits8 *arg1, bits8 *arg2);
-bits8 * bitsubstr (bits8 *arg, int32 s, int32 l);
+bits8     *zpbitin(char *s, int dummy, int32 atttypmod);
+char      *zpbitout(bits8 *s);
+char      *zpbitsout(bits8 *s);
+bits8     *varbitin(char *s, int dummy, int32 atttypmod);
+bool       biteq(bits8 *arg1, bits8 *arg2);
+bool       bitne(bits8 *arg1, bits8 *arg2);
+bool       bitge(bits8 *arg1, bits8 *arg2);
+bool       bitgt(bits8 *arg1, bits8 *arg2);
+bool       bitle(bits8 *arg1, bits8 *arg2);
+bool       bitlt(bits8 *arg1, bits8 *arg2);
+int            bitcmp(bits8 *arg1, bits8 *arg2);
+bits8     *bitand(bits8 *arg1, bits8 *arg2);
+bits8     *bitor(bits8 *arg1, bits8 *arg2);
+bits8     *bitxor(bits8 *arg1, bits8 *arg2);
+bits8     *bitnot(bits8 *arg);
+bits8     *bitshiftright(bits8 *arg, int shft);
+bits8     *bitshiftleft(bits8 *arg, int shft);
+bits8     *bitcat(bits8 *arg1, bits8 *arg2);
+bits8     *bitsubstr(bits8 *arg, int32 s, int32 l);
index 29b7debd03cd45c9a813b92bb7dee1588174aef0..bd79a849a5095d4ba8a638a0a06893810b9e7d77 100644 (file)
@@ -2,21 +2,23 @@
 
 #include "varbit.h"
 
-bits8 * varbit_in (char * s);
-char * varbit_out (bits8 *s);
+bits8     *varbit_in(char *s);
+char      *varbit_out(bits8 *s);
 
 bits8 *
-varbit_in (char * s) {
-  return varbitin (s, 0, -1);
+varbit_in(char *s)
+{
+   return varbitin(s, 0, -1);
 }
 
-/*char * 
+/*char *
 varbit_out (bits8 *s) {
   return zpbitout(s);
 }
 */
 
-char * 
-varbit_out (bits8 *s) {
-  return zpbitsout(s);
+char *
+varbit_out(bits8 *s)
+{
+   return zpbitsout(s);
 }
index f07f5c5b8333654b89099b7fe961137efe53905d..7725f6bbd306f027ad8cfd1e8ac35dd00e13a6a1 100644 (file)
 #include "varbit.h"
 #include <stdio.h>
 
-void print_details (unsigned char *s);
+void       print_details(unsigned char *s);
+
+const int  numb = 8;
 
-const int numb = 8;
 /*
 const char *b[] = { "B0010", "B11011011", "B0001", "X3F12", "X27", "B",
-                    "X11", "B100111"};
+                   "X11", "B100111"};
 int atttypmod[] = {-1, -1, -1,-1,-1,-1,-1,-1 };
 */
-const char *b[] = { "B0010", "B11011011", "B10001", "X3D12", "X27", "B",
-                    "X11", "B100111"};
-int atttypmod[] = { 7, 9, 6, 18, 11, 6, -1, -1 };
+const char *b[] = {"B0010", "B11011011", "B10001", "X3D12", "X27", "B",
+"X11", "B100111"};
+int            atttypmod[] = {7, 9, 6, 18, 11, 6, -1, -1};
 
 
-void print_details (unsigned char *s) 
+void
+print_details(unsigned char *s)
 {
-  int i;
-  printf ("Length in bytes    : %d\n",VARSIZE(s));
-  printf ("Length of bitstring: %d\n",VARBITLEN(s));
-  for (i=8; i<VARSIZE(s); i++) 
-    printf ("%X%X ",s[i]>>4,s[i]&0xF);
-  printf("\n");
+   int         i;
+
+   printf("Length in bytes    : %d\n", VARSIZE(s));
+   printf("Length of bitstring: %d\n", VARBITLEN(s));
+   for (i = 8; i < VARSIZE(s); i++)
+       printf("%X%X ", s[i] >> 4, s[i] & 0xF);
+   printf("\n");
 }
 
 int
-main () 
+main()
 {
-  int i, j;
-  char *s[numb];
-
-  for (i=0; i<numb; i++) {
-    printf ("Input: %s\n",b[i]);
-    s[i] = zpbitin(b[i], 0, atttypmod[i]);
-    //print_details(s[i]);
-    printf ("%s = %s\n",zpbitout(s[i]),zpbitsout(s[i]));
-  }
-
-  printf ("\nCOMPARISONS:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s <=> %s = %d\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        bitcmp(s[i],s[j]));
-
-  printf ("\nCONCATENATION:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s || %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitcat(s[i],s[j])));
-
-  printf("\nSUBSTR:\n");
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),1,8,
-    zpbitsout(bitsubstr(s[3],1,8)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),9,8,
-    zpbitsout(bitsubstr(s[3],9,8)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),1,9,
-    zpbitsout(bitsubstr(s[3],1,9)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),3,5,
-    zpbitsout(bitsubstr(s[3],3,5)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),3,9,
-    zpbitsout(bitsubstr(s[3],3,9)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),3,17,
-    zpbitsout(bitsubstr(s[3],3,17)));
-  printf ("\nLOGICAL AND:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s & %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitand(s[i],s[j])));
-
-  printf ("\nLOGICAL OR:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s | %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitor(s[i],s[j])));
-
-  printf ("\nLOGICAL XOR:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s ^ %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitxor(s[i],s[j])));
-  
-  printf ("\nLOGICAL NOT:\n");
-  for (i=0; i<numb; i++)
-    printf("~%s = %s\n",zpbitsout(s[i]),zpbitsout(bitnot(s[i])));
-
-
-  printf ("\nSHIFT LEFT:\n");
-  for (i=0; i<numb; i++) {
-    printf("%s\n",zpbitsout(s[i]));
-    for (j=0; j<=VARBITLEN(s[i]); j++)
-      printf("\t%3d\t%s\n",j,zpbitsout(bitshiftleft(s[i],j)));
-  }
-
-  printf ("\nSHIFT RIGHT:\n");
-  for (i=0; i<numb; i++) {
-    printf("%s\n",zpbitsout(s[i]));
-    for (j=0; j<=VARBITLEN(s[i]); j++)
-      printf("\t%3d\t%s\n",j,zpbitsout(bitshiftright(s[i],j)));
-  }
-
-  printf ("\n\n ********** VARYING **********\n");
-  for (i=0; i<numb; i++) {
-    printf ("Input: %s\n",b[i]);
-    s[i] = varbitin(b[i], 0, atttypmod[i]);
-    /*print_details(s);*/
-    printf ("%s\n",zpbitout(s[i]));
-    printf ("%s\n",zpbitsout(s[i]));
-  }
-
-  printf ("\nCOMPARISONS:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s <=> %s = %d\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        bitcmp(s[i],s[j]));
-
-  printf ("\nCONCATENATION:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s || %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitcat(s[i],s[j])));
-
-  printf("\nSUBSTR:\n");
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),1,8,
-    zpbitsout(bitsubstr(s[3],1,8)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),9,8,
-    zpbitsout(bitsubstr(s[3],9,8)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),1,9,
-    zpbitsout(bitsubstr(s[3],1,9)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),3,5,
-    zpbitsout(bitsubstr(s[3],3,5)));
-  printf("%s (%d,%d) => %s\n",zpbitsout(s[3]),3,9,
-    zpbitsout(bitsubstr(s[3],3,9)));
-  printf("%s (%d,%d) => %s (%s)\n",zpbitsout(s[3]),3,17,
-    zpbitsout(bitsubstr(s[3],3,17)),zpbitsout(bitsubstr(s[3],3,17)));
-  printf ("\nLOGICAL AND:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s & %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitand(s[i],s[j])));
-
-  printf ("\nLOGICAL OR:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s | %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitor(s[i],s[j])));
-
-  printf ("\nLOGICAL XOR:\n");
-  for (i=0; i<numb; i++)
-    for (j=i+1; j<numb; j++)
-      printf("%s ^ %s = %s\n",zpbitsout(s[i]),zpbitsout(s[j]),
-        zpbitsout(bitxor(s[i],s[j])));
-  
-  printf ("\nLOGICAL NOT:\n");
-  for (i=0; i<numb; i++)
-    printf("~%s = %s\n",zpbitsout(s[i]),zpbitsout(bitnot(s[i])));
-
-
-  printf ("\nSHIFT LEFT:\n");
-  for (i=0; i<numb; i++) {
-    printf("%s\n",zpbitsout(s[i]));
-    for (j=0; j<=VARBITLEN(s[i]); j++)
-      printf("\t%3d\t%s\n",j,zpbitsout(bitshiftleft(s[i],j)));
-  }
-
-  printf ("\nSHIFT RIGHT:\n");
-  for (i=0; i<numb; i++) {
-    printf("%s\n",zpbitsout(s[i]));
-    for (j=0; j<=VARBITLEN(s[i]); j++)
-      printf("\t%3d\t%s\n",j,zpbitsout(bitshiftright(s[i],j)));
-  }
+   int         i,
+               j;
+   char       *s[numb];
+
+   for (i = 0; i < numb; i++)
+   {
+       printf("Input: %s\n", b[i]);
+       s[i] = zpbitin(b[i], 0, atttypmod[i]);
+       //print_details(s[i]);
+       printf("%s = %s\n", zpbitout(s[i]), zpbitsout(s[i]));
+   }
+
+   printf("\nCOMPARISONS:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s <=> %s = %d\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  bitcmp(s[i], s[j]));
+
+   printf("\nCONCATENATION:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s || %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitcat(s[i], s[j])));
+
+   printf("\nSUBSTR:\n");
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 1, 8,
+          zpbitsout(bitsubstr(s[3], 1, 8)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 9, 8,
+          zpbitsout(bitsubstr(s[3], 9, 8)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 1, 9,
+          zpbitsout(bitsubstr(s[3], 1, 9)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 3, 5,
+          zpbitsout(bitsubstr(s[3], 3, 5)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 3, 9,
+          zpbitsout(bitsubstr(s[3], 3, 9)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 3, 17,
+          zpbitsout(bitsubstr(s[3], 3, 17)));
+   printf("\nLOGICAL AND:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s & %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitand(s[i], s[j])));
+
+   printf("\nLOGICAL OR:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s | %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitor(s[i], s[j])));
+
+   printf("\nLOGICAL XOR:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s ^ %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitxor(s[i], s[j])));
+
+   printf("\nLOGICAL NOT:\n");
+   for (i = 0; i < numb; i++)
+       printf("~%s = %s\n", zpbitsout(s[i]), zpbitsout(bitnot(s[i])));
+
+
+   printf("\nSHIFT LEFT:\n");
+   for (i = 0; i < numb; i++)
+   {
+       printf("%s\n", zpbitsout(s[i]));
+       for (j = 0; j <= VARBITLEN(s[i]); j++)
+           printf("\t%3d\t%s\n", j, zpbitsout(bitshiftleft(s[i], j)));
+   }
+
+   printf("\nSHIFT RIGHT:\n");
+   for (i = 0; i < numb; i++)
+   {
+       printf("%s\n", zpbitsout(s[i]));
+       for (j = 0; j <= VARBITLEN(s[i]); j++)
+           printf("\t%3d\t%s\n", j, zpbitsout(bitshiftright(s[i], j)));
+   }
+
+   printf("\n\n ********** VARYING **********\n");
+   for (i = 0; i < numb; i++)
+   {
+       printf("Input: %s\n", b[i]);
+       s[i] = varbitin(b[i], 0, atttypmod[i]);
+       /* print_details(s); */
+       printf("%s\n", zpbitout(s[i]));
+       printf("%s\n", zpbitsout(s[i]));
+   }
+
+   printf("\nCOMPARISONS:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s <=> %s = %d\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  bitcmp(s[i], s[j]));
+
+   printf("\nCONCATENATION:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s || %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitcat(s[i], s[j])));
+
+   printf("\nSUBSTR:\n");
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 1, 8,
+          zpbitsout(bitsubstr(s[3], 1, 8)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 9, 8,
+          zpbitsout(bitsubstr(s[3], 9, 8)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 1, 9,
+          zpbitsout(bitsubstr(s[3], 1, 9)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 3, 5,
+          zpbitsout(bitsubstr(s[3], 3, 5)));
+   printf("%s (%d,%d) => %s\n", zpbitsout(s[3]), 3, 9,
+          zpbitsout(bitsubstr(s[3], 3, 9)));
+   printf("%s (%d,%d) => %s (%s)\n", zpbitsout(s[3]), 3, 17,
+   zpbitsout(bitsubstr(s[3], 3, 17)), zpbitsout(bitsubstr(s[3], 3, 17)));
+   printf("\nLOGICAL AND:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s & %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitand(s[i], s[j])));
+
+   printf("\nLOGICAL OR:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s | %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitor(s[i], s[j])));
+
+   printf("\nLOGICAL XOR:\n");
+   for (i = 0; i < numb; i++)
+       for (j = i + 1; j < numb; j++)
+           printf("%s ^ %s = %s\n", zpbitsout(s[i]), zpbitsout(s[j]),
+                  zpbitsout(bitxor(s[i], s[j])));
+
+   printf("\nLOGICAL NOT:\n");
+   for (i = 0; i < numb; i++)
+       printf("~%s = %s\n", zpbitsout(s[i]), zpbitsout(bitnot(s[i])));
+
+
+   printf("\nSHIFT LEFT:\n");
+   for (i = 0; i < numb; i++)
+   {
+       printf("%s\n", zpbitsout(s[i]));
+       for (j = 0; j <= VARBITLEN(s[i]); j++)
+           printf("\t%3d\t%s\n", j, zpbitsout(bitshiftleft(s[i], j)));
+   }
+
+   printf("\nSHIFT RIGHT:\n");
+   for (i = 0; i < numb; i++)
+   {
+       printf("%s\n", zpbitsout(s[i]));
+       for (j = 0; j <= VARBITLEN(s[i]); j++)
+           printf("\t%3d\t%s\n", j, zpbitsout(bitshiftright(s[i], j)));
+   }
 
 }
index c5b8bc25e9d2789611846cb849850b2e1b81270b..47991a8646d9a5c94e642585482ba9871f00bf6c 100644 (file)
@@ -36,7 +36,7 @@
  * Decode time string 00:00:00 through 24:00:00.
  */
 static int
-decode_24h_time(char *str, struct tm *tm, double *fsec)
+decode_24h_time(char *str, struct tm * tm, double *fsec)
 {
    char       *cp;
 
@@ -51,9 +51,7 @@ decode_24h_time(char *str, struct tm *tm, double *fsec)
        *fsec = 0;
    }
    else if (*cp != ':')
-   {
        return -1;
-   }
    else
    {
        str = cp + 1;
@@ -72,10 +70,10 @@ decode_24h_time(char *str, struct tm *tm, double *fsec)
    }
 
    /* do a sanity check */
-   if (   (tm->tm_hour < 0) || (tm->tm_hour > 24)
-       || (tm->tm_min  < 0) || (tm->tm_min  > 59)
-       || (tm->tm_sec  < 0) || (tm->tm_sec  > 59)
-       || (*fsec       < 0) )
+   if ((tm->tm_hour < 0) || (tm->tm_hour > 24)
+       || (tm->tm_min < 0) || (tm->tm_min > 59)
+       || (tm->tm_sec < 0) || (tm->tm_sec > 59)
+       || (*fsec < 0))
        return -1;
 
    return 0;
@@ -265,7 +263,7 @@ currentdate()
 int4
 date2mjd(DateADT val)
 {
-   int result;
+   int         result;
 
    result = val + JDATE_2000 - 2400000.5;
 
@@ -276,8 +274,8 @@ date2mjd(DateADT val)
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index ff2309d16f0543f4e080c282547ce427b492d8e1..c345f2852b8a16d1ac5d4bfb846e750d138e254b 100644 (file)
@@ -20,8 +20,8 @@ DateADT       currentdate(void);
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index 6745b5b8bb9a9e049c19e181b875f64e45fae7ab..302118689dc1b9a713c2192eb64823261ff9850f 100644 (file)
@@ -38,6 +38,7 @@ extern int    assertTest(int val);
 
 #ifdef ASSERT_CHECKING_TEST
 extern int assertEnable(int val);
+
 #endif
 
 int
@@ -84,7 +85,8 @@ active_listeners(text *relname)
    ScanKeyData key;
    Datum       d;
    bool        isnull;
-   int         len, pid;
+   int         len,
+               pid;
    int         count = 0;
    int         ourpid = getpid();
    char        listen_name[NAMEDATALEN];
@@ -92,8 +94,9 @@ active_listeners(text *relname)
    lRel = heap_openr(ListenerRelationName, AccessShareLock);
    tdesc = RelationGetDescr(lRel);
 
-   if (relname && (VARSIZE(relname) > VARHDRSZ)) {
-       len = MIN(VARSIZE(relname)-VARHDRSZ, NAMEDATALEN-1);
+   if (relname && (VARSIZE(relname) > VARHDRSZ))
+   {
+       len = MIN(VARSIZE(relname) - VARHDRSZ, NAMEDATALEN - 1);
        strncpy(listen_name, VARDATA(relname), len);
        listen_name[len] = '\0';
        ScanKeyEntryInitialize(&key, 0,
@@ -101,15 +104,16 @@ active_listeners(text *relname)
                               F_NAMEEQ,
                               PointerGetDatum(listen_name));
        sRel = heap_beginscan(lRel, 0, SnapshotNow, 1, &key);
-   } else {
-       sRel = heap_beginscan(lRel, 0, SnapshotNow, 0, (ScanKey)NULL);
    }
+   else
+       sRel = heap_beginscan(lRel, 0, SnapshotNow, 0, (ScanKey) NULL);
 
    while (HeapTupleIsValid(lTuple = heap_getnext(sRel, 0)))
    {
        d = heap_getattr(lTuple, Anum_pg_listener_pid, tdesc, &isnull);
        pid = DatumGetInt32(d);
-       if ((pid == ourpid) || (kill(pid, SIGTSTP) == 0)) {
+       if ((pid == ourpid) || (kill(pid, SIGTSTP) == 0))
+       {
            /* elog(NOTICE, "%d ok", pid); */
            count++;
        }
@@ -134,6 +138,7 @@ assert_test(int val)
 {
    return assertTest(val);
 }
+
 #endif
 #endif
 
@@ -141,8 +146,8 @@ assert_test(int val)
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index 139df3bc775cadc75e3a75cac7e2a812c601cd58..080f1147a887753f5fb2ab51667b213b086ccf53 100644 (file)
@@ -10,8 +10,10 @@ int          active_listeners(text *relname);
 
 #ifdef USE_ASSERT_CHECKING
 int            assert_enable(int val);
+
 #ifdef ASSERT_CHECKING_TEST
 int            assert_test(int val);
+
 #endif
 #endif
 
@@ -19,8 +21,8 @@ int           assert_test(int val);
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index afdcb4484c8d557359556ef1e9dfdbf64e4edfb4..7a98eb60a9c399472aad6ef52124144ef76899a1 100644 (file)
@@ -11,7 +11,7 @@
  * DEF_PGPORT is the TCP port number on which the Postmaster listens by
  * default.  This can be overriden by command options, environment variables,
  * and the postconfig hook. (set by build script)
-   */\r
+     */\r
 \r
 #define DEF_PGPORT "5432"\r
 \r
index ab5f0907167f727e87a6637dfe0120c12c56bad1..c2b027c9eccbd7f0b788ec173aaa7a85b8a7cc5e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * $Header: /cvsroot/pgsql/contrib/pgbench/pgbench.c,v 1.2 2000/04/08 18:32:24 tgl Exp $
+ * $Header: /cvsroot/pgsql/contrib/pgbench/pgbench.c,v 1.3 2000/04/12 17:14:27 momjian Exp $
  *
  * pgbench: a simple TPC-B like benchmark program for PostgreSQL
  * written by Tatsuo Ishii
 /********************************************************************
  * some configurable parameters */
 
-#define MAXCLIENTS 1024    /* max number of clients allowed */
+#define MAXCLIENTS 1024            /* max number of clients allowed */
 
-int nclients = 1;  /* default number of simulated clients */
-int nxacts = 10;   /* default number of transactions per clients */
+int            nclients = 1;       /* default number of simulated clients */
+int            nxacts = 10;        /* default number of transactions per
+                                * clients */
 
 /*
  * scaling factor. for example, tps = 10 will make 1000000 tuples of
  * accounts table.
  */
-int tps = 1;
+int            tps = 1;
 
 /*
  * end of configurable parameters
@@ -67,671 +68,753 @@ int tps = 1;
 
 #define nbranches  1
 #define ntellers   10
-#define    naccounts   100000
-
-int remains;       /* number of remained clients */
-
-typedef struct {
-  PGconn   *con;   /* connection handle to DB */
-  int  state;  /* state No. */
-  int  cnt;    /* xacts count */
-  int  ecnt;   /* error count */
-  int  listen; /* none 0 indicates that an async query has been sent */
-  int  aid;    /* account id for this transaction */
-  int  bid;    /* branch id for this transaction */
-  int  tid;    /* teller id for this transaction */
-  int  delta;
-  int  abalance;
-} CState;
-
-static void usage() {
-  fprintf(stderr,"usage: pgbench [-h hostname][-p port][-c nclients][-t ntransactions][-s scaling_factor][-n][-v][-S][-d][dbname]\n");
-  fprintf(stderr,"(initialize mode): pgbench -i [-h hostname][-p port][-s scaling_factor][-d][dbname]\n");
+#define naccounts  100000
+
+int            remains;            /* number of remained clients */
+
+typedef struct
+{
+   PGconn     *con;            /* connection handle to DB */
+   int         state;          /* state No. */
+   int         cnt;            /* xacts count */
+   int         ecnt;           /* error count */
+   int         listen;         /* none 0 indicates that an async query
+                                * has been sent */
+   int         aid;            /* account id for this transaction */
+   int         bid;            /* branch id for this transaction */
+   int         tid;            /* teller id for this transaction */
+   int         delta;
+   int         abalance;
+}          CState;
+
+static void
+usage()
+{
+   fprintf(stderr, "usage: pgbench [-h hostname][-p port][-c nclients][-t ntransactions][-s scaling_factor][-n][-v][-S][-d][dbname]\n");
+   fprintf(stderr, "(initialize mode): pgbench -i [-h hostname][-p port][-s scaling_factor][-d][dbname]\n");
 }
 
 /* random number generator */
-static int getrand(int min, int max) {
-  return(min+(int)(max*1.0*rand()/(RAND_MAX+1.0)));
+static int
+getrand(int min, int max)
+{
+   return (min + (int) (max * 1.0 * rand() / (RAND_MAX + 1.0)));
 }
 
 /* throw away response from backend */
-static void discard_response(CState *state) {
-  PGresult *res;
-  do {
-    res = PQgetResult(state->con);
-    if (res)
-      PQclear(res);
-  } while(res);
+static void
+discard_response(CState * state)
+{
+   PGresult   *res;
+
+   do
+   {
+       res = PQgetResult(state->con);
+       if (res)
+           PQclear(res);
+   } while (res);
 }
 
-static int check(CState *state, PGresult *res, int n, int good)
+static int
+check(CState * state, PGresult *res, int n, int good)
 {
-  CState *st = &state[n];
-
-  if (res && PQresultStatus(res) != good) {
-    fprintf(stderr,"Client %d aborted in state %d: %s",n,st->state,PQerrorMessage(st->con));
-    remains--; /* I've aborted */
-    PQfinish(st->con);
-    st->con = NULL;
-    return(-1);
-  }
-  return(0);
+   CState     *st = &state[n];
+
+   if (res && PQresultStatus(res) != good)
+   {
+       fprintf(stderr, "Client %d aborted in state %d: %s", n, st->state, PQerrorMessage(st->con));
+       remains--;              /* I've aborted */
+       PQfinish(st->con);
+       st->con = NULL;
+       return (-1);
+   }
+   return (0);
 }
 
 /* process a transaction */
-static void doOne(CState *state, int n, int debug) {
-  char sql[256];
-  PGresult   *res;
-  CState *st = &state[n];
-
-  if (st->listen) {    /* are we receiver? */
-    if (debug) {
-      fprintf(stderr,"client %d receiving\n",n);
-    }
-    while (PQisBusy(st->con) == TRUE) {
-      if (!PQconsumeInput(st->con)) {  /* there's something wrong */
-   fprintf(stderr, "Client %d aborted in state %d. Probably the backend died while processing.\n",n, st->state);
-   remains--;  /* I've aborted */
-   PQfinish(st->con);
-   st->con = NULL;
-   return;
-      }
-    }
-
-    switch (st->state) {
-    case 0:    /* response to "begin" */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_COMMAND_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-      break;
-    case 1:    /* response to "update accounts..." */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_COMMAND_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-      break;
-    case 2:    /* response to "select abalance ..." */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_TUPLES_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-      break;
-    case 3:    /* response to "update tellers ..." */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_COMMAND_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-      break;
-    case 4:    /* response to "update branches ..." */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_COMMAND_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-      break;
-    case 5:    /* response to "insert into history ..." */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_COMMAND_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-      break;
-    case 6:    /* response to "end" */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_COMMAND_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-
-      if (++st->cnt >= nxacts) {
-   remains--;  /* I've done */
-   PQfinish(st->con);
-   st->con = NULL;
-   return;
-      }
-      break;
-    }
-
-    /* increment state counter */
-    st->state++;
-    if (st->state > 6) {
-      st->state = 0;
-    }
-  }
-
-  switch (st->state) {
-  case 0:  /* about to start */
-    strcpy(sql,"begin");
-    st->aid = getrand(1,naccounts*tps);
-    st->bid = getrand(1,nbranches*tps);
-    st->tid = getrand(1,ntellers*tps);
-    st->delta = getrand(1,1000);
-    break;
-  case 1:
-    sprintf(sql,"update accounts set abalance = abalance + %d where aid = %d\n",st->delta,st->aid);
-      break;
-  case 2:
-    sprintf(sql,"select abalance from accounts where aid = %d",st->aid);
-    break;
-  case 3:
-    sprintf(sql,"update tellers set tbalance = tbalance + %d where tid = %d\n",
-       st->delta,st->tid);
-    break;
-  case 4:
-    sprintf(sql,"update branches set bbalance = bbalance + %d where bid = %d",st->delta,st->bid);
-    break;
-  case 5:
-    sprintf(sql,"insert into history(tid,bid,aid,delta,time) values(%d,%d,%d,%d,'now')",
-       st->tid,st->bid,st->aid,st->delta);
-    break;
-  case 6:
-    strcpy(sql,"end");
-    break;
-  }
-
-  if (debug) {
-    fprintf(stderr,"client %d sending %s\n",n,sql);
-  }
-  if (PQsendQuery(st->con, sql) == 0) {
-    if (debug) {
-      fprintf(stderr, "PQsendQuery(%s)failed\n",sql);
-    }
-    st->ecnt++;
-  } else {
-    st->listen++;  /* flags that should be listned */
-  }
+static void
+doOne(CState * state, int n, int debug)
+{
+   char        sql[256];
+   PGresult   *res;
+   CState     *st = &state[n];
+
+   if (st->listen)
+   {                           /* are we receiver? */
+       if (debug)
+           fprintf(stderr, "client %d receiving\n", n);
+       while (PQisBusy(st->con) == TRUE)
+       {
+           if (!PQconsumeInput(st->con))
+           {                   /* there's something wrong */
+               fprintf(stderr, "Client %d aborted in state %d. Probably the backend died while processing.\n", n, st->state);
+               remains--;      /* I've aborted */
+               PQfinish(st->con);
+               st->con = NULL;
+               return;
+           }
+       }
+
+       switch (st->state)
+       {
+           case 0:             /* response to "begin" */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_COMMAND_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+               break;
+           case 1:             /* response to "update accounts..." */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_COMMAND_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+               break;
+           case 2:             /* response to "select abalance ..." */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_TUPLES_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+               break;
+           case 3:             /* response to "update tellers ..." */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_COMMAND_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+               break;
+           case 4:             /* response to "update branches ..." */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_COMMAND_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+               break;
+           case 5:             /* response to "insert into history ..." */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_COMMAND_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+               break;
+           case 6:             /* response to "end" */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_COMMAND_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+
+               if (++st->cnt >= nxacts)
+               {
+                   remains--;  /* I've done */
+                   PQfinish(st->con);
+                   st->con = NULL;
+                   return;
+               }
+               break;
+       }
+
+       /* increment state counter */
+       st->state++;
+       if (st->state > 6)
+           st->state = 0;
+   }
+
+   switch (st->state)
+   {
+       case 0:         /* about to start */
+           strcpy(sql, "begin");
+           st->aid = getrand(1, naccounts * tps);
+           st->bid = getrand(1, nbranches * tps);
+           st->tid = getrand(1, ntellers * tps);
+           st->delta = getrand(1, 1000);
+           break;
+       case 1:
+           sprintf(sql, "update accounts set abalance = abalance + %d where aid = %d\n", st->delta, st->aid);
+           break;
+       case 2:
+           sprintf(sql, "select abalance from accounts where aid = %d", st->aid);
+           break;
+       case 3:
+           sprintf(sql, "update tellers set tbalance = tbalance + %d where tid = %d\n",
+                   st->delta, st->tid);
+           break;
+       case 4:
+           sprintf(sql, "update branches set bbalance = bbalance + %d where bid = %d", st->delta, st->bid);
+           break;
+       case 5:
+           sprintf(sql, "insert into history(tid,bid,aid,delta,time) values(%d,%d,%d,%d,'now')",
+                   st->tid, st->bid, st->aid, st->delta);
+           break;
+       case 6:
+           strcpy(sql, "end");
+           break;
+   }
+
+   if (debug)
+       fprintf(stderr, "client %d sending %s\n", n, sql);
+   if (PQsendQuery(st->con, sql) == 0)
+   {
+       if (debug)
+           fprintf(stderr, "PQsendQuery(%s)failed\n", sql);
+       st->ecnt++;
+   }
+   else
+   {
+       st->listen++;           /* flags that should be listned */
+   }
 }
 
 /* process a select only transaction */
-static void doSelectOnly(CState *state, int n, int debug) {
-  char sql[256];
-  PGresult   *res;
-  CState *st = &state[n];
-
-  if (st->listen) {    /* are we receiver? */
-    if (debug) {
-      fprintf(stderr,"client %d receiving\n",n);
-    }
-    while (PQisBusy(st->con) == TRUE) {
-      if (!PQconsumeInput(st->con)) {  /* there's something wrong */
-   fprintf(stderr, "Client %d aborted in state %d. Probably the backend died while processing.\n",n, st->state);
-   remains--;  /* I've aborted */
-   PQfinish(st->con);
-   st->con = NULL;
-   return;
-      }
-    }
-
-    switch (st->state) {
-    case 0:    /* response to "select abalance ..." */
-      res = PQgetResult(st->con);
-      if (check(state, res, n, PGRES_TUPLES_OK)) {
-   return;
-      }
-      PQclear(res);
-      discard_response(st);
-
-      if (++st->cnt >= nxacts) {
-   remains--;  /* I've done */
-   PQfinish(st->con);
-   st->con = NULL;
-   return;
-      }
-      break;
-    }
-
-    /* increment state counter */
-    st->state++;
-    if (st->state > 0) {
-      st->state = 0;
-    }
-  }
-
-  switch (st->state) {
-  case 0:
-    st->aid = getrand(1,naccounts*tps);
-    sprintf(sql,"select abalance from accounts where aid = %d",st->aid);
-    break;
-  }
-
-  if (debug) {
-    fprintf(stderr,"client %d sending %s\n",n,sql);
-  }
-
-  if (PQsendQuery(st->con, sql) == 0) {
-    if (debug) {
-      fprintf(stderr, "PQsendQuery(%s)failed\n",sql);
-    }
-    st->ecnt++;
-  } else {
-    st->listen++;  /* flags that should be listned */
-  }
+static void
+doSelectOnly(CState * state, int n, int debug)
+{
+   char        sql[256];
+   PGresult   *res;
+   CState     *st = &state[n];
+
+   if (st->listen)
+   {                           /* are we receiver? */
+       if (debug)
+           fprintf(stderr, "client %d receiving\n", n);
+       while (PQisBusy(st->con) == TRUE)
+       {
+           if (!PQconsumeInput(st->con))
+           {                   /* there's something wrong */
+               fprintf(stderr, "Client %d aborted in state %d. Probably the backend died while processing.\n", n, st->state);
+               remains--;      /* I've aborted */
+               PQfinish(st->con);
+               st->con = NULL;
+               return;
+           }
+       }
+
+       switch (st->state)
+       {
+           case 0:             /* response to "select abalance ..." */
+               res = PQgetResult(st->con);
+               if (check(state, res, n, PGRES_TUPLES_OK))
+                   return;
+               PQclear(res);
+               discard_response(st);
+
+               if (++st->cnt >= nxacts)
+               {
+                   remains--;  /* I've done */
+                   PQfinish(st->con);
+                   st->con = NULL;
+                   return;
+               }
+               break;
+       }
+
+       /* increment state counter */
+       st->state++;
+       if (st->state > 0)
+           st->state = 0;
+   }
+
+   switch (st->state)
+   {
+       case 0:
+           st->aid = getrand(1, naccounts * tps);
+           sprintf(sql, "select abalance from accounts where aid = %d", st->aid);
+           break;
+   }
+
+   if (debug)
+       fprintf(stderr, "client %d sending %s\n", n, sql);
+
+   if (PQsendQuery(st->con, sql) == 0)
+   {
+       if (debug)
+           fprintf(stderr, "PQsendQuery(%s)failed\n", sql);
+       st->ecnt++;
+   }
+   else
+   {
+       st->listen++;           /* flags that should be listned */
+   }
 }
 
 /* discard connections */
-static void disconnect_all(CState *state) {
-  int i;
-  for (i=0;i<nclients;i++) {
-    if (state[i].con) {
-      PQfinish(state[i].con);
-    }
-  }
+static void
+disconnect_all(CState * state)
+{
+   int         i;
+
+   for (i = 0; i < nclients; i++)
+   {
+       if (state[i].con)
+           PQfinish(state[i].con);
+   }
 }
 
 /* create tables and setup data */
-static void init(char *pghost, char *pgport,char *dbName) {
-  PGconn *con;
-  PGresult *res;
-  static char *DDLs[] = {
-    "drop table branches",
-    "create table branches(bid int, primary key(bid),bbalance int,filler char(88))",
-    "drop table tellers",
-    "create table tellers(tid int, primary key(tid),bid int,tbalance int,filler char(84))",
-    "drop table accounts",
-    "create table accounts(aid int,primary key(aid),bid int,abalance int,filler char(84))",
-    "drop table history",
-    "create table history(tid int,bid int,aid int,delta int,time timestamp,filler char(22))"};
-  char sql[256];
-
-  int i;
-
-  con = PQsetdb(pghost, pgport, NULL, NULL, dbName);
-  if (PQstatus(con) == CONNECTION_BAD) {
-    fprintf(stderr, "Connection to database '%s' on %s failed.\n", dbName,pghost);
-    fprintf(stderr, "%s", PQerrorMessage(con));
-    exit(1);
-  }
-
-  for (i=0;i<(sizeof(DDLs)/sizeof(char *));i++) {
-    res = PQexec(con,DDLs[i]);
-    if (strncmp(DDLs[i],"drop",4) && PQresultStatus(res) != PGRES_COMMAND_OK) {
-      fprintf(stderr, "%s", PQerrorMessage(con));
-      exit(1);
-    }
-    PQclear(res);
-  }
-
-  res = PQexec(con,"begin");
-  if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-    fprintf(stderr, "%s", PQerrorMessage(con));
-    exit(1);
-  }
-
-  for(i = 0; i < nbranches * tps; i++) {
-    sprintf(sql,"insert into branches(bid,bbalance) values(%d,0)",i+1);
-    res = PQexec(con,sql);
-    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-      fprintf(stderr, "%s", PQerrorMessage(con));
-      exit(1);
-    }
-    PQclear(res);
-  }
-
-  for(i = 0; i < ntellers * tps; i++) {
-    sprintf(sql,"insert into tellers(tid,bid,tbalance) values (%d,%d,0)"
-       ,i+1,i/ntellers+1);
-    res = PQexec(con,sql);
-    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-      fprintf(stderr, "%s", PQerrorMessage(con));
-      exit(1);
-    }
-    PQclear(res);
-  }
-
-  res = PQexec(con,"copy accounts from stdin");
-  if (PQresultStatus(res) != PGRES_COPY_IN) {
-    fprintf(stderr, "%s", PQerrorMessage(con));
-    exit(1);
-  }
-  PQclear(res);
-
-  fprintf(stderr,"creating tables...\n");
-  for(i = 0; i < naccounts*tps; i++) {
-    int j = i + 1;
-    sprintf(sql,"%d\t%d\t%d\t\n",i+1,(i+1)/naccounts,0);
-    if (PQputline(con,sql)) {
-      fprintf(stderr,"PQputline failed\n");
-      exit(1);
-    }
-    if (j % 10000 == 0) {
-      fprintf(stderr,"%d tuples done.\n",j);
-    }
-  }
-  if (PQputline(con,"\\.\n")) {
-    fprintf(stderr,"very last PQputline failed\n");
-    exit(1);
-  }
-
-  if (PQendcopy(con)) {
-    fprintf(stderr,"PQendcopy failed\n");
-    exit(1);
-  }
-
-  res = PQexec(con,"end");
-  if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-    fprintf(stderr, "%s", PQerrorMessage(con));
-    exit(1);
-  }
-
-  /* vacuum */
-  fprintf(stderr,"vacuum...");
-  res = PQexec(con,"vacuum analyze");
-  if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-    fprintf(stderr, "%s", PQerrorMessage(con));
-    exit(1);
-  }
-  fprintf(stderr,"done.\n");
-
-  PQfinish(con);
-}
+static void
+init(char *pghost, char *pgport, char *dbName)
+{
+   PGconn     *con;
+   PGresult   *res;
+   static char *DDLs[] = {
+       "drop table branches",
+       "create table branches(bid int, primary key(bid),bbalance int,filler char(88))",
+       "drop table tellers",
+       "create table tellers(tid int, primary key(tid),bid int,tbalance int,filler char(84))",
+       "drop table accounts",
+       "create table accounts(aid int,primary key(aid),bid int,abalance int,filler char(84))",
+       "drop table history",
+   "create table history(tid int,bid int,aid int,delta int,time timestamp,filler char(22))"};
+   char        sql[256];
+
+   int         i;
+
+   con = PQsetdb(pghost, pgport, NULL, NULL, dbName);
+   if (PQstatus(con) == CONNECTION_BAD)
+   {
+       fprintf(stderr, "Connection to database '%s' on %s failed.\n", dbName, pghost);
+       fprintf(stderr, "%s", PQerrorMessage(con));
+       exit(1);
+   }
 
-/* print out results */
-static void printResults(
-            int ttype, CState *state, 
-            struct timeval *tv1,struct timeval *tv2,
-            struct timeval *tv3) {
-  double t1,t2;
-  int i;
-  int normal_xacts = 0;
-
-  for (i=0;i<nclients;i++) {
-    normal_xacts += state[i].cnt;
-  }
-
-  t1 = (tv3->tv_sec - tv1->tv_sec)*1000000.0+(tv3->tv_usec - tv1->tv_usec);
-  t1 = normal_xacts*1000000.0/t1;
-
-  t2 = (tv3->tv_sec - tv2->tv_sec)*1000000.0+(tv3->tv_usec - tv2->tv_usec);
-  t2 = normal_xacts*1000000.0/t2;
-
-  printf("transaction type: %s\n",ttype==0?"TPC-B (sort of)":"SELECT only");
-  printf("scaling factor: %d\n",tps);
-  printf("number of clients: %d\n",nclients);
-  printf("number of transactions per client: %d\n",nxacts);
-  printf("number of transactions actually processed: %d/%d\n",normal_xacts,nxacts*nclients);
-  printf("tps = %f(including connections establishing)\n",t1);
-  printf("tps = %f(excluding connections establishing)\n",t2);
-}
+   for (i = 0; i < (sizeof(DDLs) / sizeof(char *)); i++)
+   {
+       res = PQexec(con, DDLs[i]);
+       if (strncmp(DDLs[i], "drop", 4) && PQresultStatus(res) != PGRES_COMMAND_OK)
+       {
+           fprintf(stderr, "%s", PQerrorMessage(con));
+           exit(1);
+       }
+       PQclear(res);
+   }
 
-int main(int argc, char **argv) {
-  extern char *optarg;
-  extern int optind, opterr, optopt;
-  int c;
-  char *pghost = "";
-  char *pgport = "";
-  char *dbName;
-  int is_init_mode = 0;    /* initialize mode? */
-  int is_no_vacuum = 0;    /* no vacuum at all before testing? */
-  int is_full_vacuum = 0;  /* do full vacuum before testing? */
-  int debug = 0;   /* debug flag */
-  int ttype = 0;   /* transaction type. 0: TPC-B, 1: SELECT only */
+   res = PQexec(con, "begin");
+   if (PQresultStatus(res) != PGRES_COMMAND_OK)
+   {
+       fprintf(stderr, "%s", PQerrorMessage(con));
+       exit(1);
+   }
 
-  static CState       state[MAXCLIENTS];   /* clients status */
+   for (i = 0; i < nbranches * tps; i++)
+   {
+       sprintf(sql, "insert into branches(bid,bbalance) values(%d,0)", i + 1);
+       res = PQexec(con, sql);
+       if (PQresultStatus(res) != PGRES_COMMAND_OK)
+       {
+           fprintf(stderr, "%s", PQerrorMessage(con));
+           exit(1);
+       }
+       PQclear(res);
+   }
 
-  struct timeval tv1;  /* start up time */
-  struct timeval tv2;  /* after establishing all connections to the backend */
-  struct timeval tv3;  /* end time */
+   for (i = 0; i < ntellers * tps; i++)
+   {
+       sprintf(sql, "insert into tellers(tid,bid,tbalance) values (%d,%d,0)"
+               ,i + 1, i / ntellers + 1);
+       res = PQexec(con, sql);
+       if (PQresultStatus(res) != PGRES_COMMAND_OK)
+       {
+           fprintf(stderr, "%s", PQerrorMessage(con));
+           exit(1);
+       }
+       PQclear(res);
+   }
 
-  int  i;
+   res = PQexec(con, "copy accounts from stdin");
+   if (PQresultStatus(res) != PGRES_COPY_IN)
+   {
+       fprintf(stderr, "%s", PQerrorMessage(con));
+       exit(1);
+   }
+   PQclear(res);
+
+   fprintf(stderr, "creating tables...\n");
+   for (i = 0; i < naccounts * tps; i++)
+   {
+       int         j = i + 1;
+
+       sprintf(sql, "%d\t%d\t%d\t\n", i + 1, (i + 1) / naccounts, 0);
+       if (PQputline(con, sql))
+       {
+           fprintf(stderr, "PQputline failed\n");
+           exit(1);
+       }
+       if (j % 10000 == 0)
+           fprintf(stderr, "%d tuples done.\n", j);
+   }
+   if (PQputline(con, "\\.\n"))
+   {
+       fprintf(stderr, "very last PQputline failed\n");
+       exit(1);
+   }
+
+   if (PQendcopy(con))
+   {
+       fprintf(stderr, "PQendcopy failed\n");
+       exit(1);
+   }
+
+   res = PQexec(con, "end");
+   if (PQresultStatus(res) != PGRES_COMMAND_OK)
+   {
+       fprintf(stderr, "%s", PQerrorMessage(con));
+       exit(1);
+   }
+
+   /* vacuum */
+   fprintf(stderr, "vacuum...");
+   res = PQexec(con, "vacuum analyze");
+   if (PQresultStatus(res) != PGRES_COMMAND_OK)
+   {
+       fprintf(stderr, "%s", PQerrorMessage(con));
+       exit(1);
+   }
+   fprintf(stderr, "done.\n");
+
+   PQfinish(con);
+}
 
-  fd_set   input_mask;
-  int nsocks;  /* return from select(2) */
-  int maxsock; /* max socket number to be waited */
+/* print out results */
+static void
+printResults(
+            int ttype, CState * state,
+            struct timeval * tv1, struct timeval * tv2,
+            struct timeval * tv3)
+{
+   double      t1,
+               t2;
+   int         i;
+   int         normal_xacts = 0;
+
+   for (i = 0; i < nclients; i++)
+       normal_xacts += state[i].cnt;
+
+   t1 = (tv3->tv_sec - tv1->tv_sec) * 1000000.0 + (tv3->tv_usec - tv1->tv_usec);
+   t1 = normal_xacts * 1000000.0 / t1;
+
+   t2 = (tv3->tv_sec - tv2->tv_sec) * 1000000.0 + (tv3->tv_usec - tv2->tv_usec);
+   t2 = normal_xacts * 1000000.0 / t2;
+
+   printf("transaction type: %s\n", ttype == 0 ? "TPC-B (sort of)" : "SELECT only");
+   printf("scaling factor: %d\n", tps);
+   printf("number of clients: %d\n", nclients);
+   printf("number of transactions per client: %d\n", nxacts);
+   printf("number of transactions actually processed: %d/%d\n", normal_xacts, nxacts * nclients);
+   printf("tps = %f(including connections establishing)\n", t1);
+   printf("tps = %f(excluding connections establishing)\n", t2);
+}
+
+int
+main(int argc, char **argv)
+{
+   extern char *optarg;
+   extern int  optind,
+               opterr,
+               optopt;
+   int         c;
+   char       *pghost = "";
+   char       *pgport = "";
+   char       *dbName;
+   int         is_init_mode = 0;       /* initialize mode? */
+   int         is_no_vacuum = 0;       /* no vacuum at all before
+                                        * testing? */
+   int         is_full_vacuum = 0;     /* do full vacuum before testing? */
+   int         debug = 0;      /* debug flag */
+   int         ttype = 0;      /* transaction type. 0: TPC-B, 1: SELECT
+                                * only */
+
+   static CState state[MAXCLIENTS];    /* clients status */
+
+   struct timeval tv1;         /* start up time */
+   struct timeval tv2;         /* after establishing all connections to
+                                * the backend */
+   struct timeval tv3;         /* end time */
+
+   int         i;
+
+   fd_set      input_mask;
+   int         nsocks;         /* return from select(2) */
+   int         maxsock;        /* max socket number to be waited */
 
 #ifndef __CYGWIN32__
-  struct rlimit rlim;
+   struct rlimit rlim;
+
 #endif
 
-  PGconn *con;
-  PGresult *res;
-
-  while ((c = getopt(argc, argv, "ih:nvp:dc:t:s:S")) != EOF) {
-    switch (c) {
-    case 'i':
-      is_init_mode++;
-      break;
-    case 'h':
-      pghost = optarg;
-      break;
-    case 'n':
-      is_no_vacuum++;
-      break;
-    case 'v':
-      is_full_vacuum++;
-      break;
-    case 'p':
-      pgport = optarg;
-      break;
-    case 'd':
-      debug++;
-      break;
-    case 'S':
-      ttype = 1;
-      break;
-    case 'c':
-      nclients = atoi(optarg);
-      if (nclients <= 0 || nclients > MAXCLIENTS) {
-   fprintf(stderr,"wrong number of clients: %d\n",nclients);
-   exit(1);
-      }
+   PGconn     *con;
+   PGresult   *res;
+
+   while ((c = getopt(argc, argv, "ih:nvp:dc:t:s:S")) != EOF)
+   {
+       switch (c)
+       {
+           case 'i':
+               is_init_mode++;
+               break;
+           case 'h':
+               pghost = optarg;
+               break;
+           case 'n':
+               is_no_vacuum++;
+               break;
+           case 'v':
+               is_full_vacuum++;
+               break;
+           case 'p':
+               pgport = optarg;
+               break;
+           case 'd':
+               debug++;
+               break;
+           case 'S':
+               ttype = 1;
+               break;
+           case 'c':
+               nclients = atoi(optarg);
+               if (nclients <= 0 || nclients > MAXCLIENTS)
+               {
+                   fprintf(stderr, "wrong number of clients: %d\n", nclients);
+                   exit(1);
+               }
 #ifndef __CYGWIN32__
-#ifdef RLIMIT_NOFILE       /* most platform uses RLIMIT_NOFILE */
-      if (getrlimit(RLIMIT_NOFILE,&rlim) == -1) {
-#else  /* but BSD doesn't ... */
-      if (getrlimit(RLIMIT_OFILE,&rlim) == -1) {
-#endif /* HAVE_RLIMIT_NOFILE */
-   fprintf(stderr,"getrlimit failed. reason: %s\n",strerror(errno));
-   exit(1);
-      }
-      if (rlim.rlim_cur <= (nclients+2)) {
-   fprintf(stderr,"You need at least %d open files resource but you are only allowed to use %ld.\n",nclients+2,rlim.rlim_cur);
-   fprintf(stderr,"Use limit/ulimt to increase the limit before using pgbench.\n");
-   exit(1);
-      }
-#endif /* #ifndef __CYGWIN32__ */
-      break;
-    case 's':
-      tps = atoi(optarg);
-      if (tps <= 0) {
-   fprintf(stderr,"wrong scaling factor: %d\n",tps);
-   exit(1);
-      }
-      break;
-    case 't':
-      nxacts = atoi(optarg);
-      if (nxacts <= 0) {
-   fprintf(stderr,"wrong number of transactions: %d\n",nxacts);
-   exit(1);
-      }
-      break;
-    default:
-      usage();
-      exit(1);
-      break;
-    }
-  }
-
-  if (argc > optind) {
-    dbName = argv[optind];
-  } else {
-    dbName = getenv("USER");
-    if (dbName == NULL) {
-      dbName = "";
-    }
-  }
-
-  if (is_init_mode) {
-    init(pghost, pgport, dbName);
-    exit(0);
-  }
-
-  remains = nclients;
-
-  if (debug) {
-    printf("pghost: %s pgport: %s nclients: %d nxacts: %d dbName: %s\n",
-      pghost, pgport, nclients, nxacts, dbName);
-  }
-
-  /* opening connection... */
-  con = PQsetdb(pghost, pgport, NULL, NULL, dbName);
-  if (PQstatus(con) == CONNECTION_BAD) {
-    fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
-    fprintf(stderr, "%s", PQerrorMessage(con));
-    exit(1);
-  }
-
-  /* get the scaling factor that should be same as count(*) from branches... */
-  res = PQexec(con,"select count(*) from branches");
-  if (PQresultStatus(res) != PGRES_TUPLES_OK) {
-    fprintf(stderr, "%s", PQerrorMessage(con));
-    exit(1);
-  }
-  tps = atoi(PQgetvalue(res, 0, 0));
-  if (tps < 0) {
-    fprintf(stderr,"count(*) from branches invalid (%d)\n",tps);
-    exit(1);
-  }
-  PQclear(res);
-
-  if (!is_no_vacuum) {
-    fprintf(stderr,"starting vacuum...");
-    res = PQexec(con,"vacuum branches");
-    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-      fprintf(stderr, "%s", PQerrorMessage(con));
-      exit(1);
-    }
-    PQclear(res);
-
-    res = PQexec(con,"vacuum tellers");
-    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-      fprintf(stderr, "%s", PQerrorMessage(con));
-      exit(1);
-    }
-    PQclear(res);
-
-    res = PQexec(con,"delete from history");
-    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-      fprintf(stderr, "%s", PQerrorMessage(con));
-      exit(1);
-    }
-    PQclear(res);
-    res = PQexec(con,"vacuum history");
-    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-      fprintf(stderr, "%s", PQerrorMessage(con));
-      exit(1);
-    }
-    PQclear(res);
-
-    fprintf(stderr,"end.\n");
-
-    if (is_full_vacuum) {
-      fprintf(stderr,"starting full vacuum...");
-      res = PQexec(con,"vacuum analyze accounts");
-      if (PQresultStatus(res) != PGRES_COMMAND_OK) {
-   fprintf(stderr, "%s", PQerrorMessage(con));
-   exit(1);
-      }
-      PQclear(res);
-      fprintf(stderr,"end.\n");
-    }
-  }
-  PQfinish(con);
-
-  /* set random seed */
-  gettimeofday(&tv1, 0);
-  srand((uint)tv1.tv_usec);
-
-  /* get start up time */
-  gettimeofday(&tv1, 0);
-
-  /* make connections to the database */
-  for (i=0;i<nclients;i++) {
-    state[i].con = PQsetdb(pghost, pgport, NULL, NULL, dbName);
-    if (PQstatus(state[i].con) == CONNECTION_BAD) {
-      fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
-      fprintf(stderr, "%s", PQerrorMessage(state[i].con));
-      exit(1);
-    }
-  }
-
-  /* time after connections set up */
-  gettimeofday(&tv2, 0);
-
-  /* send start up quries in async manner */
-  for (i=0;i<nclients;i++) {
-    if (ttype == 0) {
-      doOne(state, i, debug);
-    } else if (ttype == 1) {
-      doSelectOnly(state, i, debug);
-    }
-  }
-
-  for (;;) {
-    if (remains <= 0) {    /* all done ? */
-      disconnect_all(state);
-      /* get end time */
-      gettimeofday(&tv3, 0);
-      printResults(ttype, state, &tv1,&tv2,&tv3);
-      exit(0);
-    }
-
-    FD_ZERO(&input_mask);
-
-    maxsock = 0;
-    for (i=0;i<nclients;i++) {
-      if (state[i].con) {
-   int sock = PQsocket(state[i].con);
-   if (sock < 0) {
-     fprintf(stderr,"Client %d: PQsock failed\n",i);
-     disconnect_all(state);
-     exit(1);
-   }
-   FD_SET(sock, &input_mask);
-   if (maxsock < sock) {
-     maxsock = sock;
-   }
-      }
-    }
-
-    if ((nsocks = select(maxsock +1, &input_mask, (fd_set *)NULL,
-            (fd_set *)NULL, (struct timeval *)NULL)) < 0) {
-      if (errno == EINTR) {
-   continue;
-      }
-      /* must be something wrong */
-      disconnect_all(state);
-      fprintf(stderr,"select failed: %s\n",strerror(errno));
-      exit(1);
-    } else if (nsocks == 0) { /* timeout */
-      fprintf(stderr,"select timeout\n");
-      for (i=0;i<nclients;i++) {
-   fprintf(stderr,"client %d:state %d cnt %d ecnt %d listen %d\n",
-       i,state[i].state,state[i].cnt,state[i].ecnt,state[i].listen);
-      }
-      exit(0);
-    }
-
-    /* ok, backend returns reply */
-    for (i=0;i<nclients;i++) {
-      if (state[i].con && FD_ISSET(PQsocket(state[i].con), &input_mask)) {
-   if (ttype == 0) {
-     doOne(state, i, debug);
-   } else if (ttype == 1) {
-     doSelectOnly(state, i, debug);
-   }
-      }
-    }
-  }
+#ifdef RLIMIT_NOFILE           /* most platform uses RLIMIT_NOFILE */
+               if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
+               {
+#else                          /* but BSD doesn't ... */
+               if (getrlimit(RLIMIT_OFILE, &rlim) == -1)
+               {
+#endif  /* HAVE_RLIMIT_NOFILE */
+                   fprintf(stderr, "getrlimit failed. reason: %s\n", strerror(errno));
+                   exit(1);
+               }
+               if (rlim.rlim_cur <= (nclients + 2))
+               {
+                   fprintf(stderr, "You need at least %d open files resource but you are only allowed to use %ld.\n", nclients + 2, rlim.rlim_cur);
+                   fprintf(stderr, "Use limit/ulimt to increase the limit before using pgbench.\n");
+                   exit(1);
+               }
+#endif  /* #ifndef __CYGWIN32__ */
+               break;
+           case 's':
+               tps = atoi(optarg);
+               if (tps <= 0)
+               {
+                   fprintf(stderr, "wrong scaling factor: %d\n", tps);
+                   exit(1);
+               }
+               break;
+           case 't':
+               nxacts = atoi(optarg);
+               if (nxacts <= 0)
+               {
+                   fprintf(stderr, "wrong number of transactions: %d\n", nxacts);
+                   exit(1);
+               }
+               break;
+           default:
+               usage();
+               exit(1);
+               break;
+       }
+   }
+
+   if (argc > optind)
+       dbName = argv[optind];
+   else
+   {
+       dbName = getenv("USER");
+       if (dbName == NULL)
+           dbName = "";
+   }
+
+   if (is_init_mode)
+   {
+       init(pghost, pgport, dbName);
+       exit(0);
+   }
+
+   remains = nclients;
+
+   if (debug)
+   {
+       printf("pghost: %s pgport: %s nclients: %d nxacts: %d dbName: %s\n",
+              pghost, pgport, nclients, nxacts, dbName);
+   }
+
+   /* opening connection... */
+   con = PQsetdb(pghost, pgport, NULL, NULL, dbName);
+   if (PQstatus(con) == CONNECTION_BAD)
+   {
+       fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
+       fprintf(stderr, "%s", PQerrorMessage(con));
+       exit(1);
+   }
+
+   /*
+    * get the scaling factor that should be same as count(*) from
+    * branches...
+    */
+   res = PQexec(con, "select count(*) from branches");
+   if (PQresultStatus(res) != PGRES_TUPLES_OK)
+   {
+       fprintf(stderr, "%s", PQerrorMessage(con));
+       exit(1);
+   }
+   tps = atoi(PQgetvalue(res, 0, 0));
+   if (tps < 0)
+   {
+       fprintf(stderr, "count(*) from branches invalid (%d)\n", tps);
+       exit(1);
+   }
+   PQclear(res);
+
+   if (!is_no_vacuum)
+   {
+       fprintf(stderr, "starting vacuum...");
+       res = PQexec(con, "vacuum branches");
+       if (PQresultStatus(res) != PGRES_COMMAND_OK)
+       {
+           fprintf(stderr, "%s", PQerrorMessage(con));
+           exit(1);
+       }
+       PQclear(res);
+
+       res = PQexec(con, "vacuum tellers");
+       if (PQresultStatus(res) != PGRES_COMMAND_OK)
+       {
+           fprintf(stderr, "%s", PQerrorMessage(con));
+           exit(1);
+       }
+       PQclear(res);
+
+       res = PQexec(con, "delete from history");
+       if (PQresultStatus(res) != PGRES_COMMAND_OK)
+       {
+           fprintf(stderr, "%s", PQerrorMessage(con));
+           exit(1);
+       }
+       PQclear(res);
+       res = PQexec(con, "vacuum history");
+       if (PQresultStatus(res) != PGRES_COMMAND_OK)
+       {
+           fprintf(stderr, "%s", PQerrorMessage(con));
+           exit(1);
+       }
+       PQclear(res);
+
+       fprintf(stderr, "end.\n");
+
+       if (is_full_vacuum)
+       {
+           fprintf(stderr, "starting full vacuum...");
+           res = PQexec(con, "vacuum analyze accounts");
+           if (PQresultStatus(res) != PGRES_COMMAND_OK)
+           {
+               fprintf(stderr, "%s", PQerrorMessage(con));
+               exit(1);
+           }
+           PQclear(res);
+           fprintf(stderr, "end.\n");
+       }
+   }
+   PQfinish(con);
+
+   /* set random seed */
+   gettimeofday(&tv1, 0);
+   srand((uint) tv1.tv_usec);
+
+   /* get start up time */
+   gettimeofday(&tv1, 0);
+
+   /* make connections to the database */
+   for (i = 0; i < nclients; i++)
+   {
+       state[i].con = PQsetdb(pghost, pgport, NULL, NULL, dbName);
+       if (PQstatus(state[i].con) == CONNECTION_BAD)
+       {
+           fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
+           fprintf(stderr, "%s", PQerrorMessage(state[i].con));
+           exit(1);
+       }
+   }
+
+   /* time after connections set up */
+   gettimeofday(&tv2, 0);
+
+   /* send start up quries in async manner */
+   for (i = 0; i < nclients; i++)
+   {
+       if (ttype == 0)
+           doOne(state, i, debug);
+       else if (ttype == 1)
+           doSelectOnly(state, i, debug);
+   }
+
+   for (;;)
+   {
+       if (remains <= 0)
+       {                       /* all done ? */
+           disconnect_all(state);
+           /* get end time */
+           gettimeofday(&tv3, 0);
+           printResults(ttype, state, &tv1, &tv2, &tv3);
+           exit(0);
+       }
+
+       FD_ZERO(&input_mask);
+
+       maxsock = 0;
+       for (i = 0; i < nclients; i++)
+       {
+           if (state[i].con)
+           {
+               int         sock = PQsocket(state[i].con);
+
+               if (sock < 0)
+               {
+                   fprintf(stderr, "Client %d: PQsock failed\n", i);
+                   disconnect_all(state);
+                   exit(1);
+               }
+               FD_SET(sock, &input_mask);
+               if (maxsock < sock)
+                   maxsock = sock;
+           }
+       }
+
+       if ((nsocks = select(maxsock + 1, &input_mask, (fd_set *) NULL,
+                         (fd_set *) NULL, (struct timeval *) NULL)) < 0)
+       {
+           if (errno == EINTR)
+               continue;
+           /* must be something wrong */
+           disconnect_all(state);
+           fprintf(stderr, "select failed: %s\n", strerror(errno));
+           exit(1);
+       }
+       else if (nsocks == 0)
+       {                       /* timeout */
+           fprintf(stderr, "select timeout\n");
+           for (i = 0; i < nclients; i++)
+           {
+               fprintf(stderr, "client %d:state %d cnt %d ecnt %d listen %d\n",
+                       i, state[i].state, state[i].cnt, state[i].ecnt, state[i].listen);
+           }
+           exit(0);
+       }
+
+       /* ok, backend returns reply */
+       for (i = 0; i < nclients; i++)
+       {
+           if (state[i].con && FD_ISSET(PQsocket(state[i].con), &input_mask))
+           {
+               if (ttype == 0)
+                   doOne(state, i, debug);
+               else if (ttype == 1)
+                   doSelectOnly(state, i, debug);
+           }
+       }
+   }
 }
index 9407e6a21b3d37425140ad96b43f1e08affedca8..cb8323d9c9b75650429cc753536fcf65682419bf 100644 (file)
@@ -23,7 +23,7 @@
 #define ISO8859
 
 #define MIN(x, y)  ((x) < (y) ? (x) : (y))
-#define VALUE(char)    ((char) - '0')
+#define VALUE(char) ((char) - '0')
 #define DIGIT(val) ((val) + '0')
 #define ISOCTAL(c) (((c) >= '0') && ((c) <= '7'))
 #ifndef ISO8859
@@ -89,9 +89,8 @@ string_output(unsigned char *data, int size)
                break;
            case '{':
                /* Escape beginning of string, to distinguish from arrays */
-               if (p == data) {
+               if (p == data)
                    len++;
-               }
                break;
            default:
                if (NOTPRINTABLE(*p))
@@ -137,9 +136,8 @@ string_output(unsigned char *data, int size)
                break;
            case '{':
                /* Escape beginning of string, to distinguish from arrays */
-               if (p == data) {
+               if (p == data)
                    *r++ = '\\';
-               }
                *r++ = c;
                break;
            default:
@@ -361,14 +359,15 @@ c_charin(unsigned char *str)
 {
    return (string_input(str, 1, 0, NULL));
 }
+
 #endif
 
 /* end of file */
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index e79d7fd28febc7392d56c8102c166561c2182883..556c33660ce7b18c1c5d9585bce44cfff4531d9f 100644 (file)
@@ -1,24 +1,25 @@
 #ifndef STRING_IO_H
 #define STRING_IO_H
 
-unsigned charstring_output(unsigned char *data, int size);
-unsigned charstring_input(unsigned char *str, int size, int hdrsize,
-                             int *rtn_size);
-unsigned charc_charout(int32 c);
-unsigned charc_textout(struct varlena * vlena);
-unsigned charc_varcharout(unsigned char *s);
+unsigned char *string_output(unsigned char *data, int size);
+unsigned char *string_input(unsigned char *str, int size, int hdrsize,
+            int *rtn_size);
+unsigned char *c_charout(int32 c);
+unsigned char *c_textout(struct varlena * vlena);
+unsigned char *c_varcharout(unsigned char *s);
 
 #if 0
-struct varlena*    c_textin(unsigned char *str);
-int32*         c_charin(unsigned char *str)
+struct varlena *c_textin(unsigned char *str);
+int32 *
+c_charin(unsigned char *str)
 #endif
 
 #endif
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index 1a596d515401696034e38dff0fedd0256500b059..1e37a54cf01ec2470e75e78fdde185ee6c2d1418 100644 (file)
@@ -96,8 +96,8 @@ user_unlock_all()
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index 3f0449e7e4507a1ffae70bec4d28adcbb69329fb..82ecb3b9ea00c22b98b9c9bbe244ae2e7ed84230 100644 (file)
@@ -13,8 +13,8 @@ int           user_unlock_all(void);
 
 /*
  * Local Variables:
- *  tab-width: 4
- *  c-indent-level: 4
- *  c-basic-offset: 4
+ * tab-width: 4
+ * c-indent-level: 4
+ * c-basic-offset: 4
  * End:
  */
index 4eec6ed6d077438bd3d637a17536b2f948d7620a..d30e4c7fe64e350bbee4ffed062a74e7d679e1ab 100644 (file)
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/common/heaptuple.c,v 1.61 2000/01/26 05:55:53 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/common/heaptuple.c,v 1.62 2000/04/12 17:14:36 momjian Exp $
  *
  * NOTES
  *   The old interface functions have been converted to macros
@@ -137,9 +137,9 @@ DataFill(char *data,
                                   *((int32 *) value[i]));
                break;
            default:
-                Assert(att[i]->attlen >= 0);
-                memmove(data, DatumGetPointer(value[i]),
-                        (size_t)(att[i]->attlen));
+               Assert(att[i]->attlen >= 0);
+               memmove(data, DatumGetPointer(value[i]),
+                       (size_t) (att[i]->attlen));
                break;
        }
        data = (char *) att_addlength((long) data, att[i]->attlen, value[i]);
@@ -326,7 +326,7 @@ nocachegetattr(HeapTuple tuple,
    Form_pg_attribute *att = tupleDesc->attrs;
    int         slow = 0;       /* do we have to walk nulls? */
 
-    (void)isnull; /*not used*/
+   (void) isnull;              /* not used */
 #ifdef IN_MACRO
 /* This is handled in the macro */
    Assert(attnum > 0);
@@ -681,7 +681,7 @@ heap_formtuple(TupleDesc tupleDescriptor,
        len += bitmaplen;
    }
 
-   hoff = len = MAXALIGN(len);     /* be conservative here */
+   hoff = len = MAXALIGN(len); /* be conservative here */
 
    len += ComputeDataSize(tupleDescriptor, value, nulls);
 
@@ -806,11 +806,9 @@ void
 heap_freetuple(HeapTuple htup)
 {
    if (htup->t_data != NULL)
-       if (htup->t_datamcxt != NULL && (char *)(htup->t_data) != 
-                                   ((char *) htup + HEAPTUPLESIZE))
-       {
+       if (htup->t_datamcxt != NULL && (char *) (htup->t_data) !=
+           ((char *) htup + HEAPTUPLESIZE))
            elog(NOTICE, "TELL Jan Wieck: heap_freetuple() found separate t_data");
-       }
 
    pfree(htup);
 }
@@ -835,7 +833,7 @@ heap_addheader(uint32 natts,    /* max domain index */
 
    len = offsetof(HeapTupleHeaderData, t_bits);
 
-   hoff = len = MAXALIGN(len);     /* be conservative */
+   hoff = len = MAXALIGN(len); /* be conservative */
    len += structlen;
    tuple = (HeapTuple) palloc(HEAPTUPLESIZE + len);
    tuple->t_datamcxt = CurrentMemoryContext;
@@ -850,8 +848,8 @@ heap_addheader(uint32 natts,    /* max domain index */
    td->t_infomask = 0;
    td->t_infomask |= HEAP_XMAX_INVALID;
 
-    if (structlen > 0)
-        memmove((char *) td + hoff, structure, (size_t)structlen);
+   if (structlen > 0)
+       memmove((char *) td + hoff, structure, (size_t) structlen);
 
    return tuple;
 }
index 438318747d24cd75b895fde89728fac6b9180019..e11ddbc1dc9b495cd5a81438268d48f2692088aa 100644 (file)
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/common/indextuple.c,v 1.42 2000/01/26 05:55:53 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/common/indextuple.c,v 1.43 2000/04/12 17:14:37 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -60,7 +60,7 @@ index_formtuple(TupleDesc tupleDescriptor,
 
    hoff = IndexInfoFindDataOffset(infomask);
    size = hoff + ComputeDataSize(tupleDescriptor, value, null);
-   size = MAXALIGN(size);  /* be conservative */
+   size = MAXALIGN(size);      /* be conservative */
 
    tp = (char *) palloc(size);
    tuple = (IndexTuple) tp;
@@ -134,7 +134,7 @@ nocache_index_getattr(IndexTuple tup,
    int         data_off;       /* tuple data offset */
    Form_pg_attribute *att = tupleDesc->attrs;
 
-    (void)isnull;
+   (void) isnull;
    /* ----------------
     *  sanity checks
     * ----------------
index b2af4ff932ecac4ba53f1dd9e78e9b8b04e5bd1e..1e8d2ae00343a5964c4a5d01b164413c0dc3c4f8 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/common/tupdesc.c,v 1.61 2000/01/31 04:35:48 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/common/tupdesc.c,v 1.62 2000/04/12 17:14:37 momjian Exp $
  *
  * NOTES
  *   some of the executor utility code such as "ExecTypeFromTL" should be
@@ -229,17 +229,19 @@ FreeTupleDesc(TupleDesc tupdesc)
 bool
 equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
 {
-   int     i;
+   int         i;
 
    if (tupdesc1->natts != tupdesc2->natts)
        return false;
    for (i = 0; i < tupdesc1->natts; i++)
    {
-       Form_pg_attribute   attr1 = tupdesc1->attrs[i];
-       Form_pg_attribute   attr2 = tupdesc2->attrs[i];
+       Form_pg_attribute attr1 = tupdesc1->attrs[i];
+       Form_pg_attribute attr2 = tupdesc2->attrs[i];
 
-       /* We do not need to check every single field here, and in fact
-        * some fields such as attdisbursion probably shouldn't be compared.
+       /*
+        * We do not need to check every single field here, and in fact
+        * some fields such as attdisbursion probably shouldn't be
+        * compared.
         */
        if (strcmp(NameStr(attr1->attname), NameStr(attr2->attname)) != 0)
            return false;
@@ -254,8 +256,8 @@ equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
    }
    if (tupdesc1->constr != NULL)
    {
-       TupleConstr    *constr1 = tupdesc1->constr;
-       TupleConstr    *constr2 = tupdesc2->constr;
+       TupleConstr *constr1 = tupdesc1->constr;
+       TupleConstr *constr2 = tupdesc2->constr;
 
        if (constr2 == NULL)
            return false;
@@ -263,8 +265,8 @@ equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
            return false;
        for (i = 0; i < (int) constr1->num_defval; i++)
        {
-           AttrDefault    *defval1 = constr1->defval + i;
-           AttrDefault    *defval2 = constr2->defval + i;
+           AttrDefault *defval1 = constr1->defval + i;
+           AttrDefault *defval2 = constr2->defval + i;
 
            if (defval1->adnum != defval2->adnum)
                return false;
@@ -275,8 +277,8 @@ equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
            return false;
        for (i = 0; i < (int) constr1->num_check; i++)
        {
-           ConstrCheck    *check1 = constr1->check + i;
-           ConstrCheck    *check2 = constr2->check + i;
+           ConstrCheck *check1 = constr1->check + i;
+           ConstrCheck *check2 = constr2->check + i;
 
            if (strcmp(check1->ccname, check2->ccname) != 0)
                return false;
@@ -585,8 +587,9 @@ BuildDescForRelation(List *schema, char *relname)
            constr->has_not_null = true;
        desc->attrs[attnum - 1]->attnotnull = entry->is_not_null;
 
-       /* Note we copy only pre-cooked default expressions.
-        * Digestion of raw ones is someone else's problem.
+       /*
+        * Note we copy only pre-cooked default expressions. Digestion of
+        * raw ones is someone else's problem.
         */
        if (entry->cooked_default != NULL)
        {
index 9e93f1d652da5d13340c6b53e717734a05468832..66a3702e438d3630486ffb97722a5fcac7583bb3 100644 (file)
@@ -6,7 +6,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/gist/gist.c,v 1.52 2000/03/17 02:36:00 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/gist/gist.c,v 1.53 2000/04/12 17:14:39 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -52,8 +52,10 @@ void     gistdelete(Relation r, ItemPointer tid);
 static IndexTuple gist_tuple_replacekey(Relation r, GISTENTRY entry, IndexTuple t);
 static void gistcentryinit(GISTSTATE *giststate, GISTENTRY *e, char *pr,
               Relation r, Page pg, OffsetNumber o, int b, bool l);
+
 #ifdef GISTDEBUG
 static char *int_range_out(INTRANGE *r);
+
 #endif
 
 /*
@@ -98,7 +100,7 @@ gistbuild(Relation heap,
 
    /* no locking is needed */
 
-   CommandCounterIncrement();      /* so we can see the new pg_index tuple */
+   CommandCounterIncrement();  /* so we can see the new pg_index tuple */
 
    initGISTstate(&giststate, index);
 
@@ -186,7 +188,7 @@ gistbuild(Relation heap,
 #ifndef OMIT_PARTIAL_INDEX
            /* SetSlotContents(slot, htup); */
            slot->val = htup;
-           if (! ExecQual((List *) pred, econtext, false))
+           if (!ExecQual((List *) pred, econtext, false))
                continue;
 #endif  /* OMIT_PARTIAL_INDEX */
        }
@@ -272,18 +274,18 @@ gistbuild(Relation heap,
    /*
     * Since we just counted the tuples in the heap, we update its stats
     * in pg_class to guarantee that the planner takes advantage of the
-    * index we just created.  But, only update statistics during
-    * normal index definitions, not for indices on system catalogs
-    * created during bootstrap processing.  We must close the relations
-    * before updating statistics to guarantee that the relcache entries
-    * are flushed when we increment the command counter in UpdateStats().
-    * But we do not release any locks on the relations; those will be
-    * held until end of transaction.
+    * index we just created.  But, only update statistics during normal
+    * index definitions, not for indices on system catalogs created
+    * during bootstrap processing.  We must close the relations before
+    * updating statistics to guarantee that the relcache entries are
+    * flushed when we increment the command counter in UpdateStats(). But
+    * we do not release any locks on the relations; those will be held
+    * until end of transaction.
     */
    if (IsNormalProcessingMode())
    {
-       Oid     hrelid = RelationGetRelid(heap);
-       Oid     irelid = RelationGetRelid(index);
+       Oid         hrelid = RelationGetRelid(heap);
+       Oid         irelid = RelationGetRelid(index);
        bool        inplace = IsReindexProcessing();
 
        heap_close(heap, NoLock);
index a7d1faf43db1b9ffcf45fda183f9e0415aa54a62..2196e897e4a12ecccfc52edd3170af13a22c93f4 100644 (file)
@@ -266,7 +266,7 @@ gistdropscan(IndexScanDesc s)
        prev = l;
 
    if (l == (GISTScanList) NULL)
-       elog(ERROR, "GiST scan list corrupted -- cannot find 0x%p", (void*)s);
+       elog(ERROR, "GiST scan list corrupted -- cannot find 0x%p", (void *) s);
 
    if (prev == (GISTScanList) NULL)
        GISTScans = l->gsl_next;
index d116aa1a4997131f44738527c1d180c45cfb6c50..1e5bc15bf2fadbe3339da23beb059622168bcf08 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/hash/hash.c,v 1.36 2000/03/01 05:39:22 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/hash/hash.c,v 1.37 2000/04/12 17:14:43 momjian Exp $
  *
  * NOTES
  *   This file contains only the public interface routines.
@@ -149,7 +149,7 @@ hashbuild(Relation heap,
 #ifndef OMIT_PARTIAL_INDEX
            /* SetSlotContents(slot, htup); */
            slot->val = htup;
-           if (! ExecQual((List *) pred, econtext, false))
+           if (!ExecQual((List *) pred, econtext, false))
                continue;
 #endif  /* OMIT_PARTIAL_INDEX */
        }
@@ -230,18 +230,18 @@ hashbuild(Relation heap,
    /*
     * Since we just counted the tuples in the heap, we update its stats
     * in pg_class to guarantee that the planner takes advantage of the
-    * index we just created.  But, only update statistics during
-    * normal index definitions, not for indices on system catalogs
-    * created during bootstrap processing.  We must close the relations
-    * before updating statistics to guarantee that the relcache entries
-    * are flushed when we increment the command counter in UpdateStats().
-    * But we do not release any locks on the relations; those will be
-    * held until end of transaction.
+    * index we just created.  But, only update statistics during normal
+    * index definitions, not for indices on system catalogs created
+    * during bootstrap processing.  We must close the relations before
+    * updating statistics to guarantee that the relcache entries are
+    * flushed when we increment the command counter in UpdateStats(). But
+    * we do not release any locks on the relations; those will be held
+    * until end of transaction.
     */
    if (IsNormalProcessingMode())
    {
-       Oid     hrelid = RelationGetRelid(heap);
-       Oid     irelid = RelationGetRelid(index);
+       Oid         hrelid = RelationGetRelid(heap);
+       Oid         irelid = RelationGetRelid(index);
        bool        inplace = IsReindexProcessing();
 
        heap_close(heap, NoLock);
index 78af6353f0ba15c417057a9004851fa8d8ee1083..80d9ac3741c01566689620526f10ce428ea9ded1 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/hash/hashfunc.c,v 1.24 2000/02/21 03:36:46 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/hash/hashfunc.c,v 1.25 2000/04/12 17:14:44 momjian Exp $
  *
  * NOTES
  *   These functions are stored in pg_amproc.  For each operator class
@@ -146,14 +146,14 @@ hashoidvector(Oid *key)
    int         i;
    uint32      result = 0;
 
-   for (i = INDEX_MAX_KEYS; --i >= 0; )
+   for (i = INDEX_MAX_KEYS; --i >= 0;)
        result = (result << 1) ^ (~(uint32) key[i]);
    return result;
 }
 
 /*
  * Note: hashint2vector currently can't be used as a user hash table
- * hash function, because it has no pg_proc entry.  We only need it
+ * hash function, because it has no pg_proc entry. We only need it
  * for catcache indexing.
  */
 uint32
@@ -162,7 +162,7 @@ hashint2vector(int16 *key)
    int         i;
    uint32      result = 0;
 
-   for (i = INDEX_MAX_KEYS; --i >= 0; )
+   for (i = INDEX_MAX_KEYS; --i >= 0;)
        result = (result << 1) ^ (~(uint32) key[i]);
    return result;
 }
index d44ba69b9bd97d9ad39919d77c0224d67e08ad17..979baf8d70c72ebfab42479ee9a54ee4dbd1198e 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/hash/hashscan.c,v 1.22 2000/01/26 05:55:55 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/hash/hashscan.c,v 1.23 2000/04/12 17:14:44 momjian Exp $
  *
  * NOTES
  *   Because we can be doing an index scan on a relation while we
@@ -75,7 +75,7 @@ _hash_dropscan(IndexScanDesc scan)
        last = chk;
 
    if (chk == (HashScanList) NULL)
-       elog(ERROR, "hash scan list trashed; can't find 0x%p", (void*)scan);
+       elog(ERROR, "hash scan list trashed; can't find 0x%p", (void *) scan);
 
    if (last == (HashScanList) NULL)
        HashScans = chk->hashsl_next;
index d6ae498d19d285745c4780e46d7959eae7279804..21f45f471370e38d8dc5ca54a554d87d0674022b 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/hash/hashsearch.c,v 1.23 2000/03/17 02:36:02 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/hash/hashsearch.c,v 1.24 2000/04/12 17:14:44 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -351,7 +351,7 @@ _hash_step(IndexScanDesc scan, Buffer *bufP, ScanDirection dir, Buffer metabuf)
                            opaque = (HashPageOpaque) PageGetSpecialPointer(page);
                            Assert(opaque->hasho_bucket == bucket);
                            while (PageIsEmpty(page) &&
-                                  BlockNumberIsValid(opaque->hasho_nextblkno))
+                            BlockNumberIsValid(opaque->hasho_nextblkno))
                                _hash_readnext(rel, &buf, &page, &opaque);
                            maxoff = PageGetMaxOffsetNumber(page);
                            offnum = FirstOffsetNumber;
index d51705fa4726ff60cde33d7fd8f423aa8bffa8c2..29d6c9e0f9ec0208fb191a52eed1f75252f5edc9 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/heap/heapam.c,v 1.66 2000/02/09 03:49:47 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/heap/heapam.c,v 1.67 2000/04/12 17:14:45 momjian Exp $
  *
  *
  * INTERFACE ROUTINES
@@ -23,7 +23,7 @@
  *     heap_fetch      - retrive tuple with tid
  *     heap_insert     - insert tuple into a relation
  *     heap_delete     - delete a tuple from a relation
- *     heap_update - replace a tuple in a relation with another tuple
+ *     heap_update - replace a tuple in a relation with another tuple
  *     heap_markpos    - mark scan position
  *     heap_restrpos   - restore position to marked location
  *
@@ -120,9 +120,9 @@ initscan(HeapScanDesc scan,
         * ----------------
         */
        scan->rs_ntup.t_datamcxt = scan->rs_ctup.t_datamcxt =
-       scan->rs_ptup.t_datamcxt = NULL;
+           scan->rs_ptup.t_datamcxt = NULL;
        scan->rs_ntup.t_data = scan->rs_ctup.t_data =
-       scan->rs_ptup.t_data = NULL;
+           scan->rs_ptup.t_data = NULL;
        scan->rs_nbuf = scan->rs_cbuf = scan->rs_pbuf = InvalidBuffer;
    }
    else if (atend)
@@ -188,8 +188,9 @@ unpinscan(HeapScanDesc scan)
    if (BufferIsValid(scan->rs_nbuf))
        ReleaseBuffer(scan->rs_nbuf);
 
-   /* we don't bother to clear rs_pbuf etc --- caller must
-    * reinitialize them if scan descriptor is not being deleted.
+   /*
+    * we don't bother to clear rs_pbuf etc --- caller must reinitialize
+    * them if scan descriptor is not being deleted.
     */
 }
 
@@ -544,7 +545,7 @@ heap_open(Oid relationId, LOCKMODE lockmode)
    if (lockmode == NoLock)
        return r;               /* caller must check RelationIsValid! */
 
-   if (! RelationIsValid(r))
+   if (!RelationIsValid(r))
        elog(ERROR, "Relation %u does not exist", relationId);
 
    LockRelation(r, lockmode);
@@ -586,7 +587,7 @@ heap_openr(const char *relationName, LOCKMODE lockmode)
    if (lockmode == NoLock)
        return r;               /* caller must check RelationIsValid! */
 
-   if (! RelationIsValid(r))
+   if (!RelationIsValid(r))
        elog(ERROR, "Relation '%s' does not exist", relationName);
 
    LockRelation(r, lockmode);
@@ -646,7 +647,7 @@ heap_beginscan(Relation relation,
     *  sanity checks
     * ----------------
     */
-   if (! RelationIsValid(relation))
+   if (!RelationIsValid(relation))
        elog(ERROR, "heap_beginscan: !RelationIsValid(relation)");
 
    /* ----------------
@@ -659,7 +660,7 @@ heap_beginscan(Relation relation,
     *  Acquire AccessShareLock for the duration of the scan
     *
     *  Note: we could get an SI inval message here and consequently have
-    *  to rebuild the relcache entry.  The refcount increment above
+    *  to rebuild the relcache entry.  The refcount increment above
     *  ensures that we will rebuild it and not just flush it...
     * ----------------
     */
@@ -681,6 +682,7 @@ heap_beginscan(Relation relation,
    scan->rs_nkeys = (short) nkeys;
 
    if (nkeys)
+
        /*
         * we do this here instead of in initscan() because heap_rescan
         * also calls initscan() and we don't want to allocate memory
@@ -847,9 +849,7 @@ heap_getnext(HeapScanDesc scandesc, int backw)
 
        if (scan->rs_ptup.t_data == scan->rs_ctup.t_data &&
            BufferIsInvalid(scan->rs_pbuf))
-       {
            return NULL;
-       }
 
        /*
         * Copy the "current" tuple/buffer to "next". Pin/unpin the
@@ -1095,8 +1095,10 @@ heap_fetch(Relation relation,
    }
    else
    {
-       /* All checks passed, so return the tuple as valid.
-        * Caller is now responsible for releasing the buffer.
+
+       /*
+        * All checks passed, so return the tuple as valid. Caller is now
+        * responsible for releasing the buffer.
         */
        *userbuf = buffer;
    }
@@ -1109,17 +1111,18 @@ heap_fetch(Relation relation,
  */
 ItemPointer
 heap_get_latest_tid(Relation relation,
-          Snapshot snapshot,
-          ItemPointer tid)
+                   Snapshot snapshot,
+                   ItemPointer tid)
 {
    ItemId      lp = NULL;
    Buffer      buffer;
    PageHeader  dp;
-   OffsetNumber    offnum;
-   HeapTupleData   tp;
-   HeapTupleHeader t_data;
-   ItemPointerData ctid;
-   bool        invalidBlock,linkend;
+   OffsetNumber offnum;
+   HeapTupleData tp;
+   HeapTupleHeader t_data;
+   ItemPointerData ctid;
+   bool        invalidBlock,
+               linkend;
 
    /* ----------------
     *  get the buffer from the relation descriptor
@@ -1149,11 +1152,11 @@ heap_get_latest_tid(Relation relation,
            invalidBlock = false;
    }
    if (invalidBlock)
-   {   
+   {
        LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
        ReleaseBuffer(buffer);
        return NULL;
-   } 
+   }
 
    /* ----------------
     *  more sanity checks
@@ -1175,7 +1178,7 @@ heap_get_latest_tid(Relation relation,
                       snapshot, 0, (ScanKey) NULL);
 
    linkend = true;
-   if ((t_data->t_infomask & HEAP_XMAX_COMMITTED) && 
+   if ((t_data->t_infomask & HEAP_XMAX_COMMITTED) &&
        !ItemPointerEquals(tid, &ctid))
        linkend = false;
 
@@ -1186,7 +1189,7 @@ heap_get_latest_tid(Relation relation,
    {
        if (linkend)
            return NULL;
-       return heap_get_latest_tid(relation, snapshot, &ctid); 
+       return heap_get_latest_tid(relation, snapshot, &ctid);
    }
 
    return tid;
@@ -1300,10 +1303,11 @@ l1:
        LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
        if (TransactionIdDidAbort(xwait))
            goto l1;
-       /* 
-        * xwait is committed but if xwait had just marked
-        * the tuple for update then some other xaction could 
-        * update this tuple before we got to this point.
+
+       /*
+        * xwait is committed but if xwait had just marked the tuple for
+        * update then some other xaction could update this tuple before
+        * we got to this point.
         */
        if (tp.t_data->t_xmax != xwait)
            goto l1;
@@ -1345,11 +1349,11 @@ l1:
 }
 
 /*
- * heap_update - replace a tuple
+ * heap_update - replace a tuple
  */
 int
 heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
-            ItemPointer ctid)
+           ItemPointer ctid)
 {
    ItemId      lp;
    HeapTupleData oldtup;
@@ -1396,10 +1400,11 @@ l2:
        LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
        if (TransactionIdDidAbort(xwait))
            goto l2;
-       /* 
-        * xwait is committed but if xwait had just marked
-        * the tuple for update then some other xaction could 
-        * update this tuple before we got to this point.
+
+       /*
+        * xwait is committed but if xwait had just marked the tuple for
+        * update then some other xaction could update this tuple before
+        * we got to this point.
         */
        if (oldtup.t_data->t_xmax != xwait)
            goto l2;
@@ -1521,10 +1526,11 @@ l3:
        LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
        if (TransactionIdDidAbort(xwait))
            goto l3;
-       /* 
-        * xwait is committed but if xwait had just marked
-        * the tuple for update then some other xaction could 
-        * update this tuple before we got to this point.
+
+       /*
+        * xwait is committed but if xwait had just marked the tuple for
+        * update then some other xaction could update this tuple before
+        * we got to this point.
         */
        if (tuple->t_data->t_xmax != xwait)
            goto l3;
index b269ca90170c0eb3f1610df05533cc8452e4666f..3fc2a69df1a3fe914c9ee30418bda41cbad593b0 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Id: hio.c,v 1.30 2000/03/17 02:36:02 tgl Exp $
+ *   $Id: hio.c,v 1.31 2000/04/12 17:14:45 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -51,7 +51,7 @@ RelationPutHeapTuple(Relation relation,
    IncrHeapAccessStat(global_RelationPutHeapTuple);
 
    pageHeader = (Page) BufferGetPage(buffer);
-   len = MAXALIGN(tuple->t_len); /* be conservative */
+   len = MAXALIGN(tuple->t_len);       /* be conservative */
    Assert(len <= PageGetFreeSpace(pageHeader));
 
    offnum = PageAddItem((Page) pageHeader, (Item) tuple->t_data,
@@ -108,11 +108,11 @@ RelationPutHeapTupleAtEnd(Relation relation, HeapTuple tuple)
    ItemId      itemId;
    Item        item;
 
-   len = MAXALIGN(tuple->t_len); /* be conservative */
+   len = MAXALIGN(tuple->t_len);       /* be conservative */
 
    /*
-    * If we're gonna fail for oversize tuple, do it right away...
-    * this code should go away eventually.
+    * If we're gonna fail for oversize tuple, do it right away... this
+    * code should go away eventually.
     */
    if (len > MaxTupleSize)
        elog(ERROR, "Tuple is too big: size %u, max size %ld",
@@ -136,8 +136,8 @@ RelationPutHeapTupleAtEnd(Relation relation, HeapTuple tuple)
    lastblock = RelationGetNumberOfBlocks(relation);
 
    /*
-    * Get the last existing page --- may need to create the first one
-    * if this is a virgin relation.
+    * Get the last existing page --- may need to create the first one if
+    * this is a virgin relation.
     */
    if (lastblock == 0)
    {
@@ -168,12 +168,14 @@ RelationPutHeapTupleAtEnd(Relation relation, HeapTuple tuple)
 
        if (len > PageGetFreeSpace(pageHeader))
        {
+
            /*
-            * BUG: by elog'ing here, we leave the new buffer locked and not
-            * marked dirty, which may result in an invalid page header
-            * being left on disk.  But we should not get here given the
-            * test at the top of the routine, and the whole deal should
-            * go away when we implement tuple splitting anyway...
+            * BUG: by elog'ing here, we leave the new buffer locked and
+            * not marked dirty, which may result in an invalid page
+            * header being left on disk.  But we should not get here
+            * given the test at the top of the routine, and the whole
+            * deal should go away when we implement tuple splitting
+            * anyway...
             */
            elog(ERROR, "Tuple is too big: size %u", len);
        }
index 9176521a5fce192811badda304a4fb70dd787e76..3aadfb2cde08c44b2665333c844616c6d82af574 100644 (file)
@@ -2,13 +2,13 @@
  *
  * tuptoaster.c
  *   Support routines for external and compressed storage of
- *    variable size attributes.
+ *   variable size attributes.
  *
  * Copyright (c) 2000, PostgreSQL Global Development Group
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/heap/tuptoaster.c,v 1.2 2000/01/20 21:50:59 petere Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/heap/tuptoaster.c,v 1.3 2000/04/12 17:14:45 momjian Exp $
  *
  *
  * INTERFACE ROUTINES
 #ifdef TUPLE_TOASTER_ACTIVE
 
 void
-heap_tuple_toast_attrs (Relation rel, HeapTuple newtup, HeapTuple oldtup)
+heap_tuple_toast_attrs(Relation rel, HeapTuple newtup, HeapTuple oldtup)
 {
    return;
 }
 
 
-varattrib *
-heap_tuple_untoast_attr (varattrib *attr)
+varattrib  *
+heap_tuple_untoast_attr(varattrib * attr)
 {
    elog(ERROR, "heap_tuple_untoast_attr() called");
 }
 
 
-#endif /* TUPLE_TOASTER_ACTIVE */
+#endif  /* TUPLE_TOASTER_ACTIVE */
index 1bd02f839ad42236df3bdd5e1966495c7cc470f8..3530320637b016172d5817857e5cd6dfe2f575d3 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/index/genam.c,v 1.24 2000/03/14 23:52:01 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/index/genam.c,v 1.25 2000/04/12 17:14:47 momjian Exp $
  *
  * NOTES
  *   many of the old access method routines have been turned into
@@ -62,7 +62,7 @@
  *
  *     At the end of a scan, the AM's endscan routine undoes the locking,
  *     but does *not* call IndexScanEnd --- the higher-level index_endscan
- *     routine does that.  (We can't do it in the AM because index_endscan
+ *     routine does that.  (We can't do it in the AM because index_endscan
  *     still needs to touch the IndexScanDesc after calling the AM.)
  *
  *     Because of this, the AM does not have a choice whether to call
@@ -114,7 +114,10 @@ RelationGetIndexScan(Relation relation,
    ItemPointerSetInvalid(&scan->currentMarkData);
    ItemPointerSetInvalid(&scan->nextMarkData);
 
-   /* mark cached function lookup data invalid; it will be set on first use */
+   /*
+    * mark cached function lookup data invalid; it will be set on first
+    * use
+    */
    scan->fn_getnext.fn_oid = InvalidOid;
 
    if (numberOfKeys > 0)
index 2335693119829d6fc289c165b1b57b41361f6f72..e0672667c7fbba99d2a58950f13719351e5810f9 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/index/indexam.c,v 1.41 2000/03/14 23:52:01 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/index/indexam.c,v 1.42 2000/04/12 17:14:47 momjian Exp $
  *
  * INTERFACE ROUTINES
  *     index_open      - open an index relation by relationId
  *     index_open - open an index relation by relationId
  *
  *     presently the relcache routines do all the work we need
- *     to open/close index relations.  However, callers of index_open
+ *     to open/close index relations.  However, callers of index_open
  *     expect it to succeed, so we need to check for a failure return.
  *
- *     Note: we acquire no lock on the index.  An AccessShareLock is
+ *     Note: we acquire no lock on the index.  An AccessShareLock is
  *     acquired by index_beginscan (and released by index_endscan).
  * ----------------
  */
@@ -129,7 +129,7 @@ index_open(Oid relationId)
 
    r = RelationIdGetRelation(relationId);
 
-   if (! RelationIsValid(r))
+   if (!RelationIsValid(r))
        elog(ERROR, "Index %u does not exist", relationId);
 
    if (r->rd_rel->relkind != RELKIND_INDEX)
@@ -151,7 +151,7 @@ index_openr(char *relationName)
 
    r = RelationNameGetRelation(relationName);
 
-   if (! RelationIsValid(r))
+   if (!RelationIsValid(r))
        elog(ERROR, "Index '%s' does not exist", relationName);
 
    if (r->rd_rel->relkind != RELKIND_INDEX)
@@ -238,7 +238,7 @@ index_beginscan(Relation relation,
     *  Acquire AccessShareLock for the duration of the scan
     *
     *  Note: we could get an SI inval message here and consequently have
-    *  to rebuild the relcache entry.  The refcount increment above
+    *  to rebuild the relcache entry.  The refcount increment above
     *  ensures that we will rebuild it and not just flush it...
     * ----------------
     */
index fe956ead378aa133c6bc8650239103283b4712ce..b0864e505fac99084e40a3fd33304d7b97044854 100644 (file)
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/index/Attic/istrat.c,v 1.41 2000/02/18 09:29:16 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/index/Attic/istrat.c,v 1.42 2000/04/12 17:14:47 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -477,7 +477,7 @@ OperatorRelationFillScanKeyEntry(Relation operatorRelation,
 {
    HeapTuple   tuple;
    HeapScanDesc scan = NULL;
-   bool    cachesearch = (!IsBootstrapProcessingMode()) && IsCacheInitialized();
+   bool        cachesearch = (!IsBootstrapProcessingMode()) && IsCacheInitialized();
 
    if (cachesearch)
    {
@@ -547,7 +547,7 @@ IndexSupportInitialize(IndexStrategy indexStrategy,
    AttrNumber  attributeNumber;
    int         attributeIndex;
    Oid         operatorClassObjectId[INDEX_MAX_KEYS];
-   bool    cachesearch = (!IsBootstrapProcessingMode()) && IsCacheInitialized();
+   bool        cachesearch = (!IsBootstrapProcessingMode()) && IsCacheInitialized();
 
    if (cachesearch)
    {
@@ -674,7 +674,7 @@ IndexSupportInitialize(IndexStrategy indexStrategy,
            aform = (Form_pg_amop) GETSTRUCT(tuple);
            OperatorRelationFillScanKeyEntry(operatorRelation,
                                             aform->amopopr,
-                   StrategyMapGetScanKeyEntry(map, aform->amopstrategy));
+                  StrategyMapGetScanKeyEntry(map, aform->amopstrategy));
        }
 
        heap_endscan(scan);
index f66b9a0e8e24c79b97446d74d5f80b258374cea9..3e58c677a0082b7ab5c8567065c5ea8ade420f8f 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtcompare.c,v 1.33 2000/02/10 19:51:38 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtcompare.c,v 1.34 2000/04/12 17:14:49 momjian Exp $
  *
  * NOTES
  *     These functions are stored in pg_amproc.  For each operator class
@@ -35,12 +35,12 @@ btint2cmp(int16 a, int16 b)
 int32
 btint4cmp(int32 a, int32 b)
 {
-      if (a > b)
-              return 1;
-      else if (a == b)
-              return 0;
-      else
-              return -1;
+   if (a > b)
+       return 1;
+   else if (a == b)
+       return 0;
+   else
+       return -1;
 }
 
 int32
index b891716a895bec4d02c71a01acec233f274d7ce1..975b53d658ac0a803bbe713722b8afa283be7fdc 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtinsert.c,v 1.56 2000/03/17 02:36:03 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtinsert.c,v 1.57 2000/04/12 17:14:49 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
 
 static InsertIndexResult _bt_insertonpg(Relation rel, Buffer buf, BTStack stack, int keysz, ScanKey scankey, BTItem btitem, BTItem afteritem);
 static Buffer _bt_split(Relation rel, Size keysz, ScanKey scankey,
-                       Buffer buf, OffsetNumber firstright);
+         Buffer buf, OffsetNumber firstright);
 static OffsetNumber _bt_findsplitloc(Relation rel, Size keysz, ScanKey scankey,
-                                    Page page, OffsetNumber start,
-                                    OffsetNumber maxoff, Size llimit);
+                Page page, OffsetNumber start,
+                OffsetNumber maxoff, Size llimit);
 static void _bt_newroot(Relation rel, Buffer lbuf, Buffer rbuf);
 static OffsetNumber _bt_pgaddtup(Relation rel, Buffer buf, int keysz, ScanKey itup_scankey, Size itemsize, BTItem btitem, BTItem afteritem);
 static bool _bt_goesonpg(Relation rel, Buffer buf, Size keysz, ScanKey scankey, BTItem afteritem);
@@ -267,21 +267,20 @@ _bt_insertonpg(Relation rel,
    itemsz = IndexTupleDSize(btitem->bti_itup)
        + (sizeof(BTItemData) - sizeof(IndexTupleData));
 
-   itemsz = MAXALIGN(itemsz);      /* be safe, PageAddItem will do
-                                        * this but we need to be
-                                        * consistent */
+   itemsz = MAXALIGN(itemsz);  /* be safe, PageAddItem will do this but
+                                * we need to be consistent */
 
    /*
-    * Check whether the item can fit on a btree page at all.
-    * (Eventually, we ought to try to apply TOAST methods if not.)
-    * We actually need to be able to fit three items on every page,
-    * so restrict any one item to 1/3 the per-page available space.
-    * Note that at this point, itemsz doesn't include the ItemId.
+    * Check whether the item can fit on a btree page at all. (Eventually,
+    * we ought to try to apply TOAST methods if not.) We actually need to
+    * be able to fit three items on every page, so restrict any one item
+    * to 1/3 the per-page available space. Note that at this point,
+    * itemsz doesn't include the ItemId.
     */
-   if (itemsz > (PageGetPageSize(page)-sizeof(PageHeaderData)-MAXALIGN(sizeof(BTPageOpaqueData)))/3 - sizeof(ItemIdData))
+   if (itemsz > (PageGetPageSize(page) - sizeof(PageHeaderData) - MAXALIGN(sizeof(BTPageOpaqueData))) / 3 - sizeof(ItemIdData))
        elog(ERROR, "btree: index item size %u exceeds maximum %lu",
             itemsz,
-            (PageGetPageSize(page)-sizeof(PageHeaderData)-MAXALIGN(sizeof(BTPageOpaqueData)))/3 - sizeof(ItemIdData));
+            (PageGetPageSize(page) - sizeof(PageHeaderData) - MAXALIGN(sizeof(BTPageOpaqueData))) /3 - sizeof(ItemIdData));
 
    /*
     * If we have to insert item on the leftmost page which is the first
@@ -415,8 +414,8 @@ _bt_insertonpg(Relation rel,
        bool        is_root = lpageop->btpo_flags & BTP_ROOT;
 
        /*
-        * Instead of splitting leaf page in the chain of duplicates 
-        * by new duplicate, insert it into some right page.
+        * Instead of splitting leaf page in the chain of duplicates by
+        * new duplicate, insert it into some right page.
         */
        if ((lpageop->btpo_flags & BTP_CHAIN) &&
            (lpageop->btpo_flags & BTP_LEAF) && keys_equal)
@@ -424,8 +423,9 @@ _bt_insertonpg(Relation rel,
            rbuf = _bt_getbuf(rel, lpageop->btpo_next, BT_WRITE);
            rpage = BufferGetPage(rbuf);
            rpageop = (BTPageOpaque) PageGetSpecialPointer(rpage);
-           /* 
-            * some checks 
+
+           /*
+            * some checks
             */
            if (!P_RIGHTMOST(rpageop))  /* non-rightmost page */
            {                   /* If we have the same hikey here then
@@ -442,6 +442,7 @@ _bt_insertonpg(Relation rel,
                                     BTGreaterStrategyNumber))
                    elog(FATAL, "btree: hikey is out of order");
                else if (rpageop->btpo_flags & BTP_CHAIN)
+
                    /*
                     * If hikey > scankey then it's last page in chain and
                     * BTP_CHAIN must be OFF
@@ -450,9 +451,7 @@ _bt_insertonpg(Relation rel,
            }
            else
 /* rightmost page */
-           {
                Assert(!(rpageop->btpo_flags & BTP_CHAIN));
-           }
            _bt_relbuf(rel, buf, BT_WRITE);
            return (_bt_insertonpg(rel, rbuf, stack, keysz,
                                   scankey, btitem, afteritem));
@@ -708,7 +707,7 @@ l_spl:  ;
                 */
                if (!parent_chained &&
                    MAXALIGN(IndexTupleDSize(lowLeftItem->bti_itup)) ==
-                   MAXALIGN(IndexTupleDSize(stack->bts_btitem->bti_itup)))
+                 MAXALIGN(IndexTupleDSize(stack->bts_btitem->bti_itup)))
                {
                    _bt_updateitem(rel, keysz, pbuf,
                                   stack->bts_btitem, lowLeftItem);
index 60eaf3a9d23f84277f2a2ca2b14b86061dfd42fe..1a623698f57c34711c62225384e7c73feb510281 100644 (file)
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtpage.c,v 1.35 2000/01/26 05:55:58 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtpage.c,v 1.36 2000/04/12 17:14:49 momjian Exp $
  *
  * NOTES
  *    Postgres btree pages look like ordinary relation pages.  The opaque
@@ -257,7 +257,7 @@ _bt_getroot(Relation rel, int access)
    else
    {
        rootblkno = metad->btm_root;
-       _bt_relbuf(rel, metabuf, BT_READ);  /* done with the meta page */
+       _bt_relbuf(rel, metabuf, BT_READ);      /* done with the meta page */
 
        rootbuf = _bt_getbuf(rel, rootblkno, access);
    }
index da5dd70332e5b07a5552b309a98d52828298f684..72969d4d1b79b4729d3bd41aa508ebf6c5476ddd 100644 (file)
@@ -12,7 +12,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtree.c,v 1.53 2000/02/18 09:29:54 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtree.c,v 1.54 2000/04/12 17:14:49 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -77,7 +77,7 @@ btbuild(Relation heap,
 #endif
    Node       *pred,
               *oldPred;
-   BTSpool    *spool = NULL;
+   BTSpool    *spool = NULL;
    bool        isunique;
    bool        usefast;
 
@@ -185,7 +185,7 @@ btbuild(Relation heap,
 #ifndef OMIT_PARTIAL_INDEX
            /* SetSlotContents(slot, htup); */
            slot->val = htup;
-           if (! ExecQual((List *) pred, econtext, false))
+           if (!ExecQual((List *) pred, econtext, false))
                continue;
 #endif  /* OMIT_PARTIAL_INDEX */
        }
@@ -276,9 +276,9 @@ btbuild(Relation heap,
    }
 
    /*
-    * if we are doing bottom-up btree build, finish the build by
-    * (1) completing the sort of the spool file, (2) inserting the
-    * sorted tuples into btree pages and (3) building the upper levels.
+    * if we are doing bottom-up btree build, finish the build by (1)
+    * completing the sort of the spool file, (2) inserting the sorted
+    * tuples into btree pages and (3) building the upper levels.
     */
    if (usefast)
    {
@@ -298,26 +298,27 @@ btbuild(Relation heap,
    /*
     * Since we just counted the tuples in the heap, we update its stats
     * in pg_class to guarantee that the planner takes advantage of the
-    * index we just created.  But, only update statistics during
-    * normal index definitions, not for indices on system catalogs
-    * created during bootstrap processing.  We must close the relations
-    * before updating statistics to guarantee that the relcache entries
-    * are flushed when we increment the command counter in UpdateStats().
-    * But we do not release any locks on the relations; those will be
-    * held until end of transaction.
+    * index we just created.  But, only update statistics during normal
+    * index definitions, not for indices on system catalogs created
+    * during bootstrap processing.  We must close the relations before
+    * updating statistics to guarantee that the relcache entries are
+    * flushed when we increment the command counter in UpdateStats(). But
+    * we do not release any locks on the relations; those will be held
+    * until end of transaction.
     */
    if (IsNormalProcessingMode())
    {
-       Oid     hrelid = RelationGetRelid(heap);
-       Oid     irelid = RelationGetRelid(index);
+       Oid         hrelid = RelationGetRelid(heap);
+       Oid         irelid = RelationGetRelid(index);
        bool        inplace = IsReindexProcessing();
 
        heap_close(heap, NoLock);
        index_close(index);
+
        /*
-       UpdateStats(hrelid, nhtups, true);
-       UpdateStats(irelid, nitups, false);
-       */
+        * UpdateStats(hrelid, nhtups, true); UpdateStats(irelid, nitups,
+        * false);
+        */
        UpdateStats(hrelid, nhtups, inplace);
        UpdateStats(irelid, nitups, inplace);
        if (oldPred != NULL)
@@ -623,7 +624,7 @@ _bt_restscan(IndexScanDesc scan)
    BTItem      item;
    BlockNumber blkno;
 
-   LockBuffer(buf, BT_READ);       /* lock buffer first! */
+   LockBuffer(buf, BT_READ);   /* lock buffer first! */
    page = BufferGetPage(buf);
    maxoff = PageGetMaxOffsetNumber(page);
    opaque = (BTPageOpaque) PageGetSpecialPointer(page);
index 95b1bf53ecbf8d332345927fdf7fd1592122c8fe..37469365bcd42e2b37c06346341d6a9bdf9e95ab 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/Attic/nbtscan.c,v 1.30 2000/01/26 05:55:58 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/Attic/nbtscan.c,v 1.31 2000/04/12 17:14:49 momjian Exp $
  *
  *
  * NOTES
@@ -52,13 +52,16 @@ static void _bt_scandel(IndexScanDesc scan, BlockNumber blkno, OffsetNumber offn
 void
 AtEOXact_nbtree(void)
 {
-   /* Note: these actions should only be necessary during xact abort;
-    * but they can't hurt during a commit.
+
+   /*
+    * Note: these actions should only be necessary during xact abort; but
+    * they can't hurt during a commit.
     */
 
-   /* Reset the active-scans list to empty.
-    * We do not need to free the list elements, because they're all
-    * palloc()'d, so they'll go away at end of transaction anyway.
+   /*
+    * Reset the active-scans list to empty. We do not need to free the
+    * list elements, because they're all palloc()'d, so they'll go away
+    * at end of transaction anyway.
     */
    BTScans = NULL;
 
@@ -96,7 +99,7 @@ _bt_dropscan(IndexScanDesc scan)
        last = chk;
 
    if (chk == (BTScanList) NULL)
-       elog(ERROR, "btree scan list trashed; can't find 0x%p", (void*)scan);
+       elog(ERROR, "btree scan list trashed; can't find 0x%p", (void *) scan);
 
    if (last == (BTScanList) NULL)
        BTScans = chk->btsl_next;
index f36da9743f852f577e5b0b672dee82ec7c16e745..cad117e5e6174f239764079d3679ef90c2b61157 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsearch.c,v 1.58 2000/03/17 02:36:04 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsearch.c,v 1.59 2000/04/12 17:14:49 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -299,9 +299,7 @@ _bt_skeycmp(Relation rel,
            compare = -1;       /* not-NULL key "<" NULL datum */
        }
        else
-       {
            compare = (int32) FMGR_PTR2(&entry->sk_func, keyDatum, attrDatum);
-       }
 
        if (compare != 0)
            break;              /* done when we find unequal attributes */
@@ -368,26 +366,26 @@ _bt_binsrch(Relation rel,
 
    /*
     * If there are no keys on the page, return the first available slot.
-    * Note this covers two cases: the page is really empty (no keys),
-    * or it contains only a high key.  The latter case is possible after
+    * Note this covers two cases: the page is really empty (no keys), or
+    * it contains only a high key.  The latter case is possible after
     * vacuuming.
     */
    if (high < low)
        return low;
 
    /*
-    * Binary search to find the first key on the page >= scan key.
-    * Loop invariant: all slots before 'low' are < scan key, all slots
-    * at or after 'high' are >= scan key.  Also, haveEq is true if the
-    * tuple at 'high' is == scan key.
-    * We can fall out when high == low.
+    * Binary search to find the first key on the page >= scan key. Loop
+    * invariant: all slots before 'low' are < scan key, all slots at or
+    * after 'high' are >= scan key.  Also, haveEq is true if the tuple at
+    * 'high' is == scan key. We can fall out when high == low.
     */
    high++;                     /* establish the loop invariant for high */
    haveEq = false;
 
    while (high > low)
    {
-       OffsetNumber    mid = low + ((high - low) / 2);
+       OffsetNumber mid = low + ((high - low) / 2);
+
        /* We have low <= mid < high, so mid points at a real slot */
 
        result = _bt_compare(rel, itupdesc, page, keysz, scankey, mid);
@@ -403,7 +401,7 @@ _bt_binsrch(Relation rel,
 
    /*--------------------
     * At this point we have high == low, but be careful: they could point
-    * past the last slot on the page.  We also know that haveEq is true
+    * past the last slot on the page.  We also know that haveEq is true
     * if and only if there is an equal key (in which case high&low point
     * at the first equal key).
     *
@@ -443,18 +441,20 @@ _bt_binsrch(Relation rel,
 
    if (haveEq)
    {
+
        /*
         * There is an equal key.  We return either the first equal key
         * (which we just found), or the last lesser key.
         *
-        * We need not check srchtype != BT_DESCENT here, since if that
-        * is true then natts == keysz by assumption.
+        * We need not check srchtype != BT_DESCENT here, since if that is
+        * true then natts == keysz by assumption.
         */
        if (natts == keysz)
            return low;         /* return first equal key */
    }
    else
    {
+
        /*
         * There is no equal key.  We return either the first greater key
         * (which we just found), or the last lesser key.
@@ -524,6 +524,7 @@ _bt_compare(Relation rel,
        && P_LEFTMOST(opaque)
        && offnum == P_HIKEY)
    {
+
        /*
         * we just have to believe that this will only be called with
         * offnum == P_HIKEY when P_HIKEY is the OffsetNumber of the first
@@ -702,11 +703,12 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
 
    bool        strategyCheck;
    ScanKey     scankeys = 0;
-   int     keysCount = 0;
-   int     *nKeyIs = 0;
-   int     i, j;
-   StrategyNumber  strat_total;
-       
+   int         keysCount = 0;
+   int        *nKeyIs = 0;
+   int         i,
+               j;
+   StrategyNumber strat_total;
+
    rel = scan->relation;
    so = (BTScanOpaque) scan->opaque;
 
@@ -723,15 +725,15 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
        _bt_orderkeys(rel, so);
 
        if (so->qual_ok)
-            strategyCheck = true;
-   }
+           strategyCheck = true;
+   }
    strat_total = BTEqualStrategyNumber;
    if (strategyCheck)
    {
        AttrNumber  attno;
 
-       nKeyIs = (int *)palloc(so->numberOfKeys*sizeof(int));
-       for (i=0; i < so->numberOfKeys; i++)
+       nKeyIs = (int *) palloc(so->numberOfKeys * sizeof(int));
+       for (i = 0; i < so->numberOfKeys; i++)
        {
            attno = so->keyData[i].sk_attno;
            if (attno == keysCount)
@@ -739,16 +741,16 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
            if (attno > keysCount + 1)
                break;
            strat = _bt_getstrat(rel, attno,
-                   so->keyData[i].sk_procedure);
+                                so->keyData[i].sk_procedure);
            if (strat == strat_total ||
-               strat == BTEqualStrategyNumber)
+               strat == BTEqualStrategyNumber)
            {
                nKeyIs[keysCount++] = i;
                continue;
            }
            if (ScanDirectionIsBackward(dir) &&
-               (strat == BTLessStrategyNumber ||
-                strat == BTLessEqualStrategyNumber) )
+               (strat == BTLessStrategyNumber ||
+                strat == BTLessEqualStrategyNumber))
            {
                nKeyIs[keysCount++] = i;
                strat_total = strat;
@@ -757,8 +759,8 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
                continue;
            }
            if (ScanDirectionIsForward(dir) &&
-               (strat == BTGreaterStrategyNumber ||
-                strat == BTGreaterEqualStrategyNumber) )
+               (strat == BTGreaterStrategyNumber ||
+                strat == BTGreaterEqualStrategyNumber))
            {
                nKeyIs[keysCount++] = i;
                strat_total = strat;
@@ -794,8 +796,8 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
     * at the right place in the scan.
     */
    /* _bt_orderkeys disallows it, but it's place to add some code latter */
-   scankeys = (ScanKey)palloc(keysCount*sizeof(ScanKeyData));
-   for (i=0; i < keysCount; i++)
+   scankeys = (ScanKey) palloc(keysCount * sizeof(ScanKeyData));
+   for (i = 0; i < keysCount; i++)
    {
        j = nKeyIs[i];
        if (so->keyData[j].sk_flags & SK_ISNULL)
@@ -804,12 +806,13 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
            pfree(scankeys);
            elog(ERROR, "_bt_first: btree doesn't support is(not)null, yet");
            return ((RetrieveIndexResult) NULL);
-       } 
-       proc = index_getprocid(rel, i+1, BTORDER_PROC);
-       ScanKeyEntryInitialize(scankeys+i, so->keyData[j].sk_flags,
-               i+1, proc, so->keyData[j].sk_argument);
+       }
+       proc = index_getprocid(rel, i + 1, BTORDER_PROC);
+       ScanKeyEntryInitialize(scankeys + i, so->keyData[j].sk_flags,
+                              i + 1, proc, so->keyData[j].sk_argument);
    }
-   if   (nKeyIs)   pfree(nKeyIs);
+   if (nKeyIs)
+       pfree(nKeyIs);
 
    stack = _bt_search(rel, keysCount, scankeys, &buf);
    _bt_freestack(stack);
index f9cbf7121ff4fb078723e226e6e81255dbbc3d48..65e757e42b3b176ab7560768ed980e0d500d0d44 100644 (file)
@@ -6,7 +6,7 @@
  *
  * We use tuplesort.c to sort the given index tuples into order.
  * Then we scan the index tuples in order and build the btree pages
- * for each level.  When we have only one page on a level, it must be the
+ * for each level. When we have only one page on a level, it must be the
  * root -- it can be attached to the btree metapage and we are done.
  *
  * this code is moderately slow (~10% slower) compared to the regular
@@ -28,7 +28,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsort.c,v 1.51 2000/02/18 06:32:39 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsort.c,v 1.52 2000/04/12 17:14:49 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -70,12 +70,12 @@ struct BTSpool
 
 static void _bt_load(Relation index, BTSpool *btspool);
 static BTItem _bt_buildadd(Relation index, Size keysz, ScanKey scankey,
-                          BTPageState *state, BTItem bti, int flags);
+            BTPageState *state, BTItem bti, int flags);
 static BTItem _bt_minitem(Page opage, BlockNumber oblkno, int atend);
 static BTPageState *_bt_pagestate(Relation index, int flags,
-                                 int level, bool doupper);
+             int level, bool doupper);
 static void _bt_uppershutdown(Relation index, Size keysz, ScanKey scankey,
-                             BTPageState *state);
+                 BTPageState *state);
 
 
 /*
@@ -86,7 +86,7 @@ static void _bt_uppershutdown(Relation index, Size keysz, ScanKey scankey,
 /*
  * create and initialize a spool structure
  */
-BTSpool *
+BTSpool    *
 _bt_spoolinit(Relation index, bool isunique)
 {
    BTSpool    *btspool = (BTSpool *) palloc(sizeof(BTSpool));
@@ -99,9 +99,9 @@ _bt_spoolinit(Relation index, bool isunique)
    btspool->sortstate = tuplesort_begin_index(index, isunique, false);
 
    /*
-    * Currently, tuplesort provides sort functions on IndexTuples.
-    * If we kept anything in a BTItem other than a regular IndexTuple,
-    * we'd need to modify tuplesort to understand BTItems as such.
+    * Currently, tuplesort provides sort functions on IndexTuples. If we
+    * kept anything in a BTItem other than a regular IndexTuple, we'd
+    * need to modify tuplesort to understand BTItems as such.
     */
    Assert(sizeof(BTItemData) == sizeof(IndexTupleData));
 
@@ -306,20 +306,20 @@ _bt_buildadd(Relation index, Size keysz, ScanKey scankey,
    btisz = MAXALIGN(btisz);
 
    /*
-    * Check whether the item can fit on a btree page at all.
-    * (Eventually, we ought to try to apply TOAST methods if not.)
-    * We actually need to be able to fit three items on every page,
-    * so restrict any one item to 1/3 the per-page available space.
-    * Note that at this point, btisz doesn't include the ItemId.
+    * Check whether the item can fit on a btree page at all. (Eventually,
+    * we ought to try to apply TOAST methods if not.) We actually need to
+    * be able to fit three items on every page, so restrict any one item
+    * to 1/3 the per-page available space. Note that at this point, btisz
+    * doesn't include the ItemId.
     *
     * NOTE: similar code appears in _bt_insertonpg() to defend against
-    * oversize items being inserted into an already-existing index.
-    * But during creation of an index, we don't go through there.
+    * oversize items being inserted into an already-existing index. But
+    * during creation of an index, we don't go through there.
     */
-   if (btisz > (PageGetPageSize(npage)-sizeof(PageHeaderData)-MAXALIGN(sizeof(BTPageOpaqueData)))/3 - sizeof(ItemIdData))
+   if (btisz > (PageGetPageSize(npage) - sizeof(PageHeaderData) - MAXALIGN(sizeof(BTPageOpaqueData))) / 3 - sizeof(ItemIdData))
        elog(ERROR, "btree: index item size %d exceeds maximum %ld",
             btisz,
-            (PageGetPageSize(npage)-sizeof(PageHeaderData)-MAXALIGN(sizeof(BTPageOpaqueData)))/3 - sizeof(ItemIdData));
+            (PageGetPageSize(npage) - sizeof(PageHeaderData) - MAXALIGN(sizeof(BTPageOpaqueData))) /3 - sizeof(ItemIdData));
 
    if (pgspc < btisz)
    {
index 9d1cc7b10d0531f07d566b8847f56bc2f28e4a7d..38b152e61b28b214fa6c3a2afd848bf94fdfc7a7 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtutils.c,v 1.35 2000/02/18 06:32:39 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtutils.c,v 1.36 2000/04/12 17:14:50 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -141,7 +141,8 @@ _bt_orderkeys(Relation relation, BTScanOpaque so)
    uint16      numberOfKeys = so->numberOfKeys;
    uint16      new_numberOfKeys = 0;
    AttrNumber  attno = 1;
-   bool        equalStrategyEnd, underEqualStrategy;
+   bool        equalStrategyEnd,
+               underEqualStrategy;
 
    if (numberOfKeys < 1)
        return;
@@ -194,6 +195,7 @@ _bt_orderkeys(Relation relation, BTScanOpaque so)
                elog(ERROR, "_bt_orderkeys: key(s) for attribute %d missed", attno + 1);
 
            underEqualStrategy = (!equalStrategyEnd);
+
            /*
             * If = has been specified, no other key will be used. In case
             * of key < 2 && key == 1 and so on we have to set qual_ok to
index 34cf0b6c9370e1d038d232b744871a2fdfda717e..53e5345a55d75f38219b800ee45ed82ff8e546c8 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtree.c,v 1.44 2000/03/01 05:39:23 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtree.c,v 1.45 2000/04/12 17:14:51 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -181,7 +181,7 @@ rtbuild(Relation heap,
 #ifndef OMIT_PARTIAL_INDEX
            /* SetSlotContents(slot, htup); */
            slot->val = htup;
-           if (! ExecQual((List *) pred, econtext, false))
+           if (!ExecQual((List *) pred, econtext, false))
                continue;
 #endif  /* OMIT_PARTIAL_INDEX */
        }
@@ -249,18 +249,18 @@ rtbuild(Relation heap,
    /*
     * Since we just counted the tuples in the heap, we update its stats
     * in pg_class to guarantee that the planner takes advantage of the
-    * index we just created.  But, only update statistics during
-    * normal index definitions, not for indices on system catalogs
-    * created during bootstrap processing.  We must close the relations
-    * before updating statistics to guarantee that the relcache entries
-    * are flushed when we increment the command counter in UpdateStats().
-    * But we do not release any locks on the relations; those will be
-    * held until end of transaction.
+    * index we just created.  But, only update statistics during normal
+    * index definitions, not for indices on system catalogs created
+    * during bootstrap processing.  We must close the relations before
+    * updating statistics to guarantee that the relcache entries are
+    * flushed when we increment the command counter in UpdateStats(). But
+    * we do not release any locks on the relations; those will be held
+    * until end of transaction.
     */
    if (IsNormalProcessingMode())
    {
-       Oid     hrelid = RelationGetRelid(heap);
-       Oid     irelid = RelationGetRelid(index);
+       Oid         hrelid = RelationGetRelid(heap);
+       Oid         irelid = RelationGetRelid(index);
        bool        inplace = IsReindexProcessing();
 
        heap_close(heap, NoLock);
index ada386127788ed34e07403737d34b440c93f5f20..71e2acf5f88d0be5cf97e28763afa50a57a0ecbf 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtscan.c,v 1.31 2000/01/26 05:56:00 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtscan.c,v 1.32 2000/04/12 17:14:51 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -268,7 +268,7 @@ rtdropscan(IndexScanDesc s)
        prev = l;
 
    if (l == (RTScanList) NULL)
-       elog(ERROR, "rtree scan list corrupted -- cannot find 0x%p", (void*)s);
+       elog(ERROR, "rtree scan list corrupted -- cannot find 0x%p", (void *) s);
 
    if (prev == (RTScanList) NULL)
        RTScans = l->rtsl_next;
index 36d50f08c0c32937d908c6a6ee2957a7d1da03a9..4efb53ea08c1ac14729c484f51f6dc9701e5b430 100644 (file)
@@ -1,4 +1,4 @@
 #include "postgres.h"
 #include "access/rmgr.h"
 
-RmgrData      *RmgrTable = NULL;
+RmgrData   *RmgrTable = NULL;
index a5af2bdc533a43810bd4c5f081c4f59ed805c859..acca4a901a2f16083d1eff601ec4647046d1b527 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/transam/transam.c,v 1.33 2000/01/26 05:56:03 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/transam/transam.c,v 1.34 2000/04/12 17:14:52 momjian Exp $
  *
  * NOTES
  *   This file contains the high level access-method interface to the
@@ -162,6 +162,7 @@ TransactionLogTest(TransactionId transactionId, /* transaction id to test */
 
    if (!fail)
    {
+
        /*
         * DO NOT cache status for transactions in unknown state !!!
         */
index 6a31bfe429ecc50feea01380d44646a721069707..5ce334aa299682048c966bc19bc859fa8df0e24e 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/transam/varsup.c,v 1.27 2000/03/31 02:43:31 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/transam/varsup.c,v 1.28 2000/04/12 17:14:53 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -331,8 +331,8 @@ ReadNewTransactionId(TransactionId *xid)
    SpinAcquire(OidGenLockId);  /* not good for concurrency... */
 
    /*
-    * Note that we don't check is ShmemVariableCache->xid_count equal
-    * to 0 or not. This will work as long as we don't call 
+    * Note that we don't check is ShmemVariableCache->xid_count equal to
+    * 0 or not. This will work as long as we don't call
     * ReadNewTransactionId() before GetNewTransactionId().
     */
    if (ShmemVariableCache->nextXid == 0)
index 2522cca46c12296a4abfe76bc6391c120fede8ae..688741511fbaa8b280972b41cf95eac3da3c4f88 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/access/transam/xact.c,v 1.63 2000/04/09 04:43:16 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/access/transam/xact.c,v 1.64 2000/04/12 17:14:53 momjian Exp $
  *
  * NOTES
  *     Transaction aborts can now occur two ways:
 #include "utils/portal.h"
 #include "utils/relcache.h"
 
-extern bool    SharedBufferChanged;
+extern bool SharedBufferChanged;
 
 static void AbortTransaction(void);
 static void AtAbort_Cache(void);
@@ -517,8 +517,8 @@ CommandCounterIncrement()
    CurrentTransactionStateData.scanCommandId = CurrentTransactionStateData.commandId;
 
    /*
-    * make cache changes visible to me.  AtCommit_LocalCache()
-    * instead of AtCommit_Cache() is called here.
+    * make cache changes visible to me.  AtCommit_LocalCache() instead of
+    * AtCommit_Cache() is called here.
     */
    AtCommit_LocalCache();
    AtStart_Cache();
@@ -627,16 +627,15 @@ RecordTransactionCommit()
     */
    xid = GetCurrentTransactionId();
 
-   /* 
-    *  flush the buffer manager pages.  Note: if we have stable
-    *  main memory, dirty shared buffers are not flushed
-    *  plai 8/7/90
+   /*
+    * flush the buffer manager pages.  Note: if we have stable main
+    * memory, dirty shared buffers are not flushed plai 8/7/90
     */
    leak = BufferPoolCheckLeak();
 
    /*
-    * If no one shared buffer was changed by this transaction then
-    * we don't flush shared buffers and don't record commit status.
+    * If no one shared buffer was changed by this transaction then we
+    * don't flush shared buffers and don't record commit status.
     */
    if (SharedBufferChanged)
    {
@@ -645,13 +644,13 @@ RecordTransactionCommit()
            ResetBufferPool(true);
 
        /*
-        *  have the transaction access methods record the status
-        *  of this transaction id in the pg_log relation.
+        * have the transaction access methods record the status of this
+        * transaction id in the pg_log relation.
         */
        TransactionIdCommit(xid);
 
        /*
-        *  Now write the log info to the disk too.
+        * Now write the log info to the disk too.
         */
        leak = BufferPoolCheckLeak();
        FlushBufferPool();
@@ -751,10 +750,10 @@ RecordTransactionAbort()
     */
    xid = GetCurrentTransactionId();
 
-   /* 
-    * Have the transaction access methods record the status of
-    * this transaction id in the pg_log relation. We skip it
-    * if no one shared buffer was changed by this transaction.
+   /*
+    * Have the transaction access methods record the status of this
+    * transaction id in the pg_log relation. We skip it if no one shared
+    * buffer was changed by this transaction.
     */
    if (SharedBufferChanged && !TransactionIdDidCommit(xid))
        TransactionIdAbort(xid);
@@ -936,7 +935,7 @@ CommitTransaction()
    /* ----------------
     *  Tell the trigger manager that this transaction is about to be
     *  committed. He'll invoke all trigger deferred until XACT before
-    *  we really start on committing the transaction. 
+    *  we really start on committing the transaction.
     * ----------------
     */
    DeferredTriggerEndXact();
@@ -965,13 +964,13 @@ CommitTransaction()
    RecordTransactionCommit();
 
    /*
-    * Let others know about no transaction in progress by me.
-    * Note that this must be done _before_ releasing locks we hold 
-    * and SpinAcquire(SInvalLock) is required: UPDATE with xid 0 is 
-    * blocked by xid 1' UPDATE, xid 1 is doing commit while xid 2 
-    * gets snapshot - if xid 2' GetSnapshotData sees xid 1 as running
-    * then it must see xid 0 as running as well or it will see two
-    * tuple versions - one deleted by xid 1 and one inserted by xid 0.
+    * Let others know about no transaction in progress by me. Note that
+    * this must be done _before_ releasing locks we hold and
+    * SpinAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked
+    * by xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot -
+    * if xid 2' GetSnapshotData sees xid 1 as running then it must see
+    * xid 0 as running as well or it will see two tuple versions - one
+    * deleted by xid 1 and one inserted by xid 0.
     */
    if (MyProc != (PROC *) NULL)
    {
@@ -995,7 +994,7 @@ CommitTransaction()
     * ----------------
     */
    s->state = TRANS_DEFAULT;
-   SharedBufferChanged = false;    /* safest place to do it */
+   SharedBufferChanged = false;/* safest place to do it */
 
 }
 
@@ -1031,7 +1030,7 @@ AbortTransaction()
 
    /* ----------------
     *  Tell the trigger manager that this transaction is about to be
-    *  aborted. 
+    *  aborted.
     * ----------------
     */
    DeferredTriggerAbortXact();
@@ -1070,7 +1069,7 @@ AbortTransaction()
     * ----------------
     */
    s->state = TRANS_DEFAULT;
-   SharedBufferChanged = false;    /* safest place to do it */
+   SharedBufferChanged = false;/* safest place to do it */
 }
 
 /* --------------------------------
index 7d197cb5a3a36b89e0dfa6fe35c308facc887a55..b672cf2c7a9621fbab60fa58ae37870be2e06718 100644 (file)
@@ -1,4 +1,4 @@
-/*------------------------------------------------------------------------- 
+/*-------------------------------------------------------------------------
  *
  * xlog.c
  *
@@ -6,7 +6,7 @@
  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- * $Header: /cvsroot/pgsql/src/backend/access/transam/xlog.c,v 1.12 2000/03/20 07:25:39 vadim Exp $
+ * $Header: /cvsroot/pgsql/src/backend/access/transam/xlog.c,v 1.13 2000/04/12 17:14:53 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -44,64 +44,64 @@ bool        StopIfError = false;
 SPINLOCK   ControlFileLockId;
 SPINLOCK   XidGenLockId;
 
-extern bool                ReleaseDataFile(void);
+extern bool ReleaseDataFile(void);
 
-extern VariableCache   ShmemVariableCache;
+extern VariableCache ShmemVariableCache;
 
-#define    MinXLOGbuffers  4
+#define MinXLOGbuffers 4
 
 typedef struct XLgwrRqst
 {
-   XLogRecPtr      Write;      /* byte (1-based) to write out */
-   XLogRecPtr      Flush;      /* byte (1-based) to flush */
+   XLogRecPtr  Write;          /* byte (1-based) to write out */
+   XLogRecPtr  Flush;          /* byte (1-based) to flush */
 } XLgwrRqst;
 
 typedef struct XLgwrResult
 {
-   XLogRecPtr      Write;      /* bytes written out */
-   XLogRecPtr      Flush;      /* bytes flushed */
+   XLogRecPtr  Write;          /* bytes written out */
+   XLogRecPtr  Flush;          /* bytes flushed */
 } XLgwrResult;
 
 typedef struct XLogCtlInsert
 {
-   XLgwrResult     LgwrResult;
-   XLogRecPtr      PrevRecord;
-   uint16          curridx;    /* current block index in cache */
-   XLogPageHeader  currpage;
-   char           *currpos;
+   XLgwrResult LgwrResult;
+   XLogRecPtr  PrevRecord;
+   uint16      curridx;        /* current block index in cache */
+   XLogPageHeader currpage;
+   char       *currpos;
 } XLogCtlInsert;
 
 typedef struct XLogCtlWrite
 {
-   XLgwrResult     LgwrResult;
-   uint16          curridx;    /* index of next block to write */
+   XLgwrResult LgwrResult;
+   uint16      curridx;        /* index of next block to write */
 } XLogCtlWrite;
 
 
 #ifndef HAS_TEST_AND_SET
-#define    TAS(lck)        0
-#define    S_UNLOCK(lck)
-#define    S_INIT_LOCK(lck)
+#define TAS(lck)       0
+#define S_UNLOCK(lck)
+#define S_INIT_LOCK(lck)
 #endif
 
 typedef struct XLogCtlData
 {
-   XLogCtlInsert   Insert;
-   XLgwrRqst       LgwrRqst;
-   XLgwrResult     LgwrResult;
-   XLogCtlWrite    Write;
-   char           *pages;
-   XLogRecPtr     *xlblocks;   /* 1st byte ptr-s + BLCKSZ */
-   uint32          XLogCacheByte;
-   uint32          XLogCacheBlck;
+   XLogCtlInsert Insert;
+   XLgwrRqst   LgwrRqst;
+   XLgwrResult LgwrResult;
+   XLogCtlWrite Write;
+   char       *pages;
+   XLogRecPtr *xlblocks;       /* 1st byte ptr-s + BLCKSZ */
+   uint32      XLogCacheByte;
+   uint32      XLogCacheBlck;
 #ifdef HAS_TEST_AND_SET
-   slock_t         insert_lck;
-   slock_t         info_lck;
-   slock_t         lgwr_lck;
+   slock_t     insert_lck;
+   slock_t     info_lck;
+   slock_t     lgwr_lck;
 #endif
 } XLogCtlData;
 
-static XLogCtlData        *XLogCtl = NULL;
+static XLogCtlData *XLogCtl = NULL;
 
 typedef enum DBState
 {
@@ -114,69 +114,69 @@ typedef enum DBState
 
 typedef struct ControlFileData
 {
-   uint32          logId;          /* current log file id */
-   uint32          logSeg;         /* current log file segment (1-based) */
-   XLogRecPtr      checkPoint;     /* last check point record ptr */
-   time_t          time;           /* time stamp of last modification */
-   DBState         state;          /* */
+   uint32      logId;          /* current log file id */
+   uint32      logSeg;         /* current log file segment (1-based) */
+   XLogRecPtr  checkPoint;     /* last check point record ptr */
+   time_t      time;           /* time stamp of last modification */
+   DBState     state;          /* */
 
    /*
-    * this data is used to make sure that configuration of this DB
-    * is compatible with the current backend
+    * this data is used to make sure that configuration of this DB is
+    * compatible with the current backend
     */
-   uint32          blcksz;         /* block size for this DB */
-   uint32          relseg_size;    /* blocks per segment of large relation */
-   uint32          catalog_version_no; /* internal version number */
+   uint32      blcksz;         /* block size for this DB */
+   uint32      relseg_size;    /* blocks per segment of large relation */
+   uint32      catalog_version_no;     /* internal version number */
 
    /*
-    * MORE DATA FOLLOWS AT THE END OF THIS STRUCTURE
-    * - locations of data dirs 
+    * MORE DATA FOLLOWS AT THE END OF THIS STRUCTURE - locations of data
+    * dirs
     */
 } ControlFileData;
 
-static ControlFileData    *ControlFile = NULL;
+static ControlFileData *ControlFile = NULL;
 
 typedef struct CheckPoint
 {
-   XLogRecPtr      redo;       /* next RecPtr available when we */
-                               /* began to create CheckPoint */
-                               /* (i.e. REDO start point) */
-   XLogRecPtr      undo;       /* first record of oldest in-progress */
-                               /* transaction when we started */
-                               /* (i.e. UNDO end point) */
-   TransactionId   nextXid;
-   Oid             nextOid;
+   XLogRecPtr  redo;           /* next RecPtr available when we */
+   /* began to create CheckPoint */
+   /* (i.e. REDO start point) */
+   XLogRecPtr  undo;           /* first record of oldest in-progress */
+   /* transaction when we started */
+   /* (i.e. UNDO end point) */
+   TransactionId nextXid;
+   Oid         nextOid;
 } CheckPoint;
 
-/* 
- * We break each log file in 16Mb segments 
+/*
+ * We break each log file in 16Mb segments
  */
 #define XLogSegSize        (16*1024*1024)
-#define    XLogLastSeg     (0xffffffff / XLogSegSize)
-#define    XLogFileSize    (XLogLastSeg * XLogSegSize)
+#define XLogLastSeg        (0xffffffff / XLogSegSize)
+#define XLogFileSize   (XLogLastSeg * XLogSegSize)
 
-#define    XLogFileName(path, log, seg)    \
+#define XLogFileName(path, log, seg)   \
            snprintf(path, MAXPGPATH, "%s%c%08X%08X",   \
                     XLogDir, SEP_CHAR, log, seg)
 
-#define    PrevBufIdx(curridx)     \
+#define PrevBufIdx(curridx)        \
        ((curridx == 0) ? XLogCtl->XLogCacheBlck : (curridx - 1))
 
-#define    NextBufIdx(curridx)     \
+#define NextBufIdx(curridx)        \
        ((curridx == XLogCtl->XLogCacheBlck) ? 0 : (curridx + 1))
 
-#define    XLByteLT(left, right)       \
+#define XLByteLT(left, right)      \
            (right.xlogid > left.xlogid || \
            (right.xlogid == left.xlogid && right.xrecoff > left.xrecoff))
 
-#define    XLByteLE(left, right)       \
+#define XLByteLE(left, right)      \
            (right.xlogid > left.xlogid || \
            (right.xlogid == left.xlogid && right.xrecoff >=  left.xrecoff))
 
-#define    XLByteEQ(left, right)       \
+#define XLByteEQ(left, right)      \
            (right.xlogid == left.xlogid && right.xrecoff ==  left.xrecoff)
 
-#define    InitXLBuffer(curridx)   (\
+#define InitXLBuffer(curridx)  (\
                XLogCtl->xlblocks[curridx].xrecoff = \
                (XLogCtl->xlblocks[Insert->curridx].xrecoff == XLogFileSize) ? \
                BLCKSZ : (XLogCtl->xlblocks[Insert->curridx].xrecoff + BLCKSZ), \
@@ -192,46 +192,46 @@ typedef struct CheckPoint
                Insert->currpage->xlp_info = 0 \
                )
 
-#define    XRecOffIsValid(xrecoff) \
+#define XRecOffIsValid(xrecoff) \
        (xrecoff % BLCKSZ >= SizeOfXLogPHD && \
        (BLCKSZ - xrecoff % BLCKSZ) >= SizeOfXLogRecord)
 
-static void                GetFreeXLBuffer(void);
-static void                XLogWrite(char *buffer);
-static int             XLogFileInit(uint32 log, uint32 seg);
-static int             XLogFileOpen(uint32 log, uint32 seg, bool econt);
-static XLogRecord     *ReadRecord(XLogRecPtr *RecPtr, char *buffer);
-static char               *str_time(time_t tnow);
-
-static XLgwrResult     LgwrResult = {{0, 0}, {0, 0}};
-static XLgwrRqst       LgwrRqst = {{0, 0}, {0, 0}};
-
-static int             logFile = -1;
-static uint32          logId = 0;
-static uint32          logSeg = 0;
-static uint32          logOff = 0;
-
-static XLogRecPtr      ReadRecPtr;
-static XLogRecPtr      EndRecPtr;
-static int             readFile = -1;
-static uint32          readId = 0;
-static uint32          readSeg = 0;
-static uint32          readOff = 0;
-static char                readBuf[BLCKSZ];
-static XLogRecord     *nextRecord = NULL;
+static void GetFreeXLBuffer(void);
+static void XLogWrite(char *buffer);
+static int XLogFileInit(uint32 log, uint32 seg);
+static int XLogFileOpen(uint32 log, uint32 seg, bool econt);
+static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, char *buffer);
+static char *str_time(time_t tnow);
+
+static XLgwrResult LgwrResult = {{0, 0}, {0, 0}};
+static XLgwrRqst LgwrRqst = {{0, 0}, {0, 0}};
+
+static int logFile = -1;
+static uint32 logId = 0;
+static uint32 logSeg = 0;
+static uint32 logOff = 0;
+
+static XLogRecPtr ReadRecPtr;
+static XLogRecPtr EndRecPtr;
+static int readFile = -1;
+static uint32 readId = 0;
+static uint32 readSeg = 0;
+static uint32 readOff = 0;
+static char readBuf[BLCKSZ];
+static XLogRecord *nextRecord = NULL;
 
 XLogRecPtr
 XLogInsert(RmgrId rmid, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
 {
-   XLogCtlInsert      *Insert = &XLogCtl->Insert;
-   XLogRecord         *record;
-   XLogSubRecord      *subrecord;
-   XLogRecPtr          RecPtr;
-   uint32              len = hdrlen + buflen,
-                       freespace,
-                       wlen;
-   uint16              curridx;
-   bool                updrqst = false;
+   XLogCtlInsert *Insert = &XLogCtl->Insert;
+   XLogRecord *record;
+   XLogSubRecord *subrecord;
+   XLogRecPtr  RecPtr;
+   uint32      len = hdrlen + buflen,
+               freespace,
+               wlen;
+   uint16      curridx;
+   bool        updrqst = false;
 
    if (len == 0 || len > MAXLOGRECSZ)
        elog(STOP, "XLogInsert: invalid record len %u", len);
@@ -242,7 +242,7 @@ XLogInsert(RmgrId rmid, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
        bool        do_lgwr = true;
        unsigned    i = 0;
 
-       for ( ; ; )
+       for (;;)
        {
            /* try to read LgwrResult while waiting for insert lock */
            if (!TAS(&(XLogCtl->info_lck)))
@@ -250,14 +250,15 @@ XLogInsert(RmgrId rmid, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
                LgwrRqst = XLogCtl->LgwrRqst;
                LgwrResult = XLogCtl->LgwrResult;
                S_UNLOCK(&(XLogCtl->info_lck));
+
                /*
                 * If cache is half filled then try to acquire lgwr lock
                 * and do LGWR work, but only once.
                 */
-               if (do_lgwr && 
-                   (LgwrRqst.Write.xlogid != LgwrResult.Write.xlogid || 
-                   (LgwrRqst.Write.xrecoff - LgwrResult.Write.xrecoff >=
-                   XLogCtl->XLogCacheByte / 2)))
+               if (do_lgwr &&
+                   (LgwrRqst.Write.xlogid != LgwrResult.Write.xlogid ||
+                    (LgwrRqst.Write.xrecoff - LgwrResult.Write.xrecoff >=
+                     XLogCtl->XLogCacheByte / 2)))
                {
                    if (!TAS(&(XLogCtl->lgwr_lck)))
                    {
@@ -282,13 +283,13 @@ XLogInsert(RmgrId rmid, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
        }
    }
 
-   freespace = ((char*) Insert->currpage) + BLCKSZ - Insert->currpos;
+   freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
    if (freespace < SizeOfXLogRecord)
    {
        curridx = NextBufIdx(Insert->curridx);
        if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
            InitXLBuffer(curridx);
-       else 
+       else
            GetFreeXLBuffer();
        freespace = BLCKSZ - SizeOfXLogPHD;
    }
@@ -296,7 +297,7 @@ XLogInsert(RmgrId rmid, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
        curridx = Insert->curridx;
 
    freespace -= SizeOfXLogRecord;
-   record = (XLogRecord*) Insert->currpos;
+   record = (XLogRecord *) Insert->currpos;
    record->xl_prev = Insert->PrevRecord;
    if (rmid != RM_XLOG_ID)
        record->xl_xact_prev = MyLastRecPtr;
@@ -310,9 +311,9 @@ XLogInsert(RmgrId rmid, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
    record->xl_info = (len > freespace) ? XLR_TO_BE_CONTINUED : 0;
    record->xl_rmid = rmid;
    RecPtr.xlogid = XLogCtl->xlblocks[curridx].xlogid;
-   RecPtr.xrecoff = 
-       XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ + 
-       Insert->currpos - ((char*) Insert->currpage);
+   RecPtr.xrecoff =
+       XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ +
+       Insert->currpos - ((char *) Insert->currpage);
    if (MyLastRecPtr.xrecoff == 0 && rmid != RM_XLOG_ID)
    {
        SpinAcquire(SInvalLock);
@@ -339,8 +340,8 @@ XLogInsert(RmgrId rmid, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
            buf += wlen;
            Insert->currpos += wlen;
        }
-       Insert->currpos = ((char*)Insert->currpage) + 
-                   DOUBLEALIGN(Insert->currpos - ((char*)Insert->currpage));
+       Insert->currpos = ((char *) Insert->currpage) +
+           DOUBLEALIGN(Insert->currpos - ((char *) Insert->currpage));
        len = hdrlen + buflen;
    }
 
@@ -360,7 +361,7 @@ nbuf:
        }
        freespace = BLCKSZ - SizeOfXLogPHD - SizeOfXLogSubRecord;
        Insert->currpage->xlp_info |= XLP_FIRST_IS_SUBRECORD;
-       subrecord = (XLogSubRecord*) Insert->currpos;
+       subrecord = (XLogSubRecord *) Insert->currpos;
        Insert->currpos += SizeOfXLogSubRecord;
        if (hdrlen > freespace)
        {
@@ -398,17 +399,19 @@ nbuf:
        }
        subrecord->xl_info = 0;
        RecPtr.xlogid = XLogCtl->xlblocks[curridx].xlogid;
-       RecPtr.xrecoff = XLogCtl->xlblocks[curridx].xrecoff - 
-               BLCKSZ + SizeOfXLogPHD + subrecord->xl_len;
-       Insert->currpos = ((char*)Insert->currpage) + 
-                   DOUBLEALIGN(Insert->currpos - ((char*)Insert->currpage));
+       RecPtr.xrecoff = XLogCtl->xlblocks[curridx].xrecoff -
+           BLCKSZ + SizeOfXLogPHD + subrecord->xl_len;
+       Insert->currpos = ((char *) Insert->currpage) +
+           DOUBLEALIGN(Insert->currpos - ((char *) Insert->currpage));
    }
-   freespace = ((char*) Insert->currpage) + BLCKSZ - Insert->currpos;
+   freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
+
    /*
     * All done! Update global LgwrRqst if some block was filled up.
     */
    if (freespace < SizeOfXLogRecord)
-       updrqst = true;     /* curridx is filled and available for writing out */
+       updrqst = true;         /* curridx is filled and available for
+                                * writing out */
    else
        curridx = PrevBufIdx(curridx);
    LgwrRqst.Write = XLogCtl->xlblocks[curridx];
@@ -419,7 +422,7 @@ nbuf:
    {
        unsigned    i = 0;
 
-       for ( ; ; )
+       for (;;)
        {
            if (!TAS(&(XLogCtl->info_lck)))
            {
@@ -433,21 +436,21 @@ nbuf:
    }
 
    return (RecPtr);
-}  
+}
 
 void
 XLogFlush(XLogRecPtr record)
 {
-   XLogRecPtr      WriteRqst;
-   char            buffer[BLCKSZ];
-   char           *usebuf = NULL;
-   unsigned        i = 0;
-   bool            force_lgwr = false;
+   XLogRecPtr  WriteRqst;
+   char        buffer[BLCKSZ];
+   char       *usebuf = NULL;
+   unsigned    i = 0;
+   bool        force_lgwr = false;
 
    if (XLByteLE(record, LgwrResult.Flush))
        return;
    WriteRqst = LgwrRqst.Write;
-   for ( ; ; )
+   for (;;)
    {
        /* try to read LgwrResult */
        if (!TAS(&(XLogCtl->info_lck)))
@@ -470,9 +473,9 @@ XLogFlush(XLogRecPtr record)
        /* if something was added to log cache then try to flush this too */
        if (!TAS(&(XLogCtl->insert_lck)))
        {
-           XLogCtlInsert      *Insert = &XLogCtl->Insert;
-           uint32              freespace = 
-                   ((char*) Insert->currpage) + BLCKSZ - Insert->currpos;
+           XLogCtlInsert *Insert = &XLogCtl->Insert;
+           uint32      freespace =
+           ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
 
            if (freespace < SizeOfXLogRecord)   /* buffer is full */
            {
@@ -485,14 +488,14 @@ XLogFlush(XLogRecPtr record)
                memcpy(usebuf, Insert->currpage, BLCKSZ - freespace);
                memset(usebuf + BLCKSZ - freespace, 0, freespace);
                WriteRqst = XLogCtl->xlblocks[Insert->curridx];
-               WriteRqst.xrecoff = WriteRqst.xrecoff - BLCKSZ + 
-                       Insert->currpos - ((char*) Insert->currpage);
+               WriteRqst.xrecoff = WriteRqst.xrecoff - BLCKSZ +
+                   Insert->currpos - ((char *) Insert->currpage);
            }
            S_UNLOCK(&(XLogCtl->insert_lck));
            force_lgwr = true;
        }
-       if (force_lgwr || WriteRqst.xlogid > record.xlogid || 
-           (WriteRqst.xlogid == record.xlogid && 
+       if (force_lgwr || WriteRqst.xlogid > record.xlogid ||
+           (WriteRqst.xlogid == record.xlogid &&
             WriteRqst.xrecoff >= record.xrecoff + BLCKSZ))
        {
            if (!TAS(&(XLogCtl->lgwr_lck)))
@@ -518,12 +521,12 @@ XLogFlush(XLogRecPtr record)
        s_lock_sleep(i++);
    }
 
-   if (logFile >= 0 && (LgwrResult.Write.xlogid != logId || 
-       (LgwrResult.Write.xrecoff - 1) / XLogSegSize != logSeg))
+   if (logFile >= 0 && (LgwrResult.Write.xlogid != logId ||
+                (LgwrResult.Write.xrecoff - 1) / XLogSegSize != logSeg))
    {
        if (close(logFile) != 0)
-           elog(STOP, "Close(logfile %u seg %u) failed: %d", 
-                       logId, logSeg, errno);
+           elog(STOP, "Close(logfile %u seg %u) failed: %d",
+                logId, logSeg, errno);
        logFile = -1;
    }
 
@@ -536,11 +539,11 @@ XLogFlush(XLogRecPtr record)
    }
 
    if (fsync(logFile) != 0)
-       elog(STOP, "Fsync(logfile %u seg %u) failed: %d", 
-                   logId, logSeg, errno);
+       elog(STOP, "Fsync(logfile %u seg %u) failed: %d",
+            logId, logSeg, errno);
    LgwrResult.Flush = LgwrResult.Write;
 
-   for (i = 0; ; )
+   for (i = 0;;)
    {
        if (!TAS(&(XLogCtl->info_lck)))
        {
@@ -562,12 +565,12 @@ XLogFlush(XLogRecPtr record)
 static void
 GetFreeXLBuffer()
 {
-   XLogCtlInsert      *Insert = &XLogCtl->Insert;
-   XLogCtlWrite       *Write = &XLogCtl->Write;
-   uint16              curridx = NextBufIdx(Insert->curridx);
+   XLogCtlInsert *Insert = &XLogCtl->Insert;
+   XLogCtlWrite *Write = &XLogCtl->Write;
+   uint16      curridx = NextBufIdx(Insert->curridx);
 
    LgwrRqst.Write = XLogCtl->xlblocks[Insert->curridx];
-   for ( ; ; )
+   for (;;)
    {
        if (!TAS(&(XLogCtl->info_lck)))
        {
@@ -581,6 +584,7 @@ GetFreeXLBuffer()
                return;
            }
        }
+
        /*
         * LgwrResult lock is busy or un-updated. Try to acquire lgwr lock
         * and write full blocks.
@@ -595,9 +599,10 @@ GetFreeXLBuffer()
                InitXLBuffer(curridx);
                return;
            }
-           /* 
-            * Have to write buffers while holding insert lock -
-            * not good...
+
+           /*
+            * Have to write buffers while holding insert lock - not
+            * good...
             */
            XLogWrite(NULL);
            S_UNLOCK(&(XLogCtl->lgwr_lck));
@@ -613,22 +618,22 @@ GetFreeXLBuffer()
 static void
 XLogWrite(char *buffer)
 {
-   XLogCtlWrite   *Write = &XLogCtl->Write;
-   char           *from;
-   uint32          wcnt = 0;
-   int             i = 0;
+   XLogCtlWrite *Write = &XLogCtl->Write;
+   char       *from;
+   uint32      wcnt = 0;
+   int         i = 0;
 
-   for ( ; XLByteLT(LgwrResult.Write,  LgwrRqst.Write); )
+   for (; XLByteLT(LgwrResult.Write, LgwrRqst.Write);)
    {
        LgwrResult.Write = XLogCtl->xlblocks[Write->curridx];
-       if (LgwrResult.Write.xlogid != logId || 
+       if (LgwrResult.Write.xlogid != logId ||
            (LgwrResult.Write.xrecoff - 1) / XLogSegSize != logSeg)
        {
            if (wcnt > 0)
            {
                if (fsync(logFile) != 0)
-                   elog(STOP, "Fsync(logfile %u seg %u) failed: %d", 
-                               logId, logSeg, errno);
+                   elog(STOP, "Fsync(logfile %u seg %u) failed: %d",
+                        logId, logSeg, errno);
                if (LgwrResult.Write.xlogid != logId)
                    LgwrResult.Flush.xrecoff = XLogFileSize;
                else
@@ -648,8 +653,8 @@ XLogWrite(char *buffer)
            if (logFile >= 0)
            {
                if (close(logFile) != 0)
-                   elog(STOP, "Close(logfile %u seg %u) failed: %d", 
-                               logId, logSeg, errno);
+                   elog(STOP, "Close(logfile %u seg %u) failed: %d",
+                        logId, logSeg, errno);
                logFile = -1;
            }
            logId = LgwrResult.Write.xlogid;
@@ -675,9 +680,9 @@ XLogWrite(char *buffer)
        if (logOff != (LgwrResult.Write.xrecoff - BLCKSZ) % XLogSegSize)
        {
            logOff = (LgwrResult.Write.xrecoff - BLCKSZ) % XLogSegSize;
-           if (lseek(logFile, (off_t)logOff, SEEK_SET) < 0)
-               elog(STOP, "Lseek(logfile %u seg %u off %u) failed: %d", 
-                           logId, logSeg, logOff, errno);
+           if (lseek(logFile, (off_t) logOff, SEEK_SET) < 0)
+               elog(STOP, "Lseek(logfile %u seg %u off %u) failed: %d",
+                    logId, logSeg, logOff, errno);
        }
 
        if (buffer != NULL && XLByteLT(LgwrRqst.Write, LgwrResult.Write))
@@ -686,8 +691,8 @@ XLogWrite(char *buffer)
            from = XLogCtl->pages + Write->curridx * BLCKSZ;
 
        if (write(logFile, from, BLCKSZ) != BLCKSZ)
-           elog(STOP, "Write(logfile %u seg %u off %u) failed: %d", 
-                       logId, logSeg, logOff, errno);
+           elog(STOP, "Write(logfile %u seg %u off %u) failed: %d",
+                logId, logSeg, logOff, errno);
 
        wcnt++;
        logOff += BLCKSZ;
@@ -700,16 +705,16 @@ XLogWrite(char *buffer)
    if (wcnt == 0)
        elog(STOP, "XLogWrite: nothing written");
 
-   if (XLByteLT(LgwrResult.Flush, LgwrRqst.Flush) && 
+   if (XLByteLT(LgwrResult.Flush, LgwrRqst.Flush) &&
        XLByteLE(LgwrRqst.Flush, LgwrResult.Write))
    {
        if (fsync(logFile) != 0)
-           elog(STOP, "Fsync(logfile %u seg %u) failed: %d", 
-                       logId, logSeg, errno);
+           elog(STOP, "Fsync(logfile %u seg %u) failed: %d",
+                logId, logSeg, errno);
        LgwrResult.Flush = LgwrResult.Write;
    }
 
-   for ( ; ; )
+   for (;;)
    {
        if (!TAS(&(XLogCtl->info_lck)))
        {
@@ -727,54 +732,54 @@ XLogWrite(char *buffer)
 static int
 XLogFileInit(uint32 log, uint32 seg)
 {
-   char    path[MAXPGPATH];
-   int     fd;
+   char        path[MAXPGPATH];
+   int         fd;
 
    XLogFileName(path, log, seg);
    unlink(path);
 
 tryAgain:
 #ifndef __CYGWIN__
-   fd = open(path, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
+   fd = open(path, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
 #else
-   fd = open(path, O_RDWR|O_CREAT|O_EXCL|O_BINARY, S_IRUSR|S_IWUSR);
+   fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_BINARY, S_IRUSR | S_IWUSR);
 #endif
    if (fd < 0 && (errno == EMFILE || errno == ENFILE))
    {
        fd = errno;
        if (!ReleaseDataFile())
-           elog(STOP, "Create(logfile %u seg %u) failed: %d (and no one data file can be closed)", 
-                       logId, logSeg, fd);
+           elog(STOP, "Create(logfile %u seg %u) failed: %d (and no one data file can be closed)",
+                logId, logSeg, fd);
        goto tryAgain;
    }
    if (fd < 0)
-       elog(STOP, "Init(logfile %u seg %u) failed: %d", 
-                   logId, logSeg, errno);
+       elog(STOP, "Init(logfile %u seg %u) failed: %d",
+            logId, logSeg, errno);
 
    if (lseek(fd, XLogSegSize - 1, SEEK_SET) != (off_t) (XLogSegSize - 1))
-       elog(STOP, "Lseek(logfile %u seg %u) failed: %d", 
-                   logId, logSeg, errno);
+       elog(STOP, "Lseek(logfile %u seg %u) failed: %d",
+            logId, logSeg, errno);
 
    if (write(fd, "", 1) != 1)
-       elog(STOP, "Init(logfile %u seg %u) failed: %d", 
-                   logId, logSeg, errno);
+       elog(STOP, "Init(logfile %u seg %u) failed: %d",
+            logId, logSeg, errno);
 
    if (fsync(fd) != 0)
-       elog(STOP, "Fsync(logfile %u seg %u) failed: %d", 
-                   logId, logSeg, errno);
+       elog(STOP, "Fsync(logfile %u seg %u) failed: %d",
+            logId, logSeg, errno);
 
    if (lseek(fd, 0, SEEK_SET) < 0)
-           elog(STOP, "Lseek(logfile %u seg %u off %u) failed: %d", 
-                       log, seg, 0, errno);
+       elog(STOP, "Lseek(logfile %u seg %u off %u) failed: %d",
+            log, seg, 0, errno);
 
-   return(fd);
+   return (fd);
 }
 
 static int
 XLogFileOpen(uint32 log, uint32 seg, bool econt)
 {
-   char    path[MAXPGPATH];
-   int     fd;
+   char        path[MAXPGPATH];
+   int         fd;
 
    XLogFileName(path, log, seg);
 
@@ -788,8 +793,8 @@ tryAgain:
    {
        fd = errno;
        if (!ReleaseDataFile())
-           elog(STOP, "Open(logfile %u seg %u) failed: %d (and no one data file can be closed)", 
-                       logId, logSeg, fd);
+           elog(STOP, "Open(logfile %u seg %u) failed: %d (and no one data file can be closed)",
+                logId, logSeg, fd);
        goto tryAgain;
    }
    if (fd < 0)
@@ -797,24 +802,24 @@ tryAgain:
        if (econt && errno == ENOENT)
        {
            elog(LOG, "Open(logfile %u seg %u) failed: file doesn't exist",
-                       logId, logSeg);
+                logId, logSeg);
            return (fd);
        }
-       elog(STOP, "Open(logfile %u seg %u) failed: %d", 
-                   logId, logSeg, errno);
+       elog(STOP, "Open(logfile %u seg %u) failed: %d",
+            logId, logSeg, errno);
    }
 
-   return(fd);
+   return (fd);
 }
 
-static XLogRecord*
+static XLogRecord *
 ReadRecord(XLogRecPtr *RecPtr, char *buffer)
 {
-   XLogRecord     *record;
-   XLogRecPtr      tmpRecPtr = EndRecPtr;
-   bool            nextmode = (RecPtr == NULL);
-   int             emode = (nextmode) ? LOG : STOP;
-   bool            noBlck = false;
+   XLogRecord *record;
+   XLogRecPtr  tmpRecPtr = EndRecPtr;
+   bool        nextmode = (RecPtr == NULL);
+   int         emode = (nextmode) ? LOG : STOP;
+   bool        noBlck = false;
 
    if (nextmode)
    {
@@ -835,10 +840,10 @@ ReadRecord(XLogRecPtr *RecPtr, char *buffer)
    }
    else if (!XRecOffIsValid(RecPtr->xrecoff))
        elog(STOP, "ReadRecord: invalid record offset in (%u, %u)",
-                   RecPtr->xlogid, RecPtr->xrecoff);
+            RecPtr->xlogid, RecPtr->xrecoff);
 
-   if (readFile >= 0 && (RecPtr->xlogid != readId || 
-       RecPtr->xrecoff / XLogSegSize != readSeg))
+   if (readFile >= 0 && (RecPtr->xlogid != readId ||
+                         RecPtr->xrecoff / XLogSegSize != readSeg))
    {
        close(readFile);
        readFile = -1;
@@ -856,59 +861,59 @@ ReadRecord(XLogRecPtr *RecPtr, char *buffer)
    if (noBlck || readOff != (RecPtr->xrecoff % XLogSegSize) / BLCKSZ)
    {
        readOff = (RecPtr->xrecoff % XLogSegSize) / BLCKSZ;
-       if (lseek(readFile, (off_t)(readOff * BLCKSZ), SEEK_SET) < 0)
-           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d", 
-                       readId, readSeg, readOff, errno);
+       if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
+           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d",
+                readId, readSeg, readOff, errno);
        if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
-           elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %d", 
-                       readId, readSeg, readOff, errno);
-       if (((XLogPageHeader)readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
+           elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %d",
+                readId, readSeg, readOff, errno);
+       if (((XLogPageHeader) readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
        {
            elog(emode, "ReadRecord: invalid magic number %u in logfile %u seg %u off %u",
-               ((XLogPageHeader)readBuf)->xlp_magic,
-               readId, readSeg, readOff);
+                ((XLogPageHeader) readBuf)->xlp_magic,
+                readId, readSeg, readOff);
            goto next_record_is_invalid;
        }
    }
-   if ((((XLogPageHeader)readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD) && 
+   if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD) &&
        RecPtr->xrecoff % BLCKSZ == SizeOfXLogPHD)
    {
        elog(emode, "ReadRecord: subrecord is requested by (%u, %u)",
-                   RecPtr->xlogid, RecPtr->xrecoff);
+            RecPtr->xlogid, RecPtr->xrecoff);
        goto next_record_is_invalid;
    }
-   record = (XLogRecord*)((char*) readBuf + RecPtr->xrecoff % BLCKSZ);
+   record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % BLCKSZ);
 
 got_record:;
-   if (record->xl_len == 0 || record->xl_len > 
+   if (record->xl_len == 0 || record->xl_len >
        (BLCKSZ - RecPtr->xrecoff % BLCKSZ - SizeOfXLogRecord))
    {
        elog(emode, "ReadRecord: invalid record len %u in (%u, %u)",
-                   record->xl_len, RecPtr->xlogid, RecPtr->xrecoff);
+            record->xl_len, RecPtr->xlogid, RecPtr->xrecoff);
        goto next_record_is_invalid;
    }
    if (record->xl_rmid > RM_MAX_ID)
    {
        elog(emode, "ReadRecord: invalid resource managed id %u in (%u, %u)",
-                   record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff);
+            record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff);
        goto next_record_is_invalid;
    }
    nextRecord = NULL;
    if (record->xl_info & XLR_TO_BE_CONTINUED)
    {
-       XLogSubRecord      *subrecord;
-       uint32              len = record->xl_len;
+       XLogSubRecord *subrecord;
+       uint32      len = record->xl_len;
 
        if (record->xl_len + RecPtr->xrecoff % BLCKSZ + SizeOfXLogRecord != BLCKSZ)
        {
            elog(emode, "ReadRecord: invalid fragmented record len %u in (%u, %u)",
-                       record->xl_len, RecPtr->xlogid, RecPtr->xrecoff);
+                record->xl_len, RecPtr->xlogid, RecPtr->xrecoff);
            goto next_record_is_invalid;
        }
        memcpy(buffer, record, record->xl_len + SizeOfXLogRecord);
-       record = (XLogRecord*) buffer;
+       record = (XLogRecord *) buffer;
        buffer += record->xl_len + SizeOfXLogRecord;
-       for ( ; ; )
+       for (;;)
        {
            readOff++;
            if (readOff == XLogSegSize / BLCKSZ)
@@ -926,114 +931,113 @@ got_record:;
                    goto next_record_is_invalid;
            }
            if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
-               elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %d", 
-                           readId, readSeg, readOff, errno);
-           if (((XLogPageHeader)readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
+               elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %d",
+                    readId, readSeg, readOff, errno);
+           if (((XLogPageHeader) readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
            {
                elog(emode, "ReadRecord: invalid magic number %u in logfile %u seg %u off %u",
-                   ((XLogPageHeader)readBuf)->xlp_magic,
-                   readId, readSeg, readOff);
+                    ((XLogPageHeader) readBuf)->xlp_magic,
+                    readId, readSeg, readOff);
                goto next_record_is_invalid;
            }
-           if (!(((XLogPageHeader)readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD))
+           if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD))
            {
                elog(emode, "ReadRecord: there is no subrecord flag in logfile %u seg %u off %u",
-                           readId, readSeg, readOff);
+                    readId, readSeg, readOff);
                goto next_record_is_invalid;
            }
-           subrecord = (XLogSubRecord*)((char*) readBuf + SizeOfXLogPHD);
-           if (subrecord->xl_len == 0 || subrecord->xl_len > 
+           subrecord = (XLogSubRecord *) ((char *) readBuf + SizeOfXLogPHD);
+           if (subrecord->xl_len == 0 || subrecord->xl_len >
                (BLCKSZ - SizeOfXLogPHD - SizeOfXLogSubRecord))
            {
                elog(emode, "ReadRecord: invalid subrecord len %u in logfile %u seg %u off %u",
-                           subrecord->xl_len, readId, readSeg, readOff);
+                    subrecord->xl_len, readId, readSeg, readOff);
                goto next_record_is_invalid;
            }
            len += subrecord->xl_len;
            if (len > MAXLOGRECSZ)
            {
                elog(emode, "ReadRecord: too long record len %u in (%u, %u)",
-                           len, RecPtr->xlogid, RecPtr->xrecoff);
+                    len, RecPtr->xlogid, RecPtr->xrecoff);
                goto next_record_is_invalid;
            }
-           memcpy(buffer, (char*)subrecord + SizeOfXLogSubRecord, subrecord->xl_len);
+           memcpy(buffer, (char *) subrecord + SizeOfXLogSubRecord, subrecord->xl_len);
            buffer += subrecord->xl_len;
            if (subrecord->xl_info & XLR_TO_BE_CONTINUED)
            {
-               if (subrecord->xl_len + 
+               if (subrecord->xl_len +
                    SizeOfXLogPHD + SizeOfXLogSubRecord != BLCKSZ)
                {
                    elog(emode, "ReadRecord: invalid fragmented subrecord len %u in logfile %u seg %u off %u",
-                               subrecord->xl_len, readId, readSeg, readOff);
+                        subrecord->xl_len, readId, readSeg, readOff);
                    goto next_record_is_invalid;
                }
                continue;
            }
            break;
        }
-       if (BLCKSZ - SizeOfXLogRecord >= 
+       if (BLCKSZ - SizeOfXLogRecord >=
            subrecord->xl_len + SizeOfXLogPHD + SizeOfXLogSubRecord)
        {
-           nextRecord = (XLogRecord*)
-               ((char*)subrecord + subrecord->xl_len + SizeOfXLogSubRecord);
+           nextRecord = (XLogRecord *)
+               ((char *) subrecord + subrecord->xl_len + SizeOfXLogSubRecord);
        }
        EndRecPtr.xlogid = readId;
-       EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff * BLCKSZ + 
+       EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff * BLCKSZ +
            SizeOfXLogPHD + SizeOfXLogSubRecord + subrecord->xl_len;
        ReadRecPtr = *RecPtr;
-       return(record);
+       return (record);
    }
-   if (BLCKSZ - SizeOfXLogRecord >= 
+   if (BLCKSZ - SizeOfXLogRecord >=
        record->xl_len + RecPtr->xrecoff % BLCKSZ + SizeOfXLogRecord)
-   {
-       nextRecord = (XLogRecord*)((char*)record + record->xl_len + SizeOfXLogRecord);
-   }
+       nextRecord = (XLogRecord *) ((char *) record + record->xl_len + SizeOfXLogRecord);
    EndRecPtr.xlogid = RecPtr->xlogid;
    EndRecPtr.xrecoff = RecPtr->xrecoff + record->xl_len + SizeOfXLogRecord;
    ReadRecPtr = *RecPtr;
 
-   return(record);
+   return (record);
 
 next_record_is_invalid:;
    close(readFile);
    readFile = -1;
    nextRecord = NULL;
    memset(buffer, 0, SizeOfXLogRecord);
-   record = (XLogRecord*) buffer;
+   record = (XLogRecord *) buffer;
+
    /*
     * If we assumed that next record began on the same page where
     * previous one ended - zero end of page.
     */
    if (XLByteEQ(tmpRecPtr, EndRecPtr))
    {
-       Assert (EndRecPtr.xrecoff % BLCKSZ > (SizeOfXLogPHD + SizeOfXLogSubRecord) && 
-               BLCKSZ - EndRecPtr.xrecoff % BLCKSZ >= SizeOfXLogRecord);
+       Assert(EndRecPtr.xrecoff % BLCKSZ > (SizeOfXLogPHD + SizeOfXLogSubRecord) &&
+              BLCKSZ - EndRecPtr.xrecoff % BLCKSZ >= SizeOfXLogRecord);
        readId = EndRecPtr.xlogid;
        readSeg = EndRecPtr.xrecoff / XLogSegSize;
        readOff = (EndRecPtr.xrecoff % XLogSegSize) / BLCKSZ;
        elog(LOG, "Formatting logfile %u seg %u block %u at offset %u",
-                   readId, readSeg, readOff, EndRecPtr.xrecoff % BLCKSZ);
+            readId, readSeg, readOff, EndRecPtr.xrecoff % BLCKSZ);
        readFile = XLogFileOpen(readId, readSeg, false);
-       if (lseek(readFile, (off_t)(readOff * BLCKSZ), SEEK_SET) < 0)
-           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d", 
-                       readId, readSeg, readOff, errno);
+       if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
+           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d",
+                readId, readSeg, readOff, errno);
        if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
-           elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %d", 
-                       readId, readSeg, readOff, errno);
-       memset(readBuf + EndRecPtr.xrecoff % BLCKSZ, 0, 
-               BLCKSZ - EndRecPtr.xrecoff % BLCKSZ);
-       if (lseek(readFile, (off_t)(readOff * BLCKSZ), SEEK_SET) < 0)
-           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d", 
-                       readId, readSeg, readOff, errno);
+           elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %d",
+                readId, readSeg, readOff, errno);
+       memset(readBuf + EndRecPtr.xrecoff % BLCKSZ, 0,
+              BLCKSZ - EndRecPtr.xrecoff % BLCKSZ);
+       if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
+           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d",
+                readId, readSeg, readOff, errno);
        if (write(readFile, readBuf, BLCKSZ) != BLCKSZ)
-           elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %d", 
-                       readId, readSeg, readOff, errno);
+           elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %d",
+                readId, readSeg, readOff, errno);
        readOff++;
    }
    else
    {
-       Assert (EndRecPtr.xrecoff % BLCKSZ == 0 || 
-               BLCKSZ - EndRecPtr.xrecoff % BLCKSZ < SizeOfXLogRecord);
+       Assert(EndRecPtr.xrecoff % BLCKSZ == 0 ||
+              BLCKSZ - EndRecPtr.xrecoff % BLCKSZ < SizeOfXLogRecord);
        readId = tmpRecPtr.xlogid;
        readSeg = tmpRecPtr.xrecoff / XLogSegSize;
        readOff = (tmpRecPtr.xrecoff % XLogSegSize) / BLCKSZ;
@@ -1043,26 +1047,26 @@ next_record_is_invalid:;
    {
        if (!XLByteEQ(tmpRecPtr, EndRecPtr))
            elog(LOG, "Formatting logfile %u seg %u block %u at offset 0",
-                       readId, readSeg, readOff);
+                readId, readSeg, readOff);
        readOff *= BLCKSZ;
        memset(readBuf, 0, BLCKSZ);
        readFile = XLogFileOpen(readId, readSeg, false);
-       if (lseek(readFile, (off_t)readOff, SEEK_SET) < 0)
-           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d", 
-                       readId, readSeg, readOff, errno);
+       if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
+           elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %d",
+                readId, readSeg, readOff, errno);
        while (readOff < XLogSegSize)
        {
            if (write(readFile, readBuf, BLCKSZ) != BLCKSZ)
-               elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %d", 
-                           readId, readSeg, readOff, errno);
+               elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %d",
+                    readId, readSeg, readOff, errno);
            readOff += BLCKSZ;
        }
    }
    if (readFile >= 0)
    {
        if (fsync(readFile) < 0)
-           elog(STOP, "ReadRecord: fsync(logfile %u seg %u) failed: %d", 
-                           readId, readSeg, errno);
+           elog(STOP, "ReadRecord: fsync(logfile %u seg %u) failed: %d",
+                readId, readSeg, errno);
        close(readFile);
        readFile = -1;
    }
@@ -1084,19 +1088,19 @@ next_record_is_invalid:;
        readId++;
    }
    {
-       char    path[MAXPGPATH];
+       char        path[MAXPGPATH];
 
        XLogFileName(path, readId, readSeg);
        unlink(path);
    }
 
-   return(record);
+   return (record);
 }
 
 void
 UpdateControlFile()
 {
-   int     fd;
+   int         fd;
 
 tryAgain:
 #ifndef __CYGWIN__
@@ -1108,8 +1112,8 @@ tryAgain:
    {
        fd = errno;
        if (!ReleaseDataFile())
-           elog(STOP, "Open(cntlfile) failed: %d (and no one data file can be closed)", 
-                       fd);
+           elog(STOP, "Open(cntlfile) failed: %d (and no one data file can be closed)",
+                fd);
        goto tryAgain;
    }
    if (fd < 0)
@@ -1132,23 +1136,23 @@ XLOGShmemSize()
    if (XLOGbuffers < MinXLOGbuffers)
        XLOGbuffers = MinXLOGbuffers;
 
-   return(sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers + 
+   return (sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers +
            sizeof(XLogRecPtr) * XLOGbuffers + BLCKSZ);
 }
 
 void
 XLOGShmemInit(void)
 {
-   bool                found;
+   bool        found;
 
    if (XLOGbuffers < MinXLOGbuffers)
        XLOGbuffers = MinXLOGbuffers;
 
-   ControlFile = (ControlFileData*) 
+   ControlFile = (ControlFileData *)
        ShmemInitStruct("Control File", BLCKSZ, &found);
    Assert(!found);
-   XLogCtl = (XLogCtlData*)
-       ShmemInitStruct("XLOG Ctl", sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers + 
+   XLogCtl = (XLogCtlData *)
+       ShmemInitStruct("XLOG Ctl", sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers +
                        sizeof(XLogRecPtr) * XLOGbuffers, &found);
    Assert(!found);
 }
@@ -1159,43 +1163,45 @@ XLOGShmemInit(void)
 void
 BootStrapXLOG()
 {
-   int             fd;
-   char            buffer[BLCKSZ];
-   CheckPoint      checkPoint;
+   int         fd;
+   char        buffer[BLCKSZ];
+   CheckPoint  checkPoint;
 
 #ifdef NOT_USED
-   XLogPageHeader  page = (XLogPageHeader)buffer;
-   XLogRecord     *record;
+   XLogPageHeader page = (XLogPageHeader) buffer;
+   XLogRecord *record;
+
 #endif
 
 #ifndef __CYGWIN__
-   fd = open(ControlFilePath, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
+   fd = open(ControlFilePath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
 #else
-   fd = open(ControlFilePath, O_RDWR|O_CREAT|O_EXCL|O_BINARY, S_IRUSR|S_IWUSR);
+   fd = open(ControlFilePath, O_RDWR | O_CREAT | O_EXCL | O_BINARY, S_IRUSR | S_IWUSR);
 #endif
    if (fd < 0)
-       elog(STOP, "BootStrapXLOG failed to create control file (%s): %d", 
-                   ControlFilePath, errno);
+       elog(STOP, "BootStrapXLOG failed to create control file (%s): %d",
+            ControlFilePath, errno);
 
    checkPoint.redo.xlogid = 0;
    checkPoint.redo.xrecoff = SizeOfXLogPHD;
    checkPoint.undo = checkPoint.redo;
    checkPoint.nextXid = FirstTransactionId;
-   checkPoint.nextOid =  BootstrapObjectIdData;
+   checkPoint.nextOid = BootstrapObjectIdData;
 
 #ifdef NOT_USED
 
    memset(buffer, 0, BLCKSZ);
    page->xlp_magic = XLOG_PAGE_MAGIC;
    page->xlp_info = 0;
-   record = (XLogRecord*) ((char*)page + SizeOfXLogPHD);
-   record->xl_prev.xlogid = 0; record->xl_prev.xrecoff = 0;
+   record = (XLogRecord *) ((char *) page + SizeOfXLogPHD);
+   record->xl_prev.xlogid = 0;
+   record->xl_prev.xrecoff = 0;
    record->xl_xact_prev = record->xl_prev;
    record->xl_xid = InvalidTransactionId;
    record->xl_len = sizeof(checkPoint);
    record->xl_info = 0;
    record->xl_rmid = RM_XLOG_ID;
-   memcpy((char*)record + SizeOfXLogRecord, &checkPoint, sizeof(checkPoint));
+   memcpy((char *) record + SizeOfXLogRecord, &checkPoint, sizeof(checkPoint));
 
    logFile = XLogFileInit(0, 0);
 
@@ -1211,7 +1217,7 @@ BootStrapXLOG()
 #endif
 
    memset(buffer, 0, BLCKSZ);
-   ControlFile = (ControlFileData*) buffer;
+   ControlFile = (ControlFileData *) buffer;
    ControlFile->logId = 0;
    ControlFile->logSeg = 1;
    ControlFile->checkPoint = checkPoint.redo;
@@ -1230,16 +1236,16 @@ BootStrapXLOG()
    close(fd);
 }
 
-static char*
+static char *
 str_time(time_t tnow)
 {
-   char   *result = ctime(&tnow);
-   char   *p = strchr(result, '\n');
+   char       *result = ctime(&tnow);
+   char       *p = strchr(result, '\n');
 
    if (p != NULL)
        *p = 0;
 
-   return(result);
+   return (result);
 }
 
 /*
@@ -1249,21 +1255,22 @@ void
 StartupXLOG()
 {
 #ifdef NOT_USED
-   XLogCtlInsert      *Insert;
-   CheckPoint          checkPoint;
-   XLogRecPtr          RecPtr,
-                       LastRec;
-   XLogRecord         *record;
-   char                buffer[MAXLOGRECSZ+SizeOfXLogRecord];
-   int                 recovery = 0;
-   bool                sie_saved = false;
+   XLogCtlInsert *Insert;
+   CheckPoint  checkPoint;
+   XLogRecPtr  RecPtr,
+               LastRec;
+   XLogRecord *record;
+   char        buffer[MAXLOGRECSZ + SizeOfXLogRecord];
+   int         recovery = 0;
+   bool        sie_saved = false;
+
 #endif
-   int                 fd;
+   int         fd;
 
    elog(LOG, "Data Base System is starting up at %s", str_time(time(NULL)));
 
-   XLogCtl->xlblocks = (XLogRecPtr*) (((char *)XLogCtl) + sizeof(XLogCtlData));
-   XLogCtl->pages = ((char *)XLogCtl->xlblocks + sizeof(XLogRecPtr) * XLOGbuffers);
+   XLogCtl->xlblocks = (XLogRecPtr *) (((char *) XLogCtl) + sizeof(XLogCtlData));
+   XLogCtl->pages = ((char *) XLogCtl->xlblocks + sizeof(XLogRecPtr) * XLOGbuffers);
    XLogCtl->XLogCacheByte = BLCKSZ * XLOGbuffers;
    XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
    memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
@@ -1291,8 +1298,8 @@ tryAgain:
    {
        fd = errno;
        if (!ReleaseDataFile())
-           elog(STOP, "Open(\"%s\") failed: %d (and no one data file can be closed)", 
-                       ControlFilePath, fd);
+           elog(STOP, "Open(\"%s\") failed: %d (and no one data file can be closed)",
+                ControlFilePath, fd);
        goto tryAgain;
    }
    if (fd < 0)
@@ -1303,10 +1310,10 @@ tryAgain:
 
    close(fd);
 
-   if (ControlFile->logSeg == 0 || 
-       ControlFile->time <= 0 || 
-       ControlFile->state < DB_SHUTDOWNED || 
-       ControlFile->state > DB_IN_PRODUCTION || 
+   if (ControlFile->logSeg == 0 ||
+       ControlFile->time <= 0 ||
+       ControlFile->state < DB_SHUTDOWNED ||
+       ControlFile->state > DB_IN_PRODUCTION ||
        !XRecOffIsValid(ControlFile->checkPoint.xrecoff))
        elog(STOP, "Control file context is broken");
 
@@ -1323,20 +1330,20 @@ tryAgain:
 
    if (ControlFile->state == DB_SHUTDOWNED)
        elog(LOG, "Data Base System was shut down at %s",
-                   str_time(ControlFile->time));
+            str_time(ControlFile->time));
    else if (ControlFile->state == DB_SHUTDOWNING)
        elog(LOG, "Data Base System was interrupted when shutting down at %s",
-                   str_time(ControlFile->time));
+            str_time(ControlFile->time));
    else if (ControlFile->state == DB_IN_RECOVERY)
    {
        elog(LOG, "Data Base System was interrupted being in recovery at %s\n"
-                 "\tThis propably means that some data blocks are corrupted\n"
-                 "\tAnd you will have to use last backup for recovery",
-                   str_time(ControlFile->time));
+            "\tThis propably means that some data blocks are corrupted\n"
+            "\tAnd you will have to use last backup for recovery",
+            str_time(ControlFile->time));
    }
    else if (ControlFile->state == DB_IN_PRODUCTION)
        elog(LOG, "Data Base System was interrupted being in production at %s",
-                   str_time(ControlFile->time));
+            str_time(ControlFile->time));
 
 #ifdef NOT_USED
 
@@ -1350,14 +1357,14 @@ tryAgain:
        elog(STOP, "Invalid RMID in checkPoint record");
    if (record->xl_len != sizeof(checkPoint))
        elog(STOP, "Invalid length of checkPoint record");
-   checkPoint = *((CheckPoint*)((char*)record + SizeOfXLogRecord));
+   checkPoint = *((CheckPoint *) ((char *) record + SizeOfXLogRecord));
 
    elog(LOG, "Redo record at (%u, %u); Undo record at (%u, %u)",
-               checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
-               checkPoint.undo.xlogid, checkPoint.undo.xrecoff);
+        checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
+        checkPoint.undo.xlogid, checkPoint.undo.xrecoff);
    elog(LOG, "NextTransactionId: %u; NextOid: %u",
-               checkPoint.nextXid, checkPoint.nextOid);
-   if (checkPoint.nextXid < FirstTransactionId || 
+        checkPoint.nextXid, checkPoint.nextOid);
+   if (checkPoint.nextXid < FirstTransactionId ||
        checkPoint.nextOid < BootstrapObjectIdData)
 #ifdef XLOG
        elog(STOP, "Invalid NextTransactionId/NextOid");
@@ -1389,7 +1396,7 @@ tryAgain:
    if (recovery > 0)
    {
        elog(LOG, "The DataBase system was not properly shut down\n"
-                   "\tAutomatic recovery is in progress...");
+            "\tAutomatic recovery is in progress...");
        ControlFile->state = DB_IN_RECOVERY;
        ControlFile->time = time(NULL);
        UpdateControlFile();
@@ -1400,14 +1407,15 @@ tryAgain:
        /* Is REDO required ? */
        if (XLByteLT(checkPoint.redo, RecPtr))
            record = ReadRecord(&(checkPoint.redo), buffer);
-       else    /* read past CheckPoint record */
+       else
+/* read past CheckPoint record */
            record = ReadRecord(NULL, buffer);
 
        /* REDO */
        if (record->xl_len != 0)
        {
-           elog(LOG, "Redo starts at (%u, %u)", 
-                       ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
+           elog(LOG, "Redo starts at (%u, %u)",
+                ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
            do
            {
 #ifdef XLOG
@@ -1417,8 +1425,8 @@ tryAgain:
                RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
                record = ReadRecord(NULL, buffer);
            } while (record->xl_len != 0);
-           elog(LOG, "Redo done at (%u, %u)", 
-                       ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
+           elog(LOG, "Redo done at (%u, %u)",
+                ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
            LastRec = ReadRecPtr;
        }
        else
@@ -1431,18 +1439,18 @@ tryAgain:
        RecPtr = ReadRecPtr;
        if (XLByteLT(checkPoint.undo, RecPtr))
        {
-           elog(LOG, "Undo starts at (%u, %u)", 
-                       RecPtr.xlogid, RecPtr.xrecoff);
+           elog(LOG, "Undo starts at (%u, %u)",
+                RecPtr.xlogid, RecPtr.xrecoff);
            do
            {
                record = ReadRecord(&RecPtr, buffer);
-               if (TransactionIdIsValid(record->xl_xid) && 
+               if (TransactionIdIsValid(record->xl_xid) &&
                    !TransactionIdDidCommit(record->xl_xid))
                    RmgrTable[record->xl_rmid].rm_undo(record);
                RecPtr = record->xl_prev;
            } while (XLByteLE(checkPoint.undo, RecPtr));
-           elog(LOG, "Undo done at (%u, %u)", 
-                       ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
+           elog(LOG, "Undo done at (%u, %u)",
+                ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
        }
        else
        {
@@ -1458,19 +1466,19 @@ tryAgain:
    logOff = 0;
    logFile = XLogFileOpen(logId, logSeg, false);
    XLogCtl->xlblocks[0].xlogid = logId;
-   XLogCtl->xlblocks[0].xrecoff = 
-           ((EndRecPtr.xrecoff - 1) / BLCKSZ + 1) * BLCKSZ;
+   XLogCtl->xlblocks[0].xrecoff =
+       ((EndRecPtr.xrecoff - 1) / BLCKSZ + 1) * BLCKSZ;
    Insert = &XLogCtl->Insert;
-   memcpy((char*)(Insert->currpage), readBuf, BLCKSZ);
-   Insert->currpos = ((char*) Insert->currpage) + 
+   memcpy((char *) (Insert->currpage), readBuf, BLCKSZ);
+   Insert->currpos = ((char *) Insert->currpage) +
        (EndRecPtr.xrecoff + BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
    Insert->PrevRecord = ControlFile->checkPoint;
 
    if (recovery > 0)
    {
-       int     i;
+       int         i;
 
-       /* 
+       /*
         * Let resource managers know that recovery is done
         */
        for (i = 0; i <= RM_MAX_ID; i++)
@@ -1479,7 +1487,7 @@ tryAgain:
        StopIfError = sie_saved;
    }
 
-#endif /* NOT_USED */
+#endif  /* NOT_USED */
 
    ControlFile->state = DB_IN_PRODUCTION;
    ControlFile->time = time(NULL);
@@ -1508,11 +1516,11 @@ void
 CreateCheckPoint(bool shutdown)
 {
 #ifdef NOT_USED
-   CheckPoint          checkPoint;
-   XLogRecPtr          recptr;
-   XLogCtlInsert      *Insert = &XLogCtl->Insert;
-   uint32              freespace;
-   uint16              curridx;
+   CheckPoint  checkPoint;
+   XLogRecPtr  recptr;
+   XLogCtlInsert *Insert = &XLogCtl->Insert;
+   uint32      freespace;
+   uint16      curridx;
 
    memset(&checkPoint, 0, sizeof(checkPoint));
    if (shutdown)
@@ -1531,21 +1539,21 @@ CreateCheckPoint(bool shutdown)
            elog(STOP, "XLog insert lock is busy while data base is shutting down");
        (void) select(0, NULL, NULL, NULL, &delay);
    }
-   freespace = ((char*) Insert->currpage) + BLCKSZ - Insert->currpos;
+   freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
    if (freespace < SizeOfXLogRecord)
    {
        curridx = NextBufIdx(Insert->curridx);
        if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
            InitXLBuffer(curridx);
-       else 
+       else
            GetFreeXLBuffer();
        freespace = BLCKSZ - SizeOfXLogPHD;
    }
    else
        curridx = Insert->curridx;
    checkPoint.redo.xlogid = XLogCtl->xlblocks[curridx].xlogid;
-   checkPoint.redo.xrecoff = XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ + 
-                               Insert->currpos - ((char*) Insert->currpage);
+   checkPoint.redo.xrecoff = XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ +
+       Insert->currpos - ((char *) Insert->currpage);
    S_UNLOCK(&(XLogCtl->insert_lck));
 
    SpinAcquire(XidGenLockId);
@@ -1563,14 +1571,14 @@ CreateCheckPoint(bool shutdown)
    if (shutdown && checkPoint.undo.xrecoff != 0)
        elog(STOP, "Active transaction while data base is shutting down");
 
-   recptr = XLogInsert(RM_XLOG_ID, (char*)&checkPoint, sizeof(checkPoint), NULL, 0);
+   recptr = XLogInsert(RM_XLOG_ID, (char *) &checkPoint, sizeof(checkPoint), NULL, 0);
 
    if (shutdown && !XLByteEQ(checkPoint.redo, MyLastRecPtr))
        elog(STOP, "XLog concurrent activity while data base is shutting down");
 
    XLogFlush(recptr);
 
-#endif /* NOT_USED */
+#endif  /* NOT_USED */
 
    SpinAcquire(ControlFileLockId);
    if (shutdown)
index 8e129a460a9e56cb6b33ba66f5f1d17d98215f39..a12bca949327c59397eea46ebc87b76d16b444bd 100644 (file)
@@ -8,7 +8,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.80 2000/02/18 09:28:39 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.81 2000/04/12 17:14:54 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
 
 #define ALLOC(t, c)        (t *)calloc((unsigned)(c), sizeof(t))
 
-extern void        BaseInit(void);
-extern void        StartupXLOG(void);
-extern void        ShutdownXLOG(void);
-extern void        BootStrapXLOG(void);
+extern void BaseInit(void);
+extern void StartupXLOG(void);
+extern void ShutdownXLOG(void);
+extern void BootStrapXLOG(void);
 
-extern char        XLogDir[];
-extern char        ControlFilePath[];
+extern char XLogDir[];
+extern char ControlFilePath[];
 
 extern int Int_yyparse(void);
 static hashnode *AddStr(char *str, int strlength, int mderef);
@@ -107,7 +107,7 @@ static struct typinfo Procid[] = {
    {"char", CHAROID, 0, 1, F_CHARIN, F_CHAROUT},
    {"name", NAMEOID, 0, NAMEDATALEN, F_NAMEIN, F_NAMEOUT},
    {"int2", INT2OID, 0, 2, F_INT2IN, F_INT2OUT},
-   {"int2vector", INT2VECTOROID, 0, INDEX_MAX_KEYS*2, F_INT2VECTORIN, F_INT2VECTOROUT},
+   {"int2vector", INT2VECTOROID, 0, INDEX_MAX_KEYS * 2, F_INT2VECTORIN, F_INT2VECTOROUT},
    {"int4", INT4OID, 0, 4, F_INT4IN, F_INT4OUT},
    {"regproc", REGPROCOID, 0, 4, F_REGPROCIN, F_REGPROCOUT},
    {"text", TEXTOID, 0, -1, F_TEXTIN, F_TEXTOUT},
@@ -115,7 +115,7 @@ static struct typinfo Procid[] = {
    {"tid", TIDOID, 0, 6, F_TIDIN, F_TIDOUT},
    {"xid", XIDOID, 0, 4, F_XIDIN, F_XIDOUT},
    {"cid", CIDOID, 0, 4, F_CIDIN, F_CIDOUT},
-   {"oidvector", 30, 0, INDEX_MAX_KEYS*4, F_OIDVECTORIN, F_OIDVECTOROUT},
+   {"oidvector", 30, 0, INDEX_MAX_KEYS * 4, F_OIDVECTORIN, F_OIDVECTOROUT},
    {"smgr", 210, 0, 2, F_SMGRIN, F_SMGROUT},
    {"_int4", 1007, INT4OID, -1, F_ARRAY_IN, F_ARRAY_OUT},
    {"_aclitem", 1034, 1033, -1, F_ARRAY_IN, F_ARRAY_OUT}
@@ -325,8 +325,8 @@ BootstrapMain(int argc, char *argv[])
    }
 
    /*
-    * Bootstrap under Postmaster means two things:
-    * (xloginit) ? StartupXLOG : ShutdownXLOG
+    * Bootstrap under Postmaster means two things: (xloginit) ?
+    * StartupXLOG : ShutdownXLOG
     *
     * If !under Postmaster and xloginit then BootStrapXLOG.
     */
@@ -345,9 +345,7 @@ BootstrapMain(int argc, char *argv[])
    }
 
    if (!IsUnderPostmaster && xloginit)
-   {
        BootStrapXLOG();
-   }
 
    /*
     * backend initialization
@@ -478,7 +476,7 @@ boot_openrel(char *relname)
         */
        if (namestrcmp(&attrtypes[i]->attname, "attisset") == 0)
            attrtypes[i]->attisset = get_attisset(RelationGetRelid(reldesc),
-                                            NameStr(attrtypes[i]->attname));
+                                        NameStr(attrtypes[i]->attname));
        else
            attrtypes[i]->attisset = false;
 
@@ -1153,8 +1151,10 @@ build_indices()
        index_build(heap, ind, ILHead->il_natts, ILHead->il_attnos,
                 ILHead->il_nparams, ILHead->il_params, ILHead->il_finfo,
                    ILHead->il_predInfo);
-       /* In normal processing mode, index_build would close the heap
-        * and index, but in bootstrap mode it will not.
+
+       /*
+        * In normal processing mode, index_build would close the heap and
+        * index, but in bootstrap mode it will not.
         */
 
        /*
index e3fec88e97e469b351ce4465ab62e89cdc1ba215..c342b067ff4078b610db7eae0eb8197d6d8894b7 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/aclchk.c,v 1.37 2000/01/26 05:56:09 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/aclchk.c,v 1.38 2000/04/12 17:14:55 momjian Exp $
  *
  * NOTES
  *   See acl.h.
@@ -364,7 +364,7 @@ pg_aclcheck(char *relname, char *usename, AclMode mode)
     */
    if (((mode & ACL_WR) || (mode & ACL_AP)) &&
        !allowSystemTableMods && IsSystemRelationName(relname) &&
-       strncmp(relname,"pg_temp.", strlen("pg_temp.")) != 0 &&
+       strncmp(relname, "pg_temp.", strlen("pg_temp.")) != 0 &&
        !((Form_pg_shadow) GETSTRUCT(tuple))->usecatupd)
    {
        elog(DEBUG, "pg_aclcheck: catalog update to \"%s\": permission denied",
index 5425387b3fe32c5c1134d421ae83f06126cee8cb..4a5b1d9df2a96fadb9ef466b24ead3a65d140bc0 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/catalog.c,v 1.31 2000/04/09 04:43:15 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/catalog.c,v 1.32 2000/04/12 17:14:55 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -44,6 +44,7 @@ relpath(const char *relname)
        snprintf(path, bufsize, "%s%c%s", DataDir, SEP_CHAR, relname);
        return path;
    }
+
    /*
     * If it is in the current database, assume it is in current working
     * directory.  NB: this does not work during bootstrap!
@@ -55,7 +56,7 @@ relpath(const char *relname)
  * relpath_blind           - construct path to a relation's file
  *
  * Construct the path using only the info available to smgrblindwrt,
- * namely the names and OIDs of the database and relation.  (Shared system
+ * namely the names and OIDs of the database and relation. (Shared system
  * relations are identified with dbid = 0.)  Note that we may have to
  * access a relation belonging to a different database!
  *
index ae8d32bb8d522c6e50bc3a7b9b717a402ae2a3d0..b7c56d5eb63be3d22fe60ffd20c41a7c579d8a39 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.124 2000/03/17 02:36:05 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.125 2000/04/12 17:14:55 momjian Exp $
  *
  *
  * INTERFACE ROUTINES
@@ -69,9 +69,9 @@
 
 
 static void AddNewRelationTuple(Relation pg_class_desc,
-                               Relation new_rel_desc, Oid new_rel_oid,
-                               int natts,
-                               char relkind, char *temp_relname);
+                   Relation new_rel_desc, Oid new_rel_oid,
+                   int natts,
+                   char relkind, char *temp_relname);
 static void AddToNoNameRelList(Relation r);
 
 static void DeleteAttributeTuples(Relation rel);
@@ -82,7 +82,7 @@ static void RelationRemoveInheritance(Relation relation);
 static void RemoveFromNoNameRelList(Relation r);
 static void AddNewRelationType(char *typeName, Oid new_rel_oid);
 static void StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin,
-                            bool updatePgAttribute);
+                bool updatePgAttribute);
 static void StoreRelCheck(Relation rel, char *ccname, char *ccbin);
 static void StoreConstraints(Relation rel);
 static void RemoveConstraints(Relation rel);
@@ -271,8 +271,9 @@ heap_create(char *relname,
 
    rel = (Relation) palloc(len);
    MemSet((char *) rel, 0, len);
-   rel->rd_fd = -1;        /* table is not open */
+   rel->rd_fd = -1;            /* table is not open */
    rel->rd_unlinked = TRUE;    /* table is not created yet */
+
    /*
     * create a new tuple descriptor from the one passed in
     */
@@ -345,7 +346,7 @@ heap_create(char *relname,
 bool
 heap_storage_create(Relation rel)
 {
-   bool smgrcall = false;
+   bool        smgrcall = false;
 
    if (rel->rd_unlinked)
    {
@@ -715,6 +716,7 @@ AddNewRelationTuple(Relation pg_class_desc,
 
    if (!IsIgnoringSystemIndexes())
    {
+
        /*
         * First, open the catalog indices and insert index tuples for the
         * new relation.
@@ -878,7 +880,7 @@ heap_create_with_catalog(char *relname,
     *  SOMEDAY: fill the STATISTIC relation properly.
     * ----------------
     */
-   heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
+   heap_close(new_rel_desc, NoLock);   /* do not unlock till end of xact */
    heap_close(pg_class_desc, RowExclusiveLock);
 
    return new_rel_oid;
@@ -893,7 +895,7 @@ heap_create_with_catalog(char *relname,
  *     3)  remove indexes
  *     4)  remove pg_class tuple
  *     5)  remove pg_attribute tuples and related descriptions
- *              6)      remove pg_description tuples
+ *             6)      remove pg_description tuples
  *     7)  remove pg_type tuples
  *     8)  RemoveConstraints ()
  *     9)  unlink relation
@@ -963,7 +965,7 @@ RelationRemoveInheritance(Relation relation)
    tuple = heap_getnext(scan, 0);
    if (HeapTupleIsValid(tuple))
    {
-       Oid     subclass = ((Form_pg_inherits) GETSTRUCT(tuple))->inhrelid;
+       Oid         subclass = ((Form_pg_inherits) GETSTRUCT(tuple))->inhrelid;
 
        heap_endscan(scan);
        heap_close(catalogRelation, RowExclusiveLock);
@@ -1073,7 +1075,7 @@ DeleteRelationTuple(Relation rel)
    {
        heap_close(pg_class_desc, RowExclusiveLock);
        elog(ERROR, "Relation '%s' does not exist",
-                   RelationGetRelationName(rel));
+            RelationGetRelationName(rel));
    }
 
    /* ----------------
@@ -1096,19 +1098,27 @@ DeleteRelationTuple(Relation rel)
 static void
 RelationTruncateIndexes(Relation heapRelation)
 {
-   Relation indexRelation, currentIndex;
+   Relation    indexRelation,
+               currentIndex;
    ScanKeyData entry;
    HeapScanDesc scan;
-   HeapTuple indexTuple, procTuple, classTuple;
+   HeapTuple   indexTuple,
+               procTuple,
+               classTuple;
    Form_pg_index index;
-   Oid heapId, indexId, procId, accessMethodId;
-   Node *oldPred = NULL;
-   PredInfo *predInfo;
-   List *cnfPred = NULL;
+   Oid         heapId,
+               indexId,
+               procId,
+               accessMethodId;
+   Node       *oldPred = NULL;
+   PredInfo   *predInfo;
+   List       *cnfPred = NULL;
    AttrNumber *attributeNumberA;
-   FuncIndexInfo fInfo, *funcInfo = NULL;
-   int i, numberOfAttributes;
-   char *predString;
+   FuncIndexInfo fInfo,
+              *funcInfo = NULL;
+   int         i,
+               numberOfAttributes;
+   char       *predString;
 
    heapId = RelationGetRelid(heapRelation);
 
@@ -1120,8 +1130,10 @@ RelationTruncateIndexes(Relation heapRelation)
    scan = heap_beginscan(indexRelation, false, SnapshotNow, 1, &entry);
    while (HeapTupleIsValid(indexTuple = heap_getnext(scan, 0)))
    {
+
        /*
-        * For each index, fetch index attributes so we can apply index_build
+        * For each index, fetch index attributes so we can apply
+        * index_build
         */
        index = (Form_pg_index) GETSTRUCT(indexTuple);
        indexId = index->indexrelid;
@@ -1181,8 +1193,8 @@ RelationTruncateIndexes(Relation heapRelation)
        LockRelation(currentIndex, AccessExclusiveLock);
 
        /*
-        * Release any buffers associated with this index.  If they're dirty,
-        * they're just dropped without bothering to flush to disk.
+        * Release any buffers associated with this index.  If they're
+        * dirty, they're just dropped without bothering to flush to disk.
         */
        ReleaseRelationBuffers(currentIndex);
        if (FlushRelationBuffers(currentIndex, (BlockNumber) 0, false) < 0)
@@ -1198,35 +1210,35 @@ RelationTruncateIndexes(Relation heapRelation)
                    attributeNumberA, 0, NULL, funcInfo, predInfo);
 
        /*
-        * index_build will close both the heap and index relations
-        * (but not give up the locks we hold on them).  That's fine
-        * for the index, but we need to open the heap again.  We need
-        * no new lock, since this backend still has the exclusive lock
-        * grabbed by heap_truncate.
+        * index_build will close both the heap and index relations (but
+        * not give up the locks we hold on them).  That's fine for the
+        * index, but we need to open the heap again.  We need no new
+        * lock, since this backend still has the exclusive lock grabbed
+        * by heap_truncate.
         */
        heapRelation = heap_open(heapId, NoLock);
        Assert(heapRelation != NULL);
    }
 
    /* Complete the scan and close pg_index */
-    heap_endscan(scan);
+   heap_endscan(scan);
    heap_close(indexRelation, AccessShareLock);
 }
 
 /* ----------------------------
- *   heap_truncate
+ *  heap_truncate
  *
- *   This routine is used to truncate the data from the
- *   storage manager of any data within the relation handed
- *   to this routine.
+ *  This routine is used to truncate the data from the
+ *  storage manager of any data within the relation handed
+ *  to this routine.
  * ----------------------------
  */
 
 void
 heap_truncate(char *relname)
 {
-   Relation rel;
-   Oid rid;
+   Relation    rel;
+   Oid         rid;
 
    /* Open relation for processing, and grab exclusive access on it. */
 
@@ -1245,12 +1257,12 @@ heap_truncate(char *relname)
     *  they don't exist anyway.  So, no warning in that case.
     * ----------------
     */
-   if (IsTransactionBlock() && ! rel->rd_myxactonly)
+   if (IsTransactionBlock() && !rel->rd_myxactonly)
        elog(NOTICE, "Caution: TRUNCATE TABLE cannot be rolled back, so don't abort now");
 
    /*
-    * Release any buffers associated with this relation.  If they're dirty,
-    * they're just dropped without bothering to flush to disk.
+    * Release any buffers associated with this relation.  If they're
+    * dirty, they're just dropped without bothering to flush to disk.
     */
 
    ReleaseRelationBuffers(rel);
@@ -1300,17 +1312,17 @@ DeleteAttributeTuples(Relation rel)
         attnum++)
    {
        if (HeapTupleIsValid(tup = SearchSysCacheTupleCopy(ATTNUM,
-                                  ObjectIdGetDatum(RelationGetRelid(rel)),
-                                  Int16GetDatum(attnum),
+                                ObjectIdGetDatum(RelationGetRelid(rel)),
+                                                  Int16GetDatum(attnum),
                                                           0, 0)))
        {
-         
-         /*** Delete any comments associated with this attribute ***/
 
-         DeleteComments(tup->t_data->t_oid);
+           /*** Delete any comments associated with this attribute ***/
+
+           DeleteComments(tup->t_data->t_oid);
 
-         heap_delete(pg_attribute_desc, &tup->t_self, NULL);
-         heap_freetuple(tup);
+           heap_delete(pg_attribute_desc, &tup->t_self, NULL);
+           heap_freetuple(tup);
 
        }
    }
@@ -1429,7 +1441,7 @@ DeleteTypeTuple(Relation rel)
     *  we release the read lock on pg_type.  -mer 13 Aug 1991
     * ----------------
     */
-   
+
    heap_delete(pg_type_desc, &tup->t_self, NULL);
 
    heap_endscan(pg_type_scan);
@@ -1477,7 +1489,7 @@ heap_drop_with_catalog(const char *relname)
     *  they don't exist anyway.  So, no warning in that case.
     * ----------------
     */
-   if (IsTransactionBlock() && ! rel->rd_myxactonly)
+   if (IsTransactionBlock() && !rel->rd_myxactonly)
        elog(NOTICE, "Caution: DROP TABLE cannot be rolled back, so don't abort now");
 
    /* ----------------
@@ -1547,8 +1559,8 @@ heap_drop_with_catalog(const char *relname)
 
    /*
     * Close relcache entry, but *keep* AccessExclusiveLock on the
-    * relation until transaction commit.  This ensures no one else
-    * will try to do something with the doomed relation.
+    * relation until transaction commit.  This ensures no one else will
+    * try to do something with the doomed relation.
     */
    heap_close(rel, NoLock);
 
@@ -1704,7 +1716,7 @@ StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin,
    Relation    idescs[Num_pg_attrdef_indices];
    HeapTuple   tuple;
    Datum       values[4];
-   static char nulls[4] = {' ', ' ', ' ', ' '};
+   static char nulls[4] = {' ', ' ', ' ', ' '};
    Relation    attrrel;
    Relation    attridescs[Num_pg_attr_indices];
    HeapTuple   atttup;
@@ -1714,6 +1726,7 @@ StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin,
     * Need to construct source equivalent of given node-string.
     */
    expr = stringToNode(adbin);
+
    /*
     * deparse_expression needs a RangeTblEntry list, so make one
     */
@@ -1747,18 +1760,18 @@ StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin,
    heap_freetuple(tuple);
    pfree(adsrc);
 
-   if (! updatePgAttribute)
+   if (!updatePgAttribute)
        return;                 /* done if pg_attribute is OK */
 
    attrrel = heap_openr(AttributeRelationName, RowExclusiveLock);
    atttup = SearchSysCacheTupleCopy(ATTNUM,
-                                    ObjectIdGetDatum(RelationGetRelid(rel)),
+                                ObjectIdGetDatum(RelationGetRelid(rel)),
                                     (Datum) attnum, 0, 0);
    if (!HeapTupleIsValid(atttup))
        elog(ERROR, "cache lookup of attribute %d in relation %u failed",
             attnum, RelationGetRelid(rel));
    attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
-   if (! attStruct->atthasdef)
+   if (!attStruct->atthasdef)
    {
        attStruct->atthasdef = true;
        heap_update(attrrel, &atttup->t_self, atttup, NULL);
@@ -1789,13 +1802,14 @@ StoreRelCheck(Relation rel, char *ccname, char *ccbin)
    Relation    idescs[Num_pg_relcheck_indices];
    HeapTuple   tuple;
    Datum       values[4];
-   static char nulls[4] = {' ', ' ', ' ', ' '};
+   static char nulls[4] = {' ', ' ', ' ', ' '};
 
    /*
     * Convert condition to a normal boolean expression tree.
     */
    expr = stringToNode(ccbin);
    expr = (Node *) make_ands_explicit((List *) expr);
+
    /*
     * deparse_expression needs a RangeTblEntry list, so make one
     */
@@ -1850,9 +1864,10 @@ StoreConstraints(Relation rel)
    if (!constr)
        return;
 
-   /* deparsing of constraint expressions will fail unless the just-created
-    * pg_attribute tuples for this relation are made visible.  So, bump
-    * the command counter.
+   /*
+    * deparsing of constraint expressions will fail unless the
+    * just-created pg_attribute tuples for this relation are made
+    * visible.  So, bump the command counter.
     */
    CommandCounterIncrement();
 
@@ -1882,7 +1897,7 @@ StoreConstraints(Relation rel)
  * expression.
  *
  * NB: caller should have opened rel with AccessExclusiveLock, and should
- * hold that lock till end of transaction.  Also, we assume the caller has
+ * hold that lock till end of transaction. Also, we assume the caller has
  * done a CommandCounterIncrement if necessary to make the relation's catalog
  * tuples visible.
  */
@@ -1921,8 +1936,8 @@ AddRelationRawConstraints(Relation rel,
    }
 
    /*
-    * Create a dummy ParseState and insert the target relation as
-    * its sole rangetable entry.  We need a ParseState for transformExpr.
+    * Create a dummy ParseState and insert the target relation as its
+    * sole rangetable entry.  We need a ParseState for transformExpr.
     */
    pstate = make_parsestate(NULL);
    makeRangeTable(pstate, NULL);
@@ -1938,25 +1953,28 @@ AddRelationRawConstraints(Relation rel,
        Oid         type_id;
 
        Assert(colDef->raw_default != NULL);
+
        /*
         * Transform raw parsetree to executable expression.
         */
        expr = transformExpr(pstate, colDef->raw_default, EXPR_COLUMN_FIRST);
+
        /*
         * Make sure default expr does not refer to any vars.
         */
        if (contain_var_clause(expr))
            elog(ERROR, "Cannot use attribute(s) in DEFAULT clause");
+
        /*
-        * Check that it will be possible to coerce the expression
-        * to the column's type.  We store the expression without
-        * coercion, however, to avoid premature coercion in cases like
+        * Check that it will be possible to coerce the expression to the
+        * column's type.  We store the expression without coercion,
+        * however, to avoid premature coercion in cases like
         *
         * CREATE TABLE tbl (fld datetime DEFAULT 'now');
         *
-        * NB: this should match the code in updateTargetListEntry()
-        * that will actually do the coercion, to ensure we don't accept
-        * an unusable default expression.
+        * NB: this should match the code in updateTargetListEntry() that
+        * will actually do the coercion, to ensure we don't accept an
+        * unusable default expression.
         */
        type_id = exprType(expr);
        if (type_id != InvalidOid)
@@ -1966,23 +1984,26 @@ AddRelationRawConstraints(Relation rel,
            if (type_id != atp->atttypid)
            {
                if (CoerceTargetExpr(NULL, expr, type_id,
-                                    atp->atttypid, atp->atttypmod) == NULL)
+                                 atp->atttypid, atp->atttypmod) == NULL)
                    elog(ERROR, "Attribute '%s' is of type '%s'"
                         " but default expression is of type '%s'"
-                        "\n\tYou will need to rewrite or cast the expression",
+                   "\n\tYou will need to rewrite or cast the expression",
                         NameStr(atp->attname),
                         typeidTypeName(atp->atttypid),
                         typeidTypeName(type_id));
            }
        }
+
        /*
         * Might as well try to reduce any constant expressions.
         */
        expr = eval_const_expressions(expr);
+
        /*
         * Must fix opids, in case any operators remain...
         */
        fix_opids(expr);
+
        /*
         * OK, store it.
         */
@@ -2037,26 +2058,31 @@ AddRelationRawConstraints(Relation rel,
            ccname = (char *) palloc(NAMEDATALEN);
            snprintf(ccname, NAMEDATALEN, "$%d", numchecks + 1);
        }
+
        /*
         * Transform raw parsetree to executable expression.
         */
        expr = transformExpr(pstate, cdef->raw_expr, EXPR_COLUMN_FIRST);
+
        /*
         * Make sure it yields a boolean result.
         */
        if (exprType(expr) != BOOLOID)
            elog(ERROR, "CHECK '%s' does not yield boolean result",
                 ccname);
+
        /*
         * Make sure no outside relations are referred to.
         */
        if (length(pstate->p_rtable) != 1)
            elog(ERROR, "Only relation '%s' can be referenced in CHECK",
                 relname);
+
        /*
         * Might as well try to reduce any constant expressions.
         */
        expr = eval_const_expressions(expr);
+
        /*
         * Constraints are evaluated with execQual, which expects an
         * implicit-AND list, so convert expression to implicit-AND form.
@@ -2064,10 +2090,12 @@ AddRelationRawConstraints(Relation rel,
         * overkill...)
         */
        expr = (Node *) make_ands_implicit((Expr *) expr);
+
        /*
         * Must fix opids in operator clauses.
         */
        fix_opids(expr);
+
        /*
         * OK, store it.
         */
@@ -2081,12 +2109,12 @@ AddRelationRawConstraints(Relation rel,
     * We do this even if there was no change, in order to ensure that an
     * SI update message is sent out for the pg_class tuple, which will
     * force other backends to rebuild their relcache entries for the rel.
-    * (Of course, for a newly created rel there is no need for an SI message,
-    * but for ALTER TABLE ADD ATTRIBUTE this'd be important.)
+    * (Of course, for a newly created rel there is no need for an SI
+    * message, but for ALTER TABLE ADD ATTRIBUTE this'd be important.)
     */
    relrel = heap_openr(RelationRelationName, RowExclusiveLock);
    reltup = SearchSysCacheTupleCopy(RELOID,
-                                    ObjectIdGetDatum(RelationGetRelid(rel)),
+                                ObjectIdGetDatum(RelationGetRelid(rel)),
                                     0, 0, 0);
    if (!HeapTupleIsValid(reltup))
        elog(ERROR, "cache lookup of relation %u failed", RelationGetRelid(rel));
index 2a4cd3e6c5efcb5c2e880a49c87da825e93327f0..a8c649bc82da57c3da3df977a2dc9f654b9092f7 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/index.c,v 1.107 2000/03/01 05:39:24 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/index.c,v 1.108 2000/04/12 17:14:55 momjian Exp $
  *
  *
  * INTERFACE ROUTINES
 
 /* non-export function prototypes */
 static Oid GetHeapRelationOid(char *heapRelationName, char *indexRelationName,
-       bool istemp);
+                  bool istemp);
 static TupleDesc BuildFuncTupleDesc(FuncIndexInfo *funcInfo);
 static TupleDesc ConstructTupleDescriptor(Oid heapoid, Relation heapRelation,
-       List *attributeList, int numatts, AttrNumber *attNums);
+                 List *attributeList, int numatts, AttrNumber *attNums);
 
 static void ConstructIndexReldesc(Relation indexRelation, Oid amoid);
 static Oid UpdateRelationRelation(Relation indexRelation, char *temp_relname);
 static void InitializeAttributeOids(Relation indexRelation,
-       int numatts, Oid indexoid);
+                       int numatts, Oid indexoid);
 static void AppendAttributeTuples(Relation indexRelation, int numatts);
 static void UpdateIndexRelation(Oid indexoid, Oid heapoid,
-       FuncIndexInfo *funcInfo, int natts,
-       AttrNumber *attNums, Oid *classOids, Node *predicate,
-       List *attributeList, bool islossy, bool unique, bool primary);
+                   FuncIndexInfo *funcInfo, int natts,
+                   AttrNumber *attNums, Oid *classOids, Node *predicate,
+          List *attributeList, bool islossy, bool unique, bool primary);
 static void DefaultBuild(Relation heapRelation, Relation indexRelation,
-       int numberOfAttributes, AttrNumber *attributeNumber,
-       IndexStrategy indexStrategy, uint16 parameterCount,
+            int numberOfAttributes, AttrNumber *attributeNumber,
+            IndexStrategy indexStrategy, uint16 parameterCount,
        Datum *parameter, FuncIndexInfoPtr funcInfo, PredInfo *predInfo);
-static Oid IndexGetRelation(Oid indexId);
+static Oid IndexGetRelation(Oid indexId);
 
-static bool    reindexing = false;
-extern bool    SetReindexProcessing(bool reindexmode)
+static bool reindexing = false;
+extern bool
+SetReindexProcessing(bool reindexmode)
 {
-   bool    old = reindexing;
+   bool        old = reindexing;
+
    reindexing = reindexmode;
    return old;
 }
-extern bool    IsReindexProcessing(void)
+extern bool
+IsReindexProcessing(void)
 {
    return reindexing;
 }
+
 /* ----------------------------------------------------------------
  *   sysatts is a structure containing attribute tuple forms
  *   for system attributes (numbered -1, -2, ...).  This really
@@ -1011,7 +1015,7 @@ index_create(char *heapRelationName,
     * ----------------
     */
    indexRelation = heap_create(indexRelationName,
-               indexTupDesc, false, istemp, false);
+                               indexTupDesc, false, istemp, false);
 
    /* ----------------
     *    construct the index relation descriptor
@@ -1075,9 +1079,9 @@ index_create(char *heapRelationName,
     * bootstrapping.  Otherwise, we call the routine that constructs the
     * index.
     *
-    * In normal processing mode, the heap and index relations are closed
-    * by index_build() --- but we continue to hold the ShareLock on the
-    * heap that we acquired above, until end of transaction.
+    * In normal processing mode, the heap and index relations are closed by
+    * index_build() --- but we continue to hold the ShareLock on the heap
+    * that we acquired above, until end of transaction.
     */
    if (IsBootstrapProcessingMode())
    {
@@ -1139,7 +1143,7 @@ index_drop(Oid indexId)
     *  they don't exist anyway.  So, no warning in that case.
     * ----------------
     */
-   if (IsTransactionBlock() && ! userIndexRelation->rd_myxactonly)
+   if (IsTransactionBlock() && !userIndexRelation->rd_myxactonly)
        elog(NOTICE, "Caution: DROP INDEX cannot be rolled back, so don't abort now");
 
    /* ----------------
@@ -1147,7 +1151,7 @@ index_drop(Oid indexId)
     * ----------------
     */
    DeleteComments(indexId);
-   
+
    /* ----------------
     * fix RELATION relation
     * ----------------
@@ -1267,15 +1271,16 @@ FormIndexDatum(int numberOfAttributes,
  * --------------------------------------------
  */
 static
-bool LockClassinfoForUpdate(Oid relid, HeapTuple rtup, Buffer *buffer, bool confirmCommitted)
+bool
+LockClassinfoForUpdate(Oid relid, HeapTuple rtup, Buffer *buffer, bool confirmCommitted)
 {
    HeapTuple   classTuple;
-   Form_pg_class   pgcform;
+   Form_pg_class pgcform;
    bool        test;
    Relation    relationRelation;
 
    classTuple = SearchSysCacheTuple(RELOID, PointerGetDatum(relid),
-                           0, 0, 0);
+                                    0, 0, 0);
    if (!HeapTupleIsValid(classTuple))
        return false;
    rtup->t_self = classTuple->t_self;
@@ -1294,7 +1299,8 @@ bool LockClassinfoForUpdate(Oid relid, HeapTuple rtup, Buffer *buffer, bool conf
    RelationInvalidateHeapTuple(relationRelation, rtup);
    if (confirmCommitted)
    {
-       HeapTupleHeader th = rtup->t_data;
+       HeapTupleHeader th = rtup->t_data;
+
        if (!(th->t_infomask & HEAP_XMIN_COMMITTED))
            elog(ERROR, "The tuple isn't committed");
        if (th->t_infomask & HEAP_XMAX_COMMITTED)
@@ -1309,28 +1315,29 @@ bool LockClassinfoForUpdate(Oid relid, HeapTuple rtup, Buffer *buffer, bool conf
  *     Indexes of the relation active ?
  * ---------------------------------------------
  */
-bool IndexesAreActive(Oid relid, bool confirmCommitted)
+bool
+IndexesAreActive(Oid relid, bool confirmCommitted)
 {
-   HeapTupleData   tuple;
+   HeapTupleData tuple;
    Relation    indexRelation;
    Buffer      buffer;
-   HeapScanDesc    scan;
-   ScanKeyData entry;
+   HeapScanDesc scan;
+   ScanKeyData entry;
    bool        isactive;
 
    if (!LockClassinfoForUpdate(relid, &tuple, &buffer, confirmCommitted))
        elog(ERROR, "IndexesAreActive couldn't lock %u", relid);
    if (((Form_pg_class) GETSTRUCT(&tuple))->relkind != RELKIND_RELATION)
-       elog(ERROR, "relation %u isn't an relation", relid); 
+       elog(ERROR, "relation %u isn't an relation", relid);
    isactive = ((Form_pg_class) GETSTRUCT(&tuple))->relhasindex;
    ReleaseBuffer(buffer);
    if (isactive)
        return isactive;
    indexRelation = heap_openr(IndexRelationName, AccessShareLock);
    ScanKeyEntryInitialize(&entry, 0, Anum_pg_index_indrelid,
-           F_OIDEQ, ObjectIdGetDatum(relid));
+                          F_OIDEQ, ObjectIdGetDatum(relid));
    scan = heap_beginscan(indexRelation, false, SnapshotNow,
-                   1, &entry);
+                         1, &entry);
    if (!heap_getnext(scan, 0))
        isactive = true;
    heap_endscan(scan);
@@ -1348,8 +1355,8 @@ setRelhasindexInplace(Oid relid, bool hasindex, bool immediate)
    Relation    whichRel;
    Relation    pg_class;
    HeapTuple   tuple;
-   Form_pg_class   rd_rel;
-   HeapScanDesc    pg_class_scan = NULL;
+   Form_pg_class rd_rel;
+   HeapScanDesc pg_class_scan = NULL;
 
    /* ----------------
     * This routine handles updates for only the heap relation
@@ -1384,7 +1391,7 @@ setRelhasindexInplace(Oid relid, bool hasindex, bool immediate)
    if (!IsIgnoringSystemIndexes())
    {
        tuple = SearchSysCacheTupleCopy(RELOID,
-                                                   ObjectIdGetDatum(relid), 0, 0, 0);
+                                       ObjectIdGetDatum(relid), 0, 0, 0);
    }
    else
    {
@@ -1406,13 +1413,15 @@ setRelhasindexInplace(Oid relid, bool hasindex, bool immediate)
        heap_close(pg_class, RowExclusiveLock);
        elog(ERROR, "setRelhasindexInplace: cannot scan RELATION relation");
    }
+
    /*
-    * Confirm that target tuple is locked by this transaction
-    * in case of immedaite updation.
+    * Confirm that target tuple is locked by this transaction in case of
+    * immedaite updation.
     */
    if (immediate)
    {
-       HeapTupleHeader th = tuple->t_data;
+       HeapTupleHeader th = tuple->t_data;
+
        if (!(th->t_infomask & HEAP_XMIN_COMMITTED))
            elog(ERROR, "Immediate hasindex updation can be done only for committed tuples %x", th->t_infomask);
        if (th->t_infomask & HEAP_XMAX_INVALID)
@@ -1447,7 +1456,7 @@ setRelhasindexInplace(Oid relid, bool hasindex, bool immediate)
    }
    else
    {
-       HeapTupleData   htup;
+       HeapTupleData htup;
        Buffer      buffer;
 
        htup.t_self = tuple->t_self;
@@ -1485,7 +1494,7 @@ UpdateStats(Oid relid, long reltuples, bool inplace)
    Datum       values[Natts_pg_class];
    char        nulls[Natts_pg_class];
    char        replace[Natts_pg_class];
-   HeapScanDesc    pg_class_scan = NULL;
+   HeapScanDesc pg_class_scan = NULL;
    bool        in_place_upd;
 
    /* ----------------
@@ -1560,7 +1569,7 @@ UpdateStats(Oid relid, long reltuples, bool inplace)
     * pattern "CREATE TABLE; CREATE INDEX; insert data" leaves the table
     * with zero size statistics until a VACUUM is done.  The optimizer will
     * generate very bad plans if the stats claim the table is empty when
-    * it is actually sizable.  See also CREATE TABLE in heap.c.
+    * it is actually sizable.  See also CREATE TABLE in heap.c.
     * ----------------
     */
    relpages = RelationGetNumberOfBlocks(whichRel);
@@ -1697,10 +1706,12 @@ DefaultBuild(Relation heapRelation,
    char       *nullv;
    long        reltuples,
                indtuples;
+
 #ifndef OMIT_PARTIAL_INDEX
    ExprContext *econtext;
    TupleTable  tupleTable;
    TupleTableSlot *slot;
+
 #endif
    Node       *predicate;
    Node       *oldPred;
@@ -1781,6 +1792,7 @@ DefaultBuild(Relation heapRelation,
        reltuples++;
 
 #ifndef OMIT_PARTIAL_INDEX
+
        /*
         * If oldPred != NULL, this is an EXTEND INDEX command, so skip
         * this tuple if it was already in the existing partial index
@@ -1804,7 +1816,7 @@ DefaultBuild(Relation heapRelation,
        {
            /* SetSlotContents(slot, heapTuple); */
            slot->val = heapTuple;
-           if (! ExecQual((List *) predicate, econtext, false))
+           if (!ExecQual((List *) predicate, econtext, false))
                continue;
        }
 #endif  /* OMIT_PARTIAL_INDEX */
@@ -1854,18 +1866,18 @@ DefaultBuild(Relation heapRelation,
    /*
     * Since we just counted the tuples in the heap, we update its stats
     * in pg_class to guarantee that the planner takes advantage of the
-    * index we just created.  But, only update statistics during
-    * normal index definitions, not for indices on system catalogs
-    * created during bootstrap processing.  We must close the relations
-    * before updating statistics to guarantee that the relcache entries
-    * are flushed when we increment the command counter in UpdateStats().
-    * But we do not release any locks on the relations; those will be
-    * held until end of transaction.
+    * index we just created.  But, only update statistics during normal
+    * index definitions, not for indices on system catalogs created
+    * during bootstrap processing.  We must close the relations before
+    * updating statistics to guarantee that the relcache entries are
+    * flushed when we increment the command counter in UpdateStats(). But
+    * we do not release any locks on the relations; those will be held
+    * until end of transaction.
     */
    if (IsNormalProcessingMode())
    {
-       Oid     hrelid = RelationGetRelid(heapRelation);
-       Oid     irelid = RelationGetRelid(indexRelation);
+       Oid         hrelid = RelationGetRelid(heapRelation);
+       Oid         irelid = RelationGetRelid(indexRelation);
        bool        inplace = IsReindexProcessing();
 
        heap_close(heapRelation, NoLock);
@@ -1936,7 +1948,7 @@ index_build(Relation heapRelation,
 
 /*
  * IndexGetRelation: given an index's relation OID, get the OID of the
- * relation it is an index on.  Uses the system cache.
+ * relation it is an index on. Uses the system cache.
  */
 static Oid
 IndexGetRelation(Oid indexId)
@@ -2037,11 +2049,11 @@ IndexIsUniqueNoCache(Oid indexId)
 bool
 activate_index(Oid indexId, bool activate)
 {
-   if (!activate)  /* Currently does nothing */
+   if (!activate)              /* Currently does nothing */
        return true;
    return reindex_index(indexId, false);
 }
+
 /* --------------------------------
  * reindex_index - This routine is used to recreate an index
  * --------------------------------
@@ -2049,18 +2061,26 @@ activate_index(Oid indexId, bool activate)
 bool
 reindex_index(Oid indexId, bool force)
 {
-   Relation    iRel, indexRelation, heapRelation;
-   ScanKeyData entry;
-   HeapScanDesc    scan;
-   HeapTuple   indexTuple, procTuple, classTuple;
-   Form_pg_index   index;
-   Oid     heapId, procId, accessMethodId;
-   Node        *oldPred = NULL;
-   PredInfo    *predInfo;
-   AttrNumber  *attributeNumberA;
-   FuncIndexInfo   fInfo, *funcInfo = NULL;
-   int     i, numberOfAttributes;
-   char        *predString;
+   Relation    iRel,
+               indexRelation,
+               heapRelation;
+   ScanKeyData entry;
+   HeapScanDesc scan;
+   HeapTuple   indexTuple,
+               procTuple,
+               classTuple;
+   Form_pg_index index;
+   Oid         heapId,
+               procId,
+               accessMethodId;
+   Node       *oldPred = NULL;
+   PredInfo   *predInfo;
+   AttrNumber *attributeNumberA;
+   FuncIndexInfo fInfo,
+              *funcInfo = NULL;
+   int         i,
+               numberOfAttributes;
+   char       *predString;
    bool        old;
 
    old = SetReindexProcessing(true);
@@ -2135,7 +2155,7 @@ reindex_index(Oid indexId, bool force)
    LockRelation(iRel, AccessExclusiveLock);
 
    /*
-    * Release any buffers associated with this index.  If they're dirty,
+    * Release any buffers associated with this index.  If they're dirty,
     * they're just dropped without bothering to flush to disk.
     */
    ReleaseRelationBuffers(iRel);
@@ -2149,14 +2169,13 @@ reindex_index(Oid indexId, bool force)
    /* Initialize the index and rebuild */
    InitIndexStrategy(numberOfAttributes, iRel, accessMethodId);
    index_build(heapRelation, iRel, numberOfAttributes,
-           attributeNumberA, 0, NULL, funcInfo, predInfo);
+               attributeNumberA, 0, NULL, funcInfo, predInfo);
 
    /*
-    * index_build will close both the heap and index relations
-    * (but not give up the locks we hold on them).  That's fine
-    * for the index, but we need to open the heap again.  We need
-    * no new lock, since this backend still has the exclusive lock
-    * grabbed by heap_truncate.
+    * index_build will close both the heap and index relations (but not
+    * give up the locks we hold on them).  That's fine for the index, but
+    * we need to open the heap again.  We need no new lock, since this
+    * backend still has the exclusive lock grabbed by heap_truncate.
     */
    iRel = index_open(indexId);
    Assert(iRel != NULL);
@@ -2170,7 +2189,7 @@ reindex_index(Oid indexId, bool force)
 
 /*
  * ----------------------------
- * activate_indexes_of_a_table  
+ * activate_indexes_of_a_table
  * activate/deactivate indexes of the specified table.
  * ----------------------------
  */
@@ -2182,21 +2201,18 @@ activate_indexes_of_a_table(Oid relid, bool activate)
        if (!activate)
            setRelhasindexInplace(relid, false, true);
        else
-       {
            return false;
-       }
    }
    else
    {
        if (activate)
            reindex_relation(relid, false);
        else
-       {
            return false;
-       }   
    }
    return true;
 }
+
 /* --------------------------------
  * reindex_relation - This routine is used to recreate indexes
  * of a relation.
@@ -2206,10 +2222,11 @@ bool
 reindex_relation(Oid relid, bool force)
 {
    Relation    indexRelation;
-   ScanKeyData entry;
-   HeapScanDesc    scan;
+   ScanKeyData entry;
+   HeapScanDesc scan;
    HeapTuple   indexTuple;
-   bool        old, reindexed;
+   bool        old,
+               reindexed;
 
    old = SetReindexProcessing(true);
    if (IndexesAreActive(relid, true))
@@ -2224,13 +2241,14 @@ reindex_relation(Oid relid, bool force)
 
    indexRelation = heap_openr(IndexRelationName, AccessShareLock);
    ScanKeyEntryInitialize(&entry, 0, Anum_pg_index_indrelid,
-           F_OIDEQ, ObjectIdGetDatum(relid));
+                          F_OIDEQ, ObjectIdGetDatum(relid));
    scan = heap_beginscan(indexRelation, false, SnapshotNow,
-                   1, &entry);
+                         1, &entry);
    reindexed = false;
    while (HeapTupleIsValid(indexTuple = heap_getnext(scan, 0)))
    {
-       Form_pg_index   index = (Form_pg_index) GETSTRUCT(indexTuple);
+       Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
+
        if (activate_index(index->indexrelid, true))
            reindexed = true;
        else
@@ -2242,9 +2260,7 @@ reindex_relation(Oid relid, bool force)
    heap_endscan(scan);
    heap_close(indexRelation, AccessShareLock);
    if (reindexed)
-   {
        setRelhasindexInplace(relid, true, false);
-   }
    SetReindexProcessing(old);
    return reindexed;
 }
index 41337da77f8a469b682fc764b24d857fc97a18fd..eb3d6debcc585e2452abf7324b804f8b8bf4b950 100644 (file)
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/indexing.c,v 1.59 2000/02/18 09:28:41 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/indexing.c,v 1.60 2000/04/12 17:14:56 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
  */
 
 char      *Name_pg_aggregate_indices[Num_pg_aggregate_indices] =
-           {AggregateNameTypeIndex};
+{AggregateNameTypeIndex};
 char      *Name_pg_am_indices[Num_pg_am_indices] =
-           {AmNameIndex};
+{AmNameIndex};
 char      *Name_pg_amop_indices[Num_pg_amop_indices] =
-           {AccessMethodOpidIndex, AccessMethodStrategyIndex};
+{AccessMethodOpidIndex, AccessMethodStrategyIndex};
 char      *Name_pg_attr_indices[Num_pg_attr_indices] =
-           {AttributeRelidNameIndex, AttributeRelidNumIndex};
+{AttributeRelidNameIndex, AttributeRelidNumIndex};
 char      *Name_pg_attrdef_indices[Num_pg_attrdef_indices] =
-           {AttrDefaultIndex};
+{AttrDefaultIndex};
 char      *Name_pg_class_indices[Num_pg_class_indices] =
-           {ClassNameIndex, ClassOidIndex};
+{ClassNameIndex, ClassOidIndex};
 char      *Name_pg_group_indices[Num_pg_group_indices] =
-           {GroupNameIndex, GroupSysidIndex};
+{GroupNameIndex, GroupSysidIndex};
 char      *Name_pg_index_indices[Num_pg_index_indices] =
-           {IndexRelidIndex};
+{IndexRelidIndex};
 char      *Name_pg_inherits_indices[Num_pg_inherits_indices] =
-           {InheritsRelidSeqnoIndex};
+{InheritsRelidSeqnoIndex};
 char      *Name_pg_language_indices[Num_pg_language_indices] =
-           {LanguageOidIndex, LanguageNameIndex};
+{LanguageOidIndex, LanguageNameIndex};
 char      *Name_pg_listener_indices[Num_pg_listener_indices] =
-           {ListenerRelnamePidIndex};
+{ListenerRelnamePidIndex};
 char      *Name_pg_opclass_indices[Num_pg_opclass_indices] =
-           {OpclassNameIndex, OpclassDeftypeIndex};
+{OpclassNameIndex, OpclassDeftypeIndex};
 char      *Name_pg_operator_indices[Num_pg_operator_indices] =
-           {OperatorOidIndex, OperatorNameIndex};
+{OperatorOidIndex, OperatorNameIndex};
 char      *Name_pg_proc_indices[Num_pg_proc_indices] =
-           {ProcedureOidIndex, ProcedureNameIndex};
+{ProcedureOidIndex, ProcedureNameIndex};
 char      *Name_pg_relcheck_indices[Num_pg_relcheck_indices] =
-           {RelCheckIndex};
+{RelCheckIndex};
 char      *Name_pg_rewrite_indices[Num_pg_rewrite_indices] =
-           {RewriteOidIndex, RewriteRulenameIndex};
+{RewriteOidIndex, RewriteRulenameIndex};
 char      *Name_pg_shadow_indices[Num_pg_shadow_indices] =
-           {ShadowNameIndex, ShadowSysidIndex};
+{ShadowNameIndex, ShadowSysidIndex};
 char      *Name_pg_statistic_indices[Num_pg_statistic_indices] =
-           {StatisticRelidAttnumIndex};
+{StatisticRelidAttnumIndex};
 char      *Name_pg_trigger_indices[Num_pg_trigger_indices] =
-           {TriggerRelidIndex, TriggerConstrNameIndex, TriggerConstrRelidIndex};
+{TriggerRelidIndex, TriggerConstrNameIndex, TriggerConstrRelidIndex};
 char      *Name_pg_type_indices[Num_pg_type_indices] =
-           {TypeNameIndex, TypeOidIndex};
-char       *Name_pg_description_indices[Num_pg_description_indices] =
-           {DescriptionObjIndex};
+{TypeNameIndex, TypeOidIndex};
+char      *Name_pg_description_indices[Num_pg_description_indices] =
+{DescriptionObjIndex};
 
 
 
 static HeapTuple CatalogIndexFetchTuple(Relation heapRelation,
-                                          Relation idesc,
-                                          ScanKey skey,
-                                          int16 num_keys);
+                      Relation idesc,
+                      ScanKey skey,
+                      int16 num_keys);
 
 
 /*
@@ -279,7 +279,7 @@ CatalogIndexFetchTuple(Relation heapRelation,
 
 
 /*---------------------------------------------------------------------
- *                       Class-specific index lookups
+ *                      Class-specific index lookups
  *---------------------------------------------------------------------
  */
 
@@ -297,7 +297,7 @@ AggregateNameTypeIndexScan(Relation heapRelation, char *aggName, Oid aggType)
    Relation    idesc;
    ScanKeyData skey[2];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -324,7 +324,7 @@ AmNameIndexScan(Relation heapRelation, char *amName)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -414,8 +414,8 @@ AccessMethodStrategyIndexScan(Relation heapRelation,
 
 HeapTuple
 AttributeRelidNameIndexScan(Relation heapRelation,
-                      Oid relid,
-                      char *attname)
+                           Oid relid,
+                           char *attname)
 {
    Relation    idesc;
    ScanKeyData skey[2];
@@ -444,8 +444,8 @@ AttributeRelidNameIndexScan(Relation heapRelation,
 
 HeapTuple
 AttributeRelidNumIndexScan(Relation heapRelation,
-                     Oid relid,
-                     AttrNumber attnum)
+                          Oid relid,
+                          AttrNumber attnum)
 {
    Relation    idesc;
    ScanKeyData skey[2];
@@ -500,7 +500,7 @@ OpclassNameIndexScan(Relation heapRelation, char *opcName)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -521,7 +521,7 @@ GroupNameIndexScan(Relation heapRelation, char *groName)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -542,7 +542,7 @@ GroupSysidIndexScan(Relation heapRelation, int4 sysId)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -581,8 +581,8 @@ IndexRelidIndexScan(Relation heapRelation, Oid relid)
 
 HeapTuple
 InheritsRelidSeqnoIndexScan(Relation heapRelation,
-                          Oid relid,
-                          int4 seqno)
+                           Oid relid,
+                           int4 seqno)
 {
    Relation    idesc;
    ScanKeyData skey[2];
@@ -615,7 +615,7 @@ LanguageNameIndexScan(Relation heapRelation, char *lanName)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -658,7 +658,7 @@ ListenerRelnamePidIndexScan(Relation heapRelation, char *relName, int4 pid)
    Relation    idesc;
    ScanKeyData skey[2];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -681,10 +681,10 @@ ListenerRelnamePidIndexScan(Relation heapRelation, char *relName, int4 pid)
 
 HeapTuple
 OperatorNameIndexScan(Relation heapRelation,
-                      char *oprName,
-                      Oid   oprLeft,
-                      Oid   oprRight,
-                       char  oprKind)
+                     char *oprName,
+                     Oid oprLeft,
+                     Oid oprRight,
+                     char oprKind)
 {
    Relation    idesc;
    ScanKeyData skey[4];
@@ -810,7 +810,7 @@ ClassNameIndexScan(Relation heapRelation, char *relName)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -853,7 +853,7 @@ RewriteRulenameIndexScan(Relation heapRelation, char *ruleName)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -896,7 +896,7 @@ ShadowNameIndexScan(Relation heapRelation, char *useName)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -917,7 +917,7 @@ ShadowSysidIndexScan(Relation heapRelation, int4 sysId)
    Relation    idesc;
    ScanKeyData skey[1];
    HeapTuple   tuple;
-   
+
    ScanKeyEntryInitialize(&skey[0],
                           (bits16) 0x0,
                           (AttrNumber) 1,
@@ -934,8 +934,8 @@ ShadowSysidIndexScan(Relation heapRelation, int4 sysId)
 
 HeapTuple
 StatisticRelidAttnumIndexScan(Relation heapRelation,
-                      Oid relId,
-                      AttrNumber attNum)
+                             Oid relId,
+                             AttrNumber attNum)
 {
    Relation    idesc;
    ScanKeyData skey[2];
@@ -1004,4 +1004,3 @@ TypeOidIndexScan(Relation heapRelation, Oid typeId)
 
    return tuple;
 }
-
index 5554752bf3fdbe19e477150a6e026598151b5247..79d796ab49d692145c5b818d76303b4a37d5a28f 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/pg_aggregate.c,v 1.30 2000/03/26 19:43:58 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/pg_aggregate.c,v 1.31 2000/04/12 17:14:56 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -168,7 +168,7 @@ AggregateCreate(char *aggName,
    /* handle finalfn */
    if (aggfinalfnName)
    {
-       int nargs = 0;
+       int         nargs = 0;
 
        if (OidIsValid(xret1))
            fnArgs[nargs++] = xret1;
@@ -184,7 +184,7 @@ AggregateCreate(char *aggName,
        {
            if (nargs == 2)
                elog(ERROR, "AggregateCreate: '%s'('%s','%s') does not exist",
-                    aggfinalfnName, aggtransfn1typeName, aggtransfn2typeName);
+               aggfinalfnName, aggtransfn1typeName, aggtransfn2typeName);
            else if (OidIsValid(xret1))
                elog(ERROR, "AggregateCreate: '%s'('%s') does not exist",
                     aggfinalfnName, aggtransfn1typeName);
@@ -200,8 +200,10 @@ AggregateCreate(char *aggName,
    }
    else
    {
-       /* If no finalfn, aggregate result type is type of the sole
-        * state value (we already checked there is only one)
+
+       /*
+        * If no finalfn, aggregate result type is type of the sole state
+        * value (we already checked there is only one)
         */
        if (OidIsValid(xret1))
            fret = xret1;
@@ -284,9 +286,9 @@ AggNameGetInitVal(char *aggName, Oid basetype, int xfuncno, bool *isNull)
    Assert(xfuncno == 1 || xfuncno == 2);
 
    /*
-    * since we will have to use fastgetattr (in case one or both init vals
-    * are NULL), we will need to open the relation.  Do that first to
-    * ensure we don't get a stale tuple from the cache.
+    * since we will have to use fastgetattr (in case one or both init
+    * vals are NULL), we will need to open the relation.  Do that first
+    * to ensure we don't get a stale tuple from the cache.
     */
 
    aggRel = heap_openr(AggregateRelationName, AccessShareLock);
index 6557335d994b0bd8dfb3695d3a518556dc2e7caf..aa23a3be8c2d9718541d050457d1d63ec402ad6c 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/pg_proc.c,v 1.41 2000/04/04 21:44:37 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/pg_proc.c,v 1.42 2000/04/12 17:14:56 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -154,7 +154,7 @@ ProcedureCreate(char *procedureName,
                return tup->t_data->t_oid;
 #else
            elog(ERROR, "lookup for procedure by source needs fix (Jan)");
-#endif /* SETS_FIXED */
+#endif  /* SETS_FIXED */
        }
    }
 
@@ -245,7 +245,7 @@ ProcedureCreate(char *procedureName,
            prosrc = procedureName;
        if (fmgr_lookupByName(prosrc) == (func_ptr) NULL)
            elog(ERROR,
-                "ProcedureCreate: there is no builtin function named \"%s\"",
+           "ProcedureCreate: there is no builtin function named \"%s\"",
                 prosrc);
    }
 
index a4e970fbfc48bf16315e3a7258e69a19425857c4..4c3120c40f4015b02de9a7602eeb159573d9b024 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/catalog/pg_type.c,v 1.49 2000/01/26 05:56:11 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/catalog/pg_type.c,v 1.50 2000/04/12 17:14:56 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -374,7 +374,7 @@ TypeCreate(char *typeName,
    values[i++] = (Datum) GetUserId();  /* 2 */
    values[i++] = (Datum) internalSize; /* 3 */
    values[i++] = (Datum) externalSize; /* 4 */
-   values[i++] = (Datum) passedByValue;/* 5 */
+   values[i++] = (Datum) passedByValue;        /* 5 */
    values[i++] = (Datum) typeType;     /* 6 */
    values[i++] = (Datum) (bool) 1;     /* 7 */
    values[i++] = (Datum) typDelim;     /* 8 */
index 6fd21c9e57d2e8b84df77a321a032df06ac16a3c..a0b87743f5b24a32a43bbff26ccce77fa413b953 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/_deadcode/Attic/recipe.c,v 1.10 2000/01/26 05:56:17 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/_deadcode/Attic/recipe.c,v 1.11 2000/04/12 17:15:06 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -702,7 +702,7 @@ getParamTypes(TgElement * elem, Oid *typev)
        if (parameterCount == FUNC_MAX_ARGS)
        {
            elog(ERROR,
-                "getParamTypes: Ingredients cannot take > %d arguments",FUNC_MAX_ARGS);
+                "getParamTypes: Ingredients cannot take > %d arguments", FUNC_MAX_ARGS);
        }
        t = elem->inTypes->val[j];
        if (strcmp(t, "opaque") == 0)
@@ -810,7 +810,7 @@ tg_parseSubQuery(TgRecipe * r, TgNode * n, TeeInfo * teeInfo)
 {
    TgElement  *elem;
    char       *funcName;
-   Oid         typev[FUNC_MAX_ARGS],       /* eight arguments maximum  */
+   Oid         typev[FUNC_MAX_ARGS],   /* eight arguments maximum  */
                relid;
    int         i,
                parameterCount;
index e7cf7ac6748d8cb186bff18f0378250f35f894e7..f6079885fa718bfcf42f19a3d1ccac9f6fc73876 100644 (file)
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.58 2000/01/26 05:56:12 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.59 2000/04/12 17:14:57 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -155,12 +155,13 @@ Async_Notify(char *relname)
    /* no point in making duplicate entries in the list ... */
    if (!AsyncExistsPendingNotify(relname))
    {
+
        /*
         * We allocate list memory from the global malloc pool to ensure
-        * that it will live until we want to use it.  This is probably not
-        * necessary any longer, since we will use it before the end of the
-        * transaction. DLList only knows how to use malloc() anyway, but we
-        * could probably palloc() the strings...
+        * that it will live until we want to use it.  This is probably
+        * not necessary any longer, since we will use it before the end
+        * of the transaction. DLList only knows how to use malloc()
+        * anyway, but we could probably palloc() the strings...
         */
        notifyName = strdup(relname);
        DLAddHead(pendingNotifies, DLNewElem(notifyName));
@@ -466,6 +467,7 @@ AtCommit_Notify()
 
            if (listenerPID == MyProcPid)
            {
+
                /*
                 * Self-notify: no need to bother with table update.
                 * Indeed, we *must not* clear the notification field in
@@ -491,6 +493,7 @@ AtCommit_Notify()
                 */
                if (kill(listenerPID, SIGUSR2) < 0)
                {
+
                    /*
                     * Get rid of pg_listener entry if it refers to a PID
                     * that no longer exists.  Presumably, that backend
@@ -514,7 +517,7 @@ AtCommit_Notify()
                        if (RelationGetForm(lRel)->relhasindex)
                        {
                            Relation    idescs[Num_pg_listener_indices];
-                   
+
                            CatalogOpenIndices(Num_pg_listener_indices, Name_pg_listener_indices, idescs);
                            CatalogIndexInsert(idescs, Num_pg_listener_indices, lRel, rTuple);
                            CatalogCloseIndices(Num_pg_listener_indices, idescs);
@@ -780,7 +783,7 @@ ProcessIncomingNotify(void)
            if (RelationGetForm(lRel)->relhasindex)
            {
                Relation    idescs[Num_pg_listener_indices];
-       
+
                CatalogOpenIndices(Num_pg_listener_indices, Name_pg_listener_indices, idescs);
                CatalogIndexInsert(idescs, Num_pg_listener_indices, lRel, rTuple);
                CatalogCloseIndices(Num_pg_listener_indices, idescs);
index 299101337f1cc274c6b928b7be54d5049e401384..0cbf4a2177b29698af4ad906ceccd06f53481847 100644 (file)
@@ -15,7 +15,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.50 2000/01/26 05:56:13 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.51 2000/04/12 17:14:57 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -104,8 +104,8 @@ cluster(char *oldrelname, char *oldindexname)
     * Like vacuum, cluster spans transactions, so I'm going to handle it
     * in the same way: commit and restart transactions where needed.
     *
-    * We grab exclusive access to the target rel and index for the
-    * duration of the initial transaction.
+    * We grab exclusive access to the target rel and index for the duration
+    * of the initial transaction.
     */
 
    OldHeap = heap_openr(oldrelname, AccessExclusiveLock);
@@ -115,7 +115,7 @@ cluster(char *oldrelname, char *oldindexname)
    LockRelation(OldIndex, AccessExclusiveLock);
    OIDOldIndex = RelationGetRelid(OldIndex);
 
-   heap_close(OldHeap, NoLock); /* do NOT give up the locks */
+   heap_close(OldHeap, NoLock);/* do NOT give up the locks */
    index_close(OldIndex);
 
    /*
index b75f3840a879a819b2e541aac5b2a07d314e5421..2b9f6a257b12f87bc800374ee0a0a8dc80ea6c29 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/command.c,v 1.70 2000/03/09 05:00:23 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/command.c,v 1.71 2000/04/12 17:14:57 momjian Exp $
  *
  * NOTES
  *   The PortalExecutorHeapMemory crap needs to be eliminated
@@ -51,7 +51,7 @@
 #include "access/genam.h"
 #include "optimizer/clauses.h"
 #include "../parser/parse.h"
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
 
 /* ----------------
  *     PortalExecutorHeapMemory stuff
@@ -262,7 +262,7 @@ PerformPortalClose(char *name, CommandDest dest)
 }
 
 /* ----------------
- *      AlterTableAddColumn
+ *     AlterTableAddColumn
  *     (formerly known as PerformAddAttribute)
  *
  *     adds an additional attribute to a relation
@@ -327,8 +327,8 @@ AlterTableAddColumn(const char *relationName,
 #endif
 
    /*
-    * Grab an exclusive lock on the target table, which we will NOT release
-    * until end of transaction.
+    * Grab an exclusive lock on the target table, which we will NOT
+    * release until end of transaction.
     */
    rel = heap_openr(relationName, AccessExclusiveLock);
    myrelid = RelationGetRelid(rel);
@@ -341,7 +341,7 @@ AlterTableAddColumn(const char *relationName,
        elog(ERROR, "Can't add a NOT NULL attribute to an existing relation");
 
    if (colDef->raw_default || colDef->cooked_default)
-        elog(ERROR, "Adding columns with defaults is not implemented.");
+       elog(ERROR, "Adding columns with defaults is not implemented.");
 
 
    /*
@@ -370,7 +370,7 @@ AlterTableAddColumn(const char *relationName,
             */
            foreach(child, children)
            {
-               Oid     childrelid = lfirsti(child);
+               Oid         childrelid = lfirsti(child);
 
                if (childrelid == myrelid)
                    continue;
@@ -514,13 +514,13 @@ static void drop_default(Oid relid, int16 attnum);
  */
 void
 AlterTableAlterColumn(const char *relationName,
-                      bool inh, const char *colName,
-                      Node *newDefault)
+                     bool inh, const char *colName,
+                     Node *newDefault)
 {
-    Relation rel;
-    HeapTuple tuple;
-    int16 attnum;
-    Oid myrelid;
+   Relation    rel;
+   HeapTuple   tuple;
+   int16       attnum;
+   Oid         myrelid;
 
    if (!allowSystemTableMods && IsSystemRelationName(relationName))
        elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
@@ -530,121 +530,122 @@ AlterTableAlterColumn(const char *relationName,
        elog(ERROR, "ALTER TABLE: permission denied");
 #endif
 
-    rel = heap_openr(relationName, AccessExclusiveLock);
-    myrelid = RelationGetRelid(rel);
-    heap_close(rel, NoLock);
+   rel = heap_openr(relationName, AccessExclusiveLock);
+   myrelid = RelationGetRelid(rel);
+   heap_close(rel, NoLock);
 
-    /*
-     * Propagate to children if desired
-     */
+   /*
+    * Propagate to children if desired
+    */
    if (inh)
-    {
-        List      *child,
-            *children;
-
-        /* this routine is actually in the planner */
-        children = find_all_inheritors(myrelid);
-
-        /*
-         * find_all_inheritors does the recursive search of the
-         * inheritance hierarchy, so all we have to do is process all
-         * of the relids in the list that it returns.
-         */
-        foreach(child, children)
+   {
+       List       *child,
+                  *children;
+
+       /* this routine is actually in the planner */
+       children = find_all_inheritors(myrelid);
+
+       /*
+        * find_all_inheritors does the recursive search of the
+        * inheritance hierarchy, so all we have to do is process all of
+        * the relids in the list that it returns.
+        */
+       foreach(child, children)
        {
-            Oid        childrelid = lfirsti(child);
-
-            if (childrelid == myrelid)
-                continue;
-            rel = heap_open(childrelid, AccessExclusiveLock);
-            AlterTableAlterColumn(RelationGetRelationName(rel),
-                                  false, colName, newDefault);
-            heap_close(rel, AccessExclusiveLock);
-        }
-    }
-
-    /* -= now do the thing on this relation =- */
-
-    /* reopen the business */
-    rel = heap_openr((char *)relationName, AccessExclusiveLock);
-
-    /*
-     * get the number of the attribute
-     */
-    tuple = SearchSysCacheTuple(ATTNAME,
-                                ObjectIdGetDatum(myrelid),
-                                NameGetDatum(namein((char *)colName)),
-                                0, 0);
-
-    if (!HeapTupleIsValid(tuple))
-    {
-        heap_close(rel, AccessExclusiveLock);
-        elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
-             relationName, colName);
-    }
-
-    attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
-
-    if (newDefault) /* SET DEFAULT */
-    {
-        List* rawDefaults = NIL;
-           RawColumnDefault *rawEnt;
-
-        /* Get rid of the old one first */
-        drop_default(myrelid, attnum);
+           Oid         childrelid = lfirsti(child);
+
+           if (childrelid == myrelid)
+               continue;
+           rel = heap_open(childrelid, AccessExclusiveLock);
+           AlterTableAlterColumn(RelationGetRelationName(rel),
+                                 false, colName, newDefault);
+           heap_close(rel, AccessExclusiveLock);
+       }
+   }
+
+   /* -= now do the thing on this relation =- */
+
+   /* reopen the business */
+   rel = heap_openr((char *) relationName, AccessExclusiveLock);
+
+   /*
+    * get the number of the attribute
+    */
+   tuple = SearchSysCacheTuple(ATTNAME,
+                               ObjectIdGetDatum(myrelid),
+                               NameGetDatum(namein((char *) colName)),
+                               0, 0);
+
+   if (!HeapTupleIsValid(tuple))
+   {
+       heap_close(rel, AccessExclusiveLock);
+       elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
+            relationName, colName);
+   }
+
+   attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
+
+   if (newDefault)             /* SET DEFAULT */
+   {
+       List       *rawDefaults = NIL;
+       RawColumnDefault *rawEnt;
+
+       /* Get rid of the old one first */
+       drop_default(myrelid, attnum);
 
        rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
        rawEnt->attnum = attnum;
-        rawEnt->raw_default = newDefault;
+       rawEnt->raw_default = newDefault;
        rawDefaults = lappend(rawDefaults, rawEnt);
 
-        /*
-         * This function is intended for CREATE TABLE,
-         * so it processes a _list_ of defaults, but we just do one.
-         */
-        AddRelationRawConstraints(rel, rawDefaults, NIL);
-    }
-
-    else /* DROP DEFAULT */
-    {
-        Relation attr_rel;
-        ScanKeyData scankeys[3];
-        HeapScanDesc scan;
-        HeapTuple tuple;
-
-        attr_rel = heap_openr(AttributeRelationName, AccessExclusiveLock);
-        ScanKeyEntryInitialize(&scankeys[0], 0x0, Anum_pg_attribute_attrelid, F_OIDEQ,
-                               ObjectIdGetDatum(myrelid));
-        ScanKeyEntryInitialize(&scankeys[1], 0x0, Anum_pg_attribute_attnum, F_INT2EQ,
-                               Int16GetDatum(attnum));
-        ScanKeyEntryInitialize(&scankeys[2], 0x0, Anum_pg_attribute_atthasdef, F_BOOLEQ,
-                               TRUE);
-
-        scan = heap_beginscan(attr_rel, false, SnapshotNow, 3, scankeys);
-        AssertState(scan!=NULL);
-
-        if (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
-        {
-            HeapTuple newtuple;
-            Relation   irelations[Num_pg_attr_indices];
-
-            /* update to false */
-            newtuple = heap_copytuple(tuple);
-            ((Form_pg_attribute) GETSTRUCT(newtuple))->atthasdef = FALSE;
-            heap_update(attr_rel, &tuple->t_self, newtuple, NULL);
-
-            /* keep the system catalog indices current */
-            CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
-            CatalogIndexInsert(irelations, Num_pg_attr_indices, attr_rel, newtuple);
-            CatalogCloseIndices(Num_pg_attr_indices, irelations);
-
-            /* get rid of actual default definition */
-            drop_default(myrelid, attnum);
-        }
-
-        heap_endscan(scan);
-        heap_close(attr_rel, NoLock);
-    }
+       /*
+        * This function is intended for CREATE TABLE, so it processes a
+        * _list_ of defaults, but we just do one.
+        */
+       AddRelationRawConstraints(rel, rawDefaults, NIL);
+   }
+
+   else
+/* DROP DEFAULT */
+   {
+       Relation    attr_rel;
+       ScanKeyData scankeys[3];
+       HeapScanDesc scan;
+       HeapTuple   tuple;
+
+       attr_rel = heap_openr(AttributeRelationName, AccessExclusiveLock);
+       ScanKeyEntryInitialize(&scankeys[0], 0x0, Anum_pg_attribute_attrelid, F_OIDEQ,
+                              ObjectIdGetDatum(myrelid));
+       ScanKeyEntryInitialize(&scankeys[1], 0x0, Anum_pg_attribute_attnum, F_INT2EQ,
+                              Int16GetDatum(attnum));
+       ScanKeyEntryInitialize(&scankeys[2], 0x0, Anum_pg_attribute_atthasdef, F_BOOLEQ,
+                              TRUE);
+
+       scan = heap_beginscan(attr_rel, false, SnapshotNow, 3, scankeys);
+       AssertState(scan != NULL);
+
+       if (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
+       {
+           HeapTuple   newtuple;
+           Relation    irelations[Num_pg_attr_indices];
+
+           /* update to false */
+           newtuple = heap_copytuple(tuple);
+           ((Form_pg_attribute) GETSTRUCT(newtuple))->atthasdef = FALSE;
+           heap_update(attr_rel, &tuple->t_self, newtuple, NULL);
+
+           /* keep the system catalog indices current */
+           CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
+           CatalogIndexInsert(irelations, Num_pg_attr_indices, attr_rel, newtuple);
+           CatalogCloseIndices(Num_pg_attr_indices, irelations);
+
+           /* get rid of actual default definition */
+           drop_default(myrelid, attnum);
+       }
+
+       heap_endscan(scan);
+       heap_close(attr_rel, NoLock);
+   }
 
    heap_close(rel, NoLock);
 }
@@ -654,33 +655,33 @@ AlterTableAlterColumn(const char *relationName,
 static void
 drop_default(Oid relid, int16 attnum)
 {
-    ScanKeyData scankeys[2];
-    HeapScanDesc scan;
-    Relation attrdef_rel;
-    HeapTuple tuple;
+   ScanKeyData scankeys[2];
+   HeapScanDesc scan;
+   Relation    attrdef_rel;
+   HeapTuple   tuple;
 
-    attrdef_rel = heap_openr(AttrDefaultRelationName, AccessExclusiveLock);
-    ScanKeyEntryInitialize(&scankeys[0], 0x0, Anum_pg_attrdef_adrelid, F_OIDEQ,
-                           ObjectIdGetDatum(relid));
-    ScanKeyEntryInitialize(&scankeys[1], 0x0, Anum_pg_attrdef_adnum, F_INT2EQ,
-                           Int16GetDatum(attnum));
+   attrdef_rel = heap_openr(AttrDefaultRelationName, AccessExclusiveLock);
+   ScanKeyEntryInitialize(&scankeys[0], 0x0, Anum_pg_attrdef_adrelid, F_OIDEQ,
+                          ObjectIdGetDatum(relid));
+   ScanKeyEntryInitialize(&scankeys[1], 0x0, Anum_pg_attrdef_adnum, F_INT2EQ,
+                          Int16GetDatum(attnum));
 
-    scan = heap_beginscan(attrdef_rel, false, SnapshotNow, 2, scankeys);
-    AssertState(scan!=NULL);
+   scan = heap_beginscan(attrdef_rel, false, SnapshotNow, 2, scankeys);
+   AssertState(scan != NULL);
 
-    if (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
-        heap_delete(attrdef_rel, &tuple->t_self, NULL);
+   if (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
+       heap_delete(attrdef_rel, &tuple->t_self, NULL);
 
-    heap_endscan(scan);
+   heap_endscan(scan);
 
-    heap_close(attrdef_rel, NoLock);
+   heap_close(attrdef_rel, NoLock);
 }
 
 
 #ifdef _DROP_COLUMN_HACK__
 /*
  * ALTER TABLE DROP COLUMN trial implementation
- *     
+ *
  */
 
 /*
@@ -690,17 +691,17 @@ typedef struct SysScanDescData
 {
    Relation    heap_rel;
    Relation    irel;
-   HeapScanDesc    scan;
-   IndexScanDesc   iscan;
-   HeapTupleData   tuple;
+   HeapScanDesc scan;
+   IndexScanDesc iscan;
+   HeapTupleData tuple;
    Buffer      buffer;
-} SysScanDescData, *SysScanDesc;
-   
+}          SysScanDescData, *SysScanDesc;
+
 static void *
 systable_beginscan(Relation rel, const char *indexRelname, int nkeys, ScanKey entry)
 {
-   bool    hasindex = (rel->rd_rel->relhasindex && !IsIgnoringSystemIndexes());
-   SysScanDesc sysscan;
+   bool        hasindex = (rel->rd_rel->relhasindex && !IsIgnoringSystemIndexes());
+   SysScanDesc sysscan;
 
    sysscan = (SysScanDesc) palloc(sizeof(SysScanDescData));
    sysscan->heap_rel = rel;
@@ -710,7 +711,7 @@ systable_beginscan(Relation rel, const char *indexRelname, int nkeys, ScanKey en
    sysscan->buffer = InvalidBuffer;
    if (hasindex)
    {
-       sysscan->irel = index_openr((char *)indexRelname);
+       sysscan->irel = index_openr((char *) indexRelname);
        sysscan->iscan = index_beginscan(sysscan->irel, false, nkeys, entry);
    }
    else
@@ -720,7 +721,7 @@ systable_beginscan(Relation rel, const char *indexRelname, int nkeys, ScanKey en
 static void
 systable_endscan(void *scan)
 {
-   SysScanDesc sysscan = (SysScanDesc) scan;
+   SysScanDesc sysscan = (SysScanDesc) scan;
 
    if (sysscan->irel)
    {
@@ -736,9 +737,9 @@ systable_endscan(void *scan)
 static HeapTuple
 systable_getnext(void *scan)
 {
-   SysScanDesc sysscan = (SysScanDesc) scan;
+   SysScanDesc sysscan = (SysScanDesc) scan;
    HeapTuple   htup = (HeapTuple) NULL;
-   RetrieveIndexResult indexRes;
+   RetrieveIndexResult indexRes;
 
    if (sysscan->irel)
    {
@@ -774,50 +775,55 @@ find_attribute_walker(Node *node, int attnum)
        return false;
    if (IsA(node, Var))
    {
-       Var *var = (Var *) node;
+       Var        *var = (Var *) node;
+
        if (var->varlevelsup == 0 && var->varno == 1 &&
            var->varattno == attnum)
            return true;
    }
-   return expression_tree_walker(node, find_attribute_walker, (void *)attnum); 
+   return expression_tree_walker(node, find_attribute_walker, (void *) attnum);
 }
 static bool
 find_attribute_in_node(Node *node, int attnum)
 {
-   return  expression_tree_walker(node, find_attribute_walker, (void *)attnum);
+   return expression_tree_walker(node, find_attribute_walker, (void *) attnum);
 }
+
 /*
  * Remove/check references for the column
  */
 static bool
 RemoveColumnReferences(Oid reloid, int attnum, bool checkonly, HeapTuple reltup)
 {
-   Relation    indexRelation, rcrel;
-   ScanKeyData entry;
-   HeapScanDesc    scan;
-   void        *sysscan;
-   HeapTuple   htup, indexTuple;
-   Form_pg_index   index;
-   Form_pg_relcheck    relcheck;
-   Form_pg_class   pgcform = (Form_pg_class) NULL;
-   int     i;
+   Relation    indexRelation,
+               rcrel;
+   ScanKeyData entry;
+   HeapScanDesc scan;
+   void       *sysscan;
+   HeapTuple   htup,
+               indexTuple;
+   Form_pg_index index;
+   Form_pg_relcheck relcheck;
+   Form_pg_class pgcform = (Form_pg_class) NULL;
+   int         i;
    bool        checkok = true;
 
-   
+
    if (!checkonly)
-       pgcform = (Form_pg_class) GETSTRUCT (reltup);
+       pgcform = (Form_pg_class) GETSTRUCT(reltup);
+
    /*
-    *  Remove/check constraints here
+    * Remove/check constraints here
     */
    ScanKeyEntryInitialize(&entry, (bits16) 0x0, Anum_pg_relcheck_rcrelid,
-           (RegProcedure) F_OIDEQ, ObjectIdGetDatum(reloid));
+                      (RegProcedure) F_OIDEQ, ObjectIdGetDatum(reloid));
    rcrel = heap_openr(RelCheckRelationName, RowExclusiveLock);
-   sysscan = systable_beginscan(rcrel, RelCheckIndex,1 ,&entry);
+   sysscan = systable_beginscan(rcrel, RelCheckIndex, 1, &entry);
 
    while (HeapTupleIsValid(htup = systable_getnext(sysscan)))
    {
-       char    *ccbin;
-       Node    *node;
+       char       *ccbin;
+       Node       *node;
 
        relcheck = (Form_pg_relcheck) GETSTRUCT(htup);
        ccbin = textout(&relcheck->rcbin);
@@ -843,15 +849,15 @@ RemoveColumnReferences(Oid reloid, int attnum, bool checkonly, HeapTuple reltup)
    heap_close(rcrel, NoLock);
 
    /*
-    *  What to do with triggers/rules/views/procedues ?
+    * What to do with triggers/rules/views/procedues ?
     */
 
    /*
-    *  Remove/check indexes
+    * Remove/check indexes
     */
    indexRelation = heap_openr(IndexRelationName, RowExclusiveLock);
    ScanKeyEntryInitialize(&entry, 0, Anum_pg_index_indrelid, F_OIDEQ,
-               ObjectIdGetDatum(reloid));
+                          ObjectIdGetDatum(reloid));
    scan = heap_beginscan(indexRelation, false, SnapshotNow, 1, &entry);
    while (HeapTupleIsValid(indexTuple = heap_getnext(scan, 0)))
    {
@@ -870,8 +876,8 @@ RemoveColumnReferences(Oid reloid, int attnum, bool checkonly, HeapTuple reltup)
                else
                {
                    htup = SearchSysCacheTuple(RELOID,
-                       ObjectIdGetDatum(index->indexrelid),
-                       0, 0, 0); 
+                                    ObjectIdGetDatum(index->indexrelid),
+                                              0, 0, 0);
                    RemoveIndex(NameStr(((Form_pg_class) GETSTRUCT(htup))->relname));
                }
                break;
@@ -883,33 +889,38 @@ RemoveColumnReferences(Oid reloid, int attnum, bool checkonly, HeapTuple reltup)
 
    return checkok;
 }
-#endif /* _DROP_COLUMN_HACK__ */
+
+#endif  /* _DROP_COLUMN_HACK__ */
 
 /*
  * ALTER TABLE DROP COLUMN
  */
 void
 AlterTableDropColumn(const char *relationName,
-                     bool inh, const char *colName,
-                     int behavior)
+                    bool inh, const char *colName,
+                    int behavior)
 {
 #ifdef _DROP_COLUMN_HACK__
-   Relation    rel, attrdesc, adrel;
-   Oid     myrelid, attoid;
+   Relation    rel,
+               attrdesc,
+               adrel;
+   Oid         myrelid,
+               attoid;
    HeapTuple   reltup;
-   HeapTupleData   classtuple;
+   HeapTupleData classtuple;
    Buffer      buffer;
    Form_pg_attribute attribute;
    HeapTuple   tup;
    Relation    idescs[Num_pg_attr_indices];
-   int     attnum;
+   int         attnum;
    bool        hasindex;
    char        dropColname[32];
-   void        *sysscan;
-       ScanKeyData scankeys[2];
+   void       *sysscan;
+   ScanKeyData scankeys[2];
 
-   if (inh)    
+   if (inh)
        elog(ERROR, "ALTER TABLE / DROP COLUMN with inherit option is not supported yet");
+
    /*
     * permissions checking.  this would normally be done in utility.c,
     * but this particular routine is recursive.
@@ -925,25 +936,25 @@ AlterTableDropColumn(const char *relationName,
 #endif
 
    /*
-    * Grab an exclusive lock on the target table, which we will NOT release
-    * until end of transaction.
+    * Grab an exclusive lock on the target table, which we will NOT
+    * release until end of transaction.
     */
    rel = heap_openr(relationName, AccessExclusiveLock);
    myrelid = RelationGetRelid(rel);
    heap_close(rel, NoLock);    /* close rel but keep lock! */
 
    /*
-    *  What to do when rel has inheritors ?
+    * What to do when rel has inheritors ?
     */
    if (length(find_all_inheritors(myrelid)) > 1)
        elog(ERROR, "ALTER TABLE: cannot drop a column on table that is inherited from");
 
 
    /*
-    *  lock the pg_class tuple for update
+    * lock the pg_class tuple for update
     */
    reltup = SearchSysCacheTuple(RELNAME, PointerGetDatum(relationName),
-                           0, 0, 0);
+                                0, 0, 0);
 
    if (!HeapTupleIsValid(reltup))
        elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
@@ -976,19 +987,20 @@ AlterTableDropColumn(const char *relationName,
     * Get the target pg_attribute tuple
     */
    tup = SearchSysCacheTupleCopy(ATTNAME,
-               ObjectIdGetDatum(reltup->t_data->t_oid),
-               PointerGetDatum(colName), 0, 0);
+                                 ObjectIdGetDatum(reltup->t_data->t_oid),
+                                 PointerGetDatum(colName), 0, 0);
    if (!HeapTupleIsValid(tup))
        elog(ERROR, "ALTER TABLE: column name \"%s\" doesn't exist in table \"%s\"",
-                colName, relationName);
+            colName, relationName);
 
    attribute = (Form_pg_attribute) GETSTRUCT(tup);
    if (attribute->attnum <= 0)
        elog(ERROR, "ALTER TABLE: column name \"%s\" was already dropped", colName);
    attnum = attribute->attnum;
    attoid = tup->t_data->t_oid;
+
    /*
-    *  Check constraints/indices etc here
+    * Check constraints/indices etc here
     */
    if (behavior != CASCADE)
    {
@@ -997,7 +1009,7 @@ AlterTableDropColumn(const char *relationName,
    }
 
    /*
-    *  change the target pg_attribute tuple
+    * change the target pg_attribute tuple
     */
    sprintf(dropColname, "*already Dropped*%d", attnum);
    namestrcpy(&(attribute->attname), dropColname);
@@ -1009,7 +1021,7 @@ AlterTableDropColumn(const char *relationName,
    {
        CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);
        CatalogIndexInsert(idescs, Num_pg_attr_indices,
-               attrdesc, tup);
+                          attrdesc, tup);
        CatalogCloseIndices(Num_pg_attr_indices, idescs);
    }
    heap_close(attrdesc, NoLock);
@@ -1020,15 +1032,17 @@ AlterTableDropColumn(const char *relationName,
    /* delete attrdef */
    adrel = heap_openr(AttrDefaultRelationName, RowExclusiveLock);
    ScanKeyEntryInitialize(&scankeys[0], 0x0, Anum_pg_attrdef_adrelid,
-           F_OIDEQ, ObjectIdGetDatum(myrelid));
-   /* Oops pg_attrdef doesn't have (adrelid,adnum) index
-   ScanKeyEntryInitialize(&scankeys[1], 0x0, Anum_pg_attrdef_adnum,
-           F_INT2EQ, Int16GetDatum(attnum));
-   sysscan = systable_beginscan(adrel, AttrDefaultIndex, 2, scankeys);
-   */
+                          F_OIDEQ, ObjectIdGetDatum(myrelid));
+
+   /*
+    * Oops pg_attrdef doesn't have (adrelid,adnum) index
+    * ScanKeyEntryInitialize(&scankeys[1], 0x0, Anum_pg_attrdef_adnum,
+    * F_INT2EQ, Int16GetDatum(attnum)); sysscan =
+    * systable_beginscan(adrel, AttrDefaultIndex, 2, scankeys);
+    */
    sysscan = systable_beginscan(adrel, AttrDefaultIndex, 1, scankeys);
    while (HeapTupleIsValid(tup = systable_getnext(sysscan)))
-   { 
+   {
        if (((Form_pg_attrdef) GETSTRUCT(tup))->adnum == attnum)
        {
            heap_delete(adrel, &tup->t_self, NULL);
@@ -1037,8 +1051,9 @@ AlterTableDropColumn(const char *relationName,
    }
    systable_endscan(sysscan);
    heap_close(adrel, NoLock);
+
    /*
-    *  Remove objects which reference this column
+    * Remove objects which reference this column
     */
    if (behavior == CASCADE)
    {
@@ -1055,8 +1070,8 @@ AlterTableDropColumn(const char *relationName,
    heap_freetuple(reltup);
    heap_close(rel, NoLock);
 #else
-    elog(ERROR, "ALTER TABLE / DROP COLUMN is not implemented");
-#endif /* _DROP_COLUMN_HACK__ */
+               elog(ERROR, "ALTER TABLE / DROP COLUMN is not implemented");
+#endif  /* _DROP_COLUMN_HACK__ */
 }
 
 
@@ -1066,76 +1081,80 @@ AlterTableDropColumn(const char *relationName,
  */
 void
 AlterTableAddConstraint(const char *relationName,
-                        bool inh, Node *newConstraint)
+                       bool inh, Node *newConstraint)
 {
-   if (newConstraint == NULL) 
+   if (newConstraint == NULL)
        elog(ERROR, "ALTER TABLE / ADD CONSTRAINT passed invalid constraint.");
 
-   switch (nodeTag(newConstraint)) 
+   switch (nodeTag(newConstraint))
    {
        case T_Constraint:
            elog(ERROR, "ALTER TABLE / ADD CONSTRAINT is not implemented");
        case T_FkConstraint:
            {
-               FkConstraint *fkconstraint=(FkConstraint *)newConstraint;
-               Relation rel;
+               FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
+               Relation    rel;
                HeapScanDesc scan;
-               HeapTuple tuple;
-               Trigger trig;
-               List *list;
-               int count;
+               HeapTuple   tuple;
+               Trigger     trig;
+               List       *list;
+               int         count;
 
-               /* 
+               /*
                 * Grab an exclusive lock on the pk table, so that someone
-                * doesn't delete rows out from under us.  
+                * doesn't delete rows out from under us.
                 */
 
                rel = heap_openr(fkconstraint->pktable_name, AccessExclusiveLock);
                heap_close(rel, NoLock);
 
-               /* 
-                * Grab an exclusive lock on the fk table, and then scan through
-                * each tuple, calling the RI_FKey_Match_Ins (insert trigger)
-                * as if that tuple had just been inserted.  If any of those
-                * fail, it should elog(ERROR) and that's that.
+               /*
+                * Grab an exclusive lock on the fk table, and then scan
+                * through each tuple, calling the RI_FKey_Match_Ins
+                * (insert trigger) as if that tuple had just been
+                * inserted.  If any of those fail, it should elog(ERROR)
+                * and that's that.
                 */
                rel = heap_openr(relationName, AccessExclusiveLock);
                trig.tgoid = 0;
                trig.tgname = "<unknown>";
-               trig.tgfoid = 0; 
+               trig.tgfoid = 0;
                trig.tgtype = 0;
                trig.tgenabled = TRUE;
                trig.tgisconstraint = TRUE;
                trig.tginitdeferred = FALSE;
                trig.tgdeferrable = FALSE;
 
-               trig.tgargs = (char **)palloc(
-                       sizeof(char *) * (4 + length(fkconstraint->fk_attrs) 
-                                           + length(fkconstraint->pk_attrs)));
-               
+               trig.tgargs = (char **) palloc(
+                    sizeof(char *) * (4 + length(fkconstraint->fk_attrs)
+                                      + length(fkconstraint->pk_attrs)));
+
                trig.tgargs[0] = "<unnamed>";
-               trig.tgargs[1] = (char *)relationName;
+               trig.tgargs[1] = (char *) relationName;
                trig.tgargs[2] = fkconstraint->pktable_name;
                trig.tgargs[3] = fkconstraint->match_type;
                count = 4;
-               foreach (list, fkconstraint->fk_attrs) 
+               foreach(list, fkconstraint->fk_attrs)
                {
-                   Ident *fk_at = lfirst(list);
+                   Ident      *fk_at = lfirst(list);
+
                    trig.tgargs[count++] = fk_at->name;
                }
-               foreach (list, fkconstraint->pk_attrs) 
+               foreach(list, fkconstraint->pk_attrs)
                {
-                   Ident *pk_at = lfirst(list);
+                   Ident      *pk_at = lfirst(list);
+
                    trig.tgargs[count++] = pk_at->name;
                }
                trig.tgnargs = count;
 
                scan = heap_beginscan(rel, false, SnapshotNow, 0, NULL);
-               AssertState(scan!=NULL);
+               AssertState(scan != NULL);
 
                while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
                {
                    TriggerData newtrigdata;
+
                    newtrigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
                    newtrigdata.tg_relation = rel;
                    newtrigdata.tg_trigtuple = tuple;
@@ -1149,7 +1168,8 @@ AlterTableAddConstraint(const char *relationName,
                    /* Make a call to the check function */
                }
                heap_endscan(scan);
-               heap_close(rel, NoLock);     /* close rel but keep lock! */
+               heap_close(rel, NoLock);        /* close rel but keep
+                                                * lock! */
 
                pfree(trig.tgargs);
            }
@@ -1166,10 +1186,10 @@ AlterTableAddConstraint(const char *relationName,
  */
 void
 AlterTableDropConstraint(const char *relationName,
-                         bool inh, const char *constrName,
-                         int behavior)
+                        bool inh, const char *constrName,
+                        int behavior)
 {
-    elog(ERROR, "ALTER TABLE / DROP CONSTRAINT is not implemented");
+   elog(ERROR, "ALTER TABLE / DROP CONSTRAINT is not implemented");
 }
 
 
@@ -1186,7 +1206,7 @@ LockTableCommand(LockStmt *lockstmt)
    int         aclresult;
 
    rel = heap_openr(lockstmt->relname, NoLock);
-   if (! RelationIsValid(rel))
+   if (!RelationIsValid(rel))
        elog(ERROR, "Relation '%s' does not exist", lockstmt->relname);
 
    if (lockstmt->mode == AccessShareLock)
index 649025b4a136be32831c255b1f511b0ee2caf07a..3fe7b6f63470b74fdff6a577dbb52c874177073c 100644 (file)
@@ -67,44 +67,47 @@ static void CommentTrigger(char *trigger, char *relation, char *comments);
  *------------------------------------------------------------------
 */
 
-void CommentObject(int objtype, char *objname, char *objproperty,
-          List *objlist, char *comment) {
-
-  switch (objtype) {
-  case (INDEX):
-  case (SEQUENCE):
-  case (TABLE):
-  case (VIEW):
-    CommentRelation(objtype, objname, comment);
-    break;
-  case (COLUMN):
-    CommentAttribute(objname, objproperty, comment);
-    break;
-  case (DATABASE):
-    CommentDatabase(objname, comment);
-    break;
-  case (RULE):
-    CommentRewrite(objname, comment);
-    break;
-  case (TYPE_P):
-    CommentType(objname, comment);
-    break;
-  case (AGGREGATE):
-    CommentAggregate(objname, objproperty, comment);
-    break;
-  case (FUNCTION):
-    CommentProc(objname, objlist, comment);
-    break;
-  case (OPERATOR):
-    CommentOperator(objname, objlist, comment);
-    break;
-  case (TRIGGER):
-    CommentTrigger(objname, objproperty, comment);
-    break;
-  default:
-    elog(ERROR, "An attempt was made to comment on a unknown type: %i",
-    objtype);
-  }
+void
+CommentObject(int objtype, char *objname, char *objproperty,
+             List *objlist, char *comment)
+{
+
+   switch (objtype)
+   {
+           case (INDEX):
+           case (SEQUENCE):
+           case (TABLE):
+           case (VIEW):
+           CommentRelation(objtype, objname, comment);
+           break;
+       case (COLUMN):
+           CommentAttribute(objname, objproperty, comment);
+           break;
+       case (DATABASE):
+           CommentDatabase(objname, comment);
+           break;
+       case (RULE):
+           CommentRewrite(objname, comment);
+           break;
+       case (TYPE_P):
+           CommentType(objname, comment);
+           break;
+       case (AGGREGATE):
+           CommentAggregate(objname, objproperty, comment);
+           break;
+       case (FUNCTION):
+           CommentProc(objname, objlist, comment);
+           break;
+       case (OPERATOR):
+           CommentOperator(objname, objlist, comment);
+           break;
+       case (TRIGGER):
+           CommentTrigger(objname, objproperty, comment);
+           break;
+       default:
+           elog(ERROR, "An attempt was made to comment on a unknown type: %i",
+                objtype);
+   }
 
 
 }
@@ -120,87 +123,99 @@ void CommentObject(int objtype, char *objname, char *objproperty,
  *------------------------------------------------------------------
  */
 
-void CreateComments(Oid oid, char *comment) {
-
-  Relation description;
-  TupleDesc tupDesc;
-  HeapScanDesc scan;
-  ScanKeyData entry;
-  HeapTuple desctuple = NULL, searchtuple;
-  Datum values[Natts_pg_description];
-  char nulls[Natts_pg_description];
-  char replaces[Natts_pg_description];
-  bool modified = false;
-  int i;
-
-  /*** Open pg_description, form a new tuple, if necessary ***/
-
-  description = heap_openr(DescriptionRelationName, RowExclusiveLock);
-  tupDesc = description->rd_att;
-  if ((comment != NULL) && (strlen(comment) > 0)) {
-    for (i = 0; i < Natts_pg_description; i++) {
-      nulls[i] = ' ';
-      replaces[i] = 'r';
-      values[i] = (Datum) NULL;
-    }
-    i = 0;
-    values[i++] = ObjectIdGetDatum(oid);
-    values[i++] = (Datum) fmgr(F_TEXTIN, comment);
-  }
-
-  /*** Now, open pg_description and attempt to find the old tuple ***/
-
-  ScanKeyEntryInitialize(&entry, 0x0, Anum_pg_description_objoid, F_OIDEQ,
-            ObjectIdGetDatum(oid));
-  scan = heap_beginscan(description, false, SnapshotNow, 1, &entry);
-  searchtuple = heap_getnext(scan, 0);
-
-  /*** If a previous tuple exists, either delete or prep replacement ***/
-
-  if (HeapTupleIsValid(searchtuple)) {
-
-    /*** If the comment is blank, call heap_delete, else heap_update ***/
-
-    if ((comment == NULL) || (strlen(comment) == 0)) {
-      heap_delete(description, &searchtuple->t_self, NULL);
-    } else {
-      desctuple = heap_modifytuple(searchtuple, description, values,
-                  nulls, replaces);
-      heap_update(description, &searchtuple->t_self, desctuple, NULL);
-      modified = TRUE;
-    }
-
-  } else {
-
-   /*** Only if comment is non-blank do we form a new tuple ***/
-
-   if ((comment != NULL) && (strlen(comment) > 0)) {
-       desctuple = heap_formtuple(tupDesc, values, nulls);
-       heap_insert(description, desctuple);
-       modified = TRUE;
+void
+CreateComments(Oid oid, char *comment)
+{
+
+   Relation    description;
+   TupleDesc   tupDesc;
+   HeapScanDesc scan;
+   ScanKeyData entry;
+   HeapTuple   desctuple = NULL,
+               searchtuple;
+   Datum       values[Natts_pg_description];
+   char        nulls[Natts_pg_description];
+   char        replaces[Natts_pg_description];
+   bool        modified = false;
+   int         i;
+
+   /*** Open pg_description, form a new tuple, if necessary ***/
+
+   description = heap_openr(DescriptionRelationName, RowExclusiveLock);
+   tupDesc = description->rd_att;
+   if ((comment != NULL) && (strlen(comment) > 0))
+   {
+       for (i = 0; i < Natts_pg_description; i++)
+       {
+           nulls[i] = ' ';
+           replaces[i] = 'r';
+           values[i] = (Datum) NULL;
+       }
+       i = 0;
+       values[i++] = ObjectIdGetDatum(oid);
+       values[i++] = (Datum) fmgr(F_TEXTIN, comment);
+   }
+
+   /*** Now, open pg_description and attempt to find the old tuple ***/
+
+   ScanKeyEntryInitialize(&entry, 0x0, Anum_pg_description_objoid, F_OIDEQ,
+                          ObjectIdGetDatum(oid));
+   scan = heap_beginscan(description, false, SnapshotNow, 1, &entry);
+   searchtuple = heap_getnext(scan, 0);
+
+   /*** If a previous tuple exists, either delete or prep replacement ***/
+
+   if (HeapTupleIsValid(searchtuple))
+   {
+
+       /*** If the comment is blank, call heap_delete, else heap_update ***/
+
+       if ((comment == NULL) || (strlen(comment) == 0))
+           heap_delete(description, &searchtuple->t_self, NULL);
+       else
+       {
+           desctuple = heap_modifytuple(searchtuple, description, values,
+                                        nulls, replaces);
+           heap_update(description, &searchtuple->t_self, desctuple, NULL);
+           modified = TRUE;
+       }
+
    }
+   else
+   {
+
+       /*** Only if comment is non-blank do we form a new tuple ***/
+
+       if ((comment != NULL) && (strlen(comment) > 0))
+       {
+           desctuple = heap_formtuple(tupDesc, values, nulls);
+           heap_insert(description, desctuple);
+           modified = TRUE;
+       }
 
-  }
+   }
 
-  /*** Complete the scan, update indices, if necessary ***/
+   /*** Complete the scan, update indices, if necessary ***/
 
-  heap_endscan(scan);
+   heap_endscan(scan);
 
-  if (modified) {
-    if (RelationGetForm(description)->relhasindex) {
-      Relation idescs[Num_pg_description_indices];
+   if (modified)
+   {
+       if (RelationGetForm(description)->relhasindex)
+       {
+           Relation    idescs[Num_pg_description_indices];
 
-      CatalogOpenIndices(Num_pg_description_indices,
-            Name_pg_description_indices, idescs);
-      CatalogIndexInsert(idescs, Num_pg_description_indices, description,
-            desctuple);
-      CatalogCloseIndices(Num_pg_description_indices, idescs);
-    }
-    heap_freetuple(desctuple);
+           CatalogOpenIndices(Num_pg_description_indices,
+                              Name_pg_description_indices, idescs);
+           CatalogIndexInsert(idescs, Num_pg_description_indices, description,
+                              desctuple);
+           CatalogCloseIndices(Num_pg_description_indices, idescs);
+       }
+       heap_freetuple(desctuple);
 
-  }
+   }
 
-  heap_close(description, RowExclusiveLock);
+   heap_close(description, RowExclusiveLock);
 
 }
 
@@ -214,34 +229,35 @@ void CreateComments(Oid oid, char *comment) {
  *------------------------------------------------------------------
  */
 
-void DeleteComments(Oid oid) {
+void
+DeleteComments(Oid oid)
+{
 
-  Relation description;
-  TupleDesc tupDesc;
-  ScanKeyData entry;
-  HeapScanDesc scan;
-  HeapTuple searchtuple;
+   Relation    description;
+   TupleDesc   tupDesc;
+   ScanKeyData entry;
+   HeapScanDesc scan;
+   HeapTuple   searchtuple;
 
-  description = heap_openr(DescriptionRelationName, RowExclusiveLock);
-  tupDesc = description->rd_att;
+   description = heap_openr(DescriptionRelationName, RowExclusiveLock);
+   tupDesc = description->rd_att;
 
-  /*** Now, open pg_description and attempt to find the old tuple ***/
+   /*** Now, open pg_description and attempt to find the old tuple ***/
 
-  ScanKeyEntryInitialize(&entry, 0x0, Anum_pg_description_objoid, F_OIDEQ,
-            ObjectIdGetDatum(oid));
-  scan = heap_beginscan(description, false, SnapshotNow, 1, &entry);
-  searchtuple = heap_getnext(scan, 0);
+   ScanKeyEntryInitialize(&entry, 0x0, Anum_pg_description_objoid, F_OIDEQ,
+                          ObjectIdGetDatum(oid));
+   scan = heap_beginscan(description, false, SnapshotNow, 1, &entry);
+   searchtuple = heap_getnext(scan, 0);
 
-  /*** If a previous tuple exists, delete it ***/
+   /*** If a previous tuple exists, delete it ***/
 
-  if (HeapTupleIsValid(searchtuple)) {
-    heap_delete(description, &searchtuple->t_self, NULL);
-  }
+   if (HeapTupleIsValid(searchtuple))
+       heap_delete(description, &searchtuple->t_self, NULL);
 
-  /*** Complete the scan, update indices, if necessary ***/
+   /*** Complete the scan, update indices, if necessary ***/
 
-  heap_endscan(scan);
-  heap_close(description, RowExclusiveLock);
+   heap_endscan(scan);
+   heap_close(description, RowExclusiveLock);
 
 }
 
@@ -256,60 +272,57 @@ void DeleteComments(Oid oid) {
  *------------------------------------------------------------------
 */
 
-static void CommentRelation(int reltype, char *relname, char *comment) {
-
-  HeapTuple reltuple;
-  Oid oid;
-  char relkind;
-
-  /*** First, check object security ***/
-
-  #ifndef NO_SECURITY
-  if (!pg_ownercheck(GetPgUserName(), relname, RELNAME)) {
-    elog(ERROR, "you are not permitted to comment on class '%s'", relname);
-  }
-  #endif
-
-  /*** Now, attempt to find the oid in the cached version of pg_class ***/
-
-  reltuple = SearchSysCacheTuple(RELNAME, PointerGetDatum(relname),
-                0, 0, 0);
-  if (!HeapTupleIsValid(reltuple)) {
-    elog(ERROR, "relation '%s' does not exist", relname);
-  }
-
-  oid = reltuple->t_data->t_oid;
-
-  /*** Next, verify that the relation type matches the intent ***/
-
-  relkind = ((Form_pg_class) GETSTRUCT(reltuple))->relkind;
-
-  switch (reltype) {
-  case (INDEX):
-    if (relkind != 'i') {
-      elog(ERROR, "relation '%s' is not an index", relname);
-    }
-    break;
-  case (TABLE):
-    if (relkind != 'r') {
-      elog(ERROR, "relation '%s' is not a table", relname);
-    }
-    break;
-  case (VIEW):
-    if (relkind != 'r') {
-      elog(ERROR, "relation '%s' is not a view", relname);
-    }
-    break;
-  case (SEQUENCE):
-    if (relkind != 'S') {
-      elog(ERROR, "relation '%s' is not a sequence", relname);
-    }
-    break;
-  }
-
-  /*** Create the comments using the tuple's oid ***/
-
-  CreateComments(oid, comment);
+static void
+CommentRelation(int reltype, char *relname, char *comment)
+{
+
+   HeapTuple   reltuple;
+   Oid         oid;
+   char        relkind;
+
+   /*** First, check object security ***/
+
+#ifndef NO_SECURITY
+   if (!pg_ownercheck(GetPgUserName(), relname, RELNAME))
+       elog(ERROR, "you are not permitted to comment on class '%s'", relname);
+#endif
+
+   /*** Now, attempt to find the oid in the cached version of pg_class ***/
+
+   reltuple = SearchSysCacheTuple(RELNAME, PointerGetDatum(relname),
+                                  0, 0, 0);
+   if (!HeapTupleIsValid(reltuple))
+       elog(ERROR, "relation '%s' does not exist", relname);
+
+   oid = reltuple->t_data->t_oid;
+
+   /*** Next, verify that the relation type matches the intent ***/
+
+   relkind = ((Form_pg_class) GETSTRUCT(reltuple))->relkind;
+
+   switch (reltype)
+   {
+       case (INDEX):
+           if (relkind != 'i')
+               elog(ERROR, "relation '%s' is not an index", relname);
+           break;
+       case (TABLE):
+           if (relkind != 'r')
+               elog(ERROR, "relation '%s' is not a table", relname);
+           break;
+       case (VIEW):
+           if (relkind != 'r')
+               elog(ERROR, "relation '%s' is not a view", relname);
+           break;
+       case (SEQUENCE):
+           if (relkind != 'S')
+               elog(ERROR, "relation '%s' is not a sequence", relname);
+           break;
+   }
+
+   /*** Create the comments using the tuple's oid ***/
+
+   CreateComments(oid, comment);
 
 }
 
@@ -320,43 +333,45 @@ static void CommentRelation(int reltype, char *relname, char *comment) {
  * such as a table's column. The routine will check security
  * restrictions and then attempt to fetch the oid of the associated
  * attribute. If successful, a comment is added/dropped, else an
- * elog() exception is thrown.  The parameters are the relation
+ * elog() exception is thrown. The parameters are the relation
  * and attribute names, and the comments
  *------------------------------------------------------------------
 */
 
-static void CommentAttribute(char *relname, char *attrname, char *comment) {
+static void
+CommentAttribute(char *relname, char *attrname, char *comment)
+{
 
-  Relation relation;
-  HeapTuple attrtuple;
-  Oid oid;
+   Relation    relation;
+   HeapTuple   attrtuple;
+   Oid         oid;
 
-  /*** First, check object security ***/
+   /*** First, check object security ***/
 
-  #ifndef NO_SECURITY
-  if (!pg_ownercheck(GetPgUserName(), relname, RELNAME)) {
-    elog(ERROR, "you are not permitted to comment on class '%s\'", relname);
-  }
-  #endif
+#ifndef NO_SECURITY
+   if (!pg_ownercheck(GetPgUserName(), relname, RELNAME))
+       elog(ERROR, "you are not permitted to comment on class '%s\'", relname);
+#endif
 
-  /*** Now, fetch the attribute oid from the system cache ***/
+   /*** Now, fetch the attribute oid from the system cache ***/
 
-  relation = heap_openr(relname, AccessShareLock);
-  attrtuple = SearchSysCacheTuple(ATTNAME, ObjectIdGetDatum(relation->rd_id),
-                 PointerGetDatum(attrname), 0, 0);
-  if (!HeapTupleIsValid(attrtuple)) {
-    elog(ERROR, "'%s' is not an attribute of class '%s'",
-    attrname, relname);
-  }
-  oid = attrtuple->t_data->t_oid;
+   relation = heap_openr(relname, AccessShareLock);
+   attrtuple = SearchSysCacheTuple(ATTNAME, ObjectIdGetDatum(relation->rd_id),
+                                   PointerGetDatum(attrname), 0, 0);
+   if (!HeapTupleIsValid(attrtuple))
+   {
+       elog(ERROR, "'%s' is not an attribute of class '%s'",
+            attrname, relname);
+   }
+   oid = attrtuple->t_data->t_oid;
 
-  /*** Call CreateComments() to create/drop the comments ***/
+   /*** Call CreateComments() to create/drop the comments ***/
 
-  CreateComments(oid, comment);
+   CreateComments(oid, comment);
 
-  /*** Now, close the heap relation and return ***/
+   /*** Now, close the heap relation and return ***/
 
-  heap_close(relation, AccessShareLock);
+   heap_close(relation, AccessShareLock);
 
 }
 
@@ -371,61 +386,64 @@ static void CommentAttribute(char *relname, char *attrname, char *comment) {
  *------------------------------------------------------------------
 */
 
-static void CommentDatabase(char *database, char *comment) {
+static void
+CommentDatabase(char *database, char *comment)
+{
 
-  Relation pg_database;
-  HeapTuple dbtuple, usertuple;
-  ScanKeyData entry;
-  HeapScanDesc scan;
-  Oid oid;
-  bool superuser;
-  int4 dba, userid;
-  char *username;
+   Relation    pg_database;
+   HeapTuple   dbtuple,
+               usertuple;
+   ScanKeyData entry;
+   HeapScanDesc scan;
+   Oid         oid;
+   bool        superuser;
+   int4        dba,
+               userid;
+   char       *username;
 
-  /*** First find the tuple in pg_database for the database ***/
+   /*** First find the tuple in pg_database for the database ***/
 
-  pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
-  ScanKeyEntryInitialize(&entry, 0, Anum_pg_database_datname,
-            F_NAMEEQ, NameGetDatum(database));
-  scan = heap_beginscan(pg_database, 0, SnapshotNow, 1, &entry);
-  dbtuple = heap_getnext(scan, 0);
+   pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
+   ScanKeyEntryInitialize(&entry, 0, Anum_pg_database_datname,
+                          F_NAMEEQ, NameGetDatum(database));
+   scan = heap_beginscan(pg_database, 0, SnapshotNow, 1, &entry);
+   dbtuple = heap_getnext(scan, 0);
 
-  /*** Validate database exists, and fetch the dba id and oid ***/
+   /*** Validate database exists, and fetch the dba id and oid ***/
 
-  if (!HeapTupleIsValid(dbtuple)) {
-    elog(ERROR, "database '%s' does not exist", database);
-  }
-  dba = ((Form_pg_database) GETSTRUCT(dbtuple))->datdba;
-  oid = dbtuple->t_data->t_oid;
+   if (!HeapTupleIsValid(dbtuple))
+       elog(ERROR, "database '%s' does not exist", database);
+   dba = ((Form_pg_database) GETSTRUCT(dbtuple))->datdba;
+   oid = dbtuple->t_data->t_oid;
 
-  /*** Now, fetch user information ***/
+   /*** Now, fetch user information ***/
 
-  username = GetPgUserName();
-  usertuple = SearchSysCacheTuple(SHADOWNAME, PointerGetDatum(username),
-                 0, 0, 0);
-  if (!HeapTupleIsValid(usertuple)) {
-    elog(ERROR, "current user '%s' does not exist", username);
-  }
-  userid = ((Form_pg_shadow) GETSTRUCT(usertuple))->usesysid;
-  superuser = ((Form_pg_shadow) GETSTRUCT(usertuple))->usesuper;
+   username = GetPgUserName();
+   usertuple = SearchSysCacheTuple(SHADOWNAME, PointerGetDatum(username),
+                                   0, 0, 0);
+   if (!HeapTupleIsValid(usertuple))
+       elog(ERROR, "current user '%s' does not exist", username);
+   userid = ((Form_pg_shadow) GETSTRUCT(usertuple))->usesysid;
+   superuser = ((Form_pg_shadow) GETSTRUCT(usertuple))->usesuper;
 
-  /*** Allow if the userid matches the database dba or is a superuser ***/
+   /*** Allow if the userid matches the database dba or is a superuser ***/
 
-  #ifndef NO_SECURITY
-  if (!(superuser || (userid == dba))) {
-    elog(ERROR, "you are not permitted to comment on database '%s'",
-    database);
-  }
-  #endif
+#ifndef NO_SECURITY
+   if (!(superuser || (userid == dba)))
+   {
+       elog(ERROR, "you are not permitted to comment on database '%s'",
+            database);
+   }
+#endif
 
-  /*** Create the comments with the pg_database oid ***/
+   /*** Create the comments with the pg_database oid ***/
 
-  CreateComments(oid, comment);
+   CreateComments(oid, comment);
 
-  /*** Complete the scan and close any opened relations ***/
+   /*** Complete the scan and close any opened relations ***/
 
-  heap_endscan(scan);
-  heap_close(pg_database, AccessShareLock);
+   heap_endscan(scan);
+   heap_close(pg_database, AccessShareLock);
 
 }
 
@@ -439,38 +457,41 @@ static void CommentDatabase(char *database, char *comment) {
  *------------------------------------------------------------------
 */
 
-static void CommentRewrite(char *rule, char *comment) {
+static void
+CommentRewrite(char *rule, char *comment)
+{
 
-  HeapTuple rewritetuple;
-  Oid oid;
-  char *user, *relation;
-  int aclcheck;
+   HeapTuple   rewritetuple;
+   Oid         oid;
+   char       *user,
+              *relation;
+   int         aclcheck;
 
-  /*** First, validate user ***/
+   /*** First, validate user ***/
 
-  #ifndef NO_SECURITY
-  user = GetPgUserName();
-  relation = RewriteGetRuleEventRel(rule);
-  aclcheck = pg_aclcheck(relation, user, ACL_RU);
-  if (aclcheck != ACLCHECK_OK) {
-    elog(ERROR, "you are not permitted to comment on rule '%s'",
-    rule);
-  }
-  #endif
+#ifndef NO_SECURITY
+   user = GetPgUserName();
+   relation = RewriteGetRuleEventRel(rule);
+   aclcheck = pg_aclcheck(relation, user, ACL_RU);
+   if (aclcheck != ACLCHECK_OK)
+   {
+       elog(ERROR, "you are not permitted to comment on rule '%s'",
+            rule);
+   }
+#endif
 
-  /*** Next, find the rule's oid ***/
+   /*** Next, find the rule's oid ***/
 
-  rewritetuple = SearchSysCacheTuple(RULENAME, PointerGetDatum(rule),
-                    0, 0, 0);
-  if (!HeapTupleIsValid(rewritetuple)) {
-    elog(ERROR, "rule '%s' does not exist", rule);
-  }
+   rewritetuple = SearchSysCacheTuple(RULENAME, PointerGetDatum(rule),
+                                      0, 0, 0);
+   if (!HeapTupleIsValid(rewritetuple))
+       elog(ERROR, "rule '%s' does not exist", rule);
 
-  oid = rewritetuple->t_data->t_oid;
+   oid = rewritetuple->t_data->t_oid;
 
-  /*** Call CreateComments() to create/drop the comments ***/
+   /*** Call CreateComments() to create/drop the comments ***/
 
-  CreateComments(oid, comment);
+   CreateComments(oid, comment);
 
 }
 
@@ -485,35 +506,37 @@ static void CommentRewrite(char *rule, char *comment) {
  *------------------------------------------------------------------
 */
 
-static void CommentType(char *type, char *comment) {
+static void
+CommentType(char *type, char *comment)
+{
 
-  HeapTuple typetuple;
-  Oid oid;
-  char *user;
+   HeapTuple   typetuple;
+   Oid         oid;
+   char       *user;
 
-  /*** First, validate user ***/
+   /*** First, validate user ***/
 
-  #ifndef NO_SECURITY
-  user = GetPgUserName();
-  if (!pg_ownercheck(user, type, TYPENAME)) {
-    elog(ERROR, "you are not permitted to comment on type '%s'",
-    type);
-  }
-  #endif
+#ifndef NO_SECURITY
+   user = GetPgUserName();
+   if (!pg_ownercheck(user, type, TYPENAME))
+   {
+       elog(ERROR, "you are not permitted to comment on type '%s'",
+            type);
+   }
+#endif
 
-  /*** Next, find the type's oid ***/
+   /*** Next, find the type's oid ***/
 
-  typetuple = SearchSysCacheTuple(TYPENAME, PointerGetDatum(type),
-                 0, 0, 0);
-  if (!HeapTupleIsValid(typetuple)) {
-    elog(ERROR, "type '%s' does not exist", type);
-  }
+   typetuple = SearchSysCacheTuple(TYPENAME, PointerGetDatum(type),
+                                   0, 0, 0);
+   if (!HeapTupleIsValid(typetuple))
+       elog(ERROR, "type '%s' does not exist", type);
 
-  oid = typetuple->t_data->t_oid;
+   oid = typetuple->t_data->t_oid;
 
-  /*** Call CreateComments() to create/drop the comments ***/
+   /*** Call CreateComments() to create/drop the comments ***/
 
-  CreateComments(oid, comment);
+   CreateComments(oid, comment);
 
 }
 
@@ -527,57 +550,66 @@ static void CommentType(char *type, char *comment) {
  *------------------------------------------------------------------
 */
 
-static void CommentAggregate(char *aggregate, char *argument, char *comment) {
-
-  HeapTuple aggtuple;
-  Oid baseoid, oid;
-  bool defined;
-  char *user;
-
-  /*** First, attempt to determine the base aggregate oid ***/
-
-  if (argument) {
-    baseoid = TypeGet(argument, &defined);
-    if (!OidIsValid(baseoid)) {
-      elog(ERROR, "aggregate type '%s' does not exist", argument);
-    }
-  } else {
-    baseoid = 0;
-  }
-
-  /*** Next, validate the user's attempt to comment ***/
-
-  #ifndef NO_SECURITY
-  user = GetPgUserName();
-  if (!pg_aggr_ownercheck(user, aggregate, baseoid)) {
-    if (argument) {
-      elog(ERROR, "you are not permitted to comment on aggregate '%s' %s '%s'",
-      aggregate, "with type", argument);
-    } else {
-      elog(ERROR, "you are not permitted to comment on aggregate '%s'",
-      aggregate);
-    }
-  }
-  #endif
-
-  /*** Now, attempt to find the actual tuple in pg_aggregate ***/
-
-  aggtuple = SearchSysCacheTuple(AGGNAME, PointerGetDatum(aggregate),
-                ObjectIdGetDatum(baseoid), 0, 0);
-  if (!HeapTupleIsValid(aggtuple)) {
-    if (argument) {
-      elog(ERROR, "aggregate type '%s' does not exist for aggregate '%s'",
-      argument, aggregate);
-    } else {
-      elog(ERROR, "aggregate '%s' does not exist", aggregate);
-    }
-  }
-
-  oid = aggtuple->t_data->t_oid;
-
-  /*** Call CreateComments() to create/drop the comments ***/
-
-  CreateComments(oid, comment);
+static void
+CommentAggregate(char *aggregate, char *argument, char *comment)
+{
+
+   HeapTuple   aggtuple;
+   Oid         baseoid,
+               oid;
+   bool        defined;
+   char       *user;
+
+   /*** First, attempt to determine the base aggregate oid ***/
+
+   if (argument)
+   {
+       baseoid = TypeGet(argument, &defined);
+       if (!OidIsValid(baseoid))
+           elog(ERROR, "aggregate type '%s' does not exist", argument);
+   }
+   else
+       baseoid = 0;
+
+   /*** Next, validate the user's attempt to comment ***/
+
+#ifndef NO_SECURITY
+   user = GetPgUserName();
+   if (!pg_aggr_ownercheck(user, aggregate, baseoid))
+   {
+       if (argument)
+       {
+           elog(ERROR, "you are not permitted to comment on aggregate '%s' %s '%s'",
+                aggregate, "with type", argument);
+       }
+       else
+       {
+           elog(ERROR, "you are not permitted to comment on aggregate '%s'",
+                aggregate);
+       }
+   }
+#endif
+
+   /*** Now, attempt to find the actual tuple in pg_aggregate ***/
+
+   aggtuple = SearchSysCacheTuple(AGGNAME, PointerGetDatum(aggregate),
+                                  ObjectIdGetDatum(baseoid), 0, 0);
+   if (!HeapTupleIsValid(aggtuple))
+   {
+       if (argument)
+       {
+           elog(ERROR, "aggregate type '%s' does not exist for aggregate '%s'",
+                argument, aggregate);
+       }
+       else
+           elog(ERROR, "aggregate '%s' does not exist", aggregate);
+   }
+
+   oid = aggtuple->t_data->t_oid;
+
+   /*** Call CreateComments() to create/drop the comments ***/
+
+   CreateComments(oid, comment);
 
 }
 
@@ -592,12 +624,17 @@ static void CommentAggregate(char *aggregate, char *argument, char *comment) {
  *------------------------------------------------------------------
 */
 
-static void CommentProc(char *function, List *arguments, char *comment)
+static void
+CommentProc(char *function, List *arguments, char *comment)
 {
-   HeapTuple argtuple, functuple;
-   Oid oid, argoids[FUNC_MAX_ARGS];
-   char *user, *argument;
-   int i, argcount;
+   HeapTuple   argtuple,
+               functuple;
+   Oid         oid,
+               argoids[FUNC_MAX_ARGS];
+   char       *user,
+              *argument;
+   int         i,
+               argcount;
 
    /*** First, initialize function's argument list with their type oids ***/
 
@@ -606,13 +643,12 @@ static void CommentProc(char *function, List *arguments, char *comment)
    if (argcount > FUNC_MAX_ARGS)
        elog(ERROR, "functions cannot have more than %d arguments",
             FUNC_MAX_ARGS);
-   for (i = 0; i < argcount; i++) {
+   for (i = 0; i < argcount; i++)
+   {
        argument = strVal(lfirst(arguments));
        arguments = lnext(arguments);
        if (strcmp(argument, "opaque") == 0)
-       {
            argoids[i] = 0;
-       }
        else
        {
            argtuple = SearchSysCacheTuple(TYPENAME,
@@ -623,7 +659,7 @@ static void CommentProc(char *function, List *arguments, char *comment)
                     argument);
            argoids[i] = argtuple->t_data->t_oid;
        }
-    }
+   }
 
    /*** Now, validate the user's ability to comment on this function ***/
 
@@ -663,81 +699,89 @@ static void CommentProc(char *function, List *arguments, char *comment)
  *------------------------------------------------------------------
 */
 
-static void CommentOperator(char *opername, List *arguments, char *comment) {
-
-  Form_pg_operator data;
-  HeapTuple optuple;
-  Oid oid, leftoid = InvalidOid, rightoid = InvalidOid;
-  bool defined;
-  char oprtype = 0, *user, *lefttype = NULL, *righttype = NULL;
-
-  /*** Initialize our left and right argument types ***/
-
-  if (lfirst(arguments) != NULL) {
-    lefttype = strVal(lfirst(arguments));
-  }
-  if (lsecond(arguments) != NULL) {
-    righttype = strVal(lsecond(arguments));
-  }
+static void
+CommentOperator(char *opername, List *arguments, char *comment)
+{
 
-  /*** Attempt to fetch the left oid, if specified ***/
+   Form_pg_operator data;
+   HeapTuple   optuple;
+   Oid         oid,
+               leftoid = InvalidOid,
+               rightoid = InvalidOid;
+   bool        defined;
+   char        oprtype = 0,
+              *user,
+              *lefttype = NULL,
+              *righttype = NULL;
+
+   /*** Initialize our left and right argument types ***/
+
+   if (lfirst(arguments) != NULL)
+       lefttype = strVal(lfirst(arguments));
+   if (lsecond(arguments) != NULL)
+       righttype = strVal(lsecond(arguments));
+
+   /*** Attempt to fetch the left oid, if specified ***/
+
+   if (lefttype != NULL)
+   {
+       leftoid = TypeGet(lefttype, &defined);
+       if (!OidIsValid(leftoid))
+           elog(ERROR, "left type '%s' does not exist", lefttype);
+   }
 
-  if (lefttype != NULL) {
-    leftoid = TypeGet(lefttype, &defined);
-    if (!OidIsValid(leftoid)) {
-      elog(ERROR, "left type '%s' does not exist", lefttype);
-    }
-  }
+   /*** Attempt to fetch the right oid, if specified ***/
 
-  /*** Attempt to fetch the right oid, if specified ***/
+   if (righttype != NULL)
+   {
+       rightoid = TypeGet(righttype, &defined);
+       if (!OidIsValid(rightoid))
+           elog(ERROR, "right type '%s' does not exist", righttype);
+   }
 
-  if (righttype != NULL) {
-    rightoid = TypeGet(righttype, &defined);
-    if (!OidIsValid(rightoid)) {
-      elog(ERROR, "right type '%s' does not exist", righttype);
-    }
-  }
+   /*** Determine operator type ***/
 
-  /*** Determine operator type ***/
+   if (OidIsValid(leftoid) && (OidIsValid(rightoid)))
+       oprtype = 'b';
+   else if (OidIsValid(leftoid))
+       oprtype = 'l';
+   else if (OidIsValid(rightoid))
+       oprtype = 'r';
+   else
+       elog(ERROR, "operator '%s' is of an illegal type'", opername);
 
-  if (OidIsValid(leftoid) && (OidIsValid(rightoid))) oprtype = 'b';
-  else if (OidIsValid(leftoid)) oprtype = 'l';
-  else if (OidIsValid(rightoid)) oprtype = 'r';
-  else elog(ERROR, "operator '%s' is of an illegal type'", opername);
+   /*** Attempt to fetch the operator oid ***/
 
-  /*** Attempt to fetch the operator oid ***/
+   optuple = SearchSysCacheTupleCopy(OPERNAME, PointerGetDatum(opername),
+                                     ObjectIdGetDatum(leftoid),
+                                     ObjectIdGetDatum(rightoid),
+                                     CharGetDatum(oprtype));
+   if (!HeapTupleIsValid(optuple))
+       elog(ERROR, "operator '%s' does not exist", opername);
 
-  optuple = SearchSysCacheTupleCopy(OPERNAME, PointerGetDatum(opername),
-                   ObjectIdGetDatum(leftoid),
-                   ObjectIdGetDatum(rightoid),
-                   CharGetDatum(oprtype));
-  if (!HeapTupleIsValid(optuple)) {
-    elog(ERROR, "operator '%s' does not exist", opername);
-  }
+   oid = optuple->t_data->t_oid;
 
-  oid = optuple->t_data->t_oid;
+   /*** Valid user's ability to comment on this operator ***/
 
-  /*** Valid user's ability to comment on this operator ***/
+#ifndef NO_SECURITY
+   user = GetPgUserName();
+   if (!pg_ownercheck(user, (char *) ObjectIdGetDatum(oid), OPEROID))
+   {
+       elog(ERROR, "you are not permitted to comment on operator '%s'",
+            opername);
+   }
+#endif
 
-  #ifndef NO_SECURITY
-  user = GetPgUserName();
-  if (!pg_ownercheck(user, (char *) ObjectIdGetDatum(oid), OPEROID)) {
-    elog(ERROR, "you are not permitted to comment on operator '%s'",
-    opername);
-  }
-  #endif
+   /*** Get the procedure associated with the operator ***/
 
-  /*** Get the procedure associated with the operator ***/
+   data = (Form_pg_operator) GETSTRUCT(optuple);
+   oid = regproctooid(data->oprcode);
+   if (oid == InvalidOid)
+       elog(ERROR, "operator '%s' does not have an underlying function", opername);
 
-  data = (Form_pg_operator) GETSTRUCT(optuple);
-  oid = regproctooid(data->oprcode);
-  if (oid == InvalidOid) {
-     elog(ERROR, "operator '%s' does not have an underlying function", opername);
-  }
-  
-  /*** Call CreateComments() to create/drop the comments ***/
+   /*** Call CreateComments() to create/drop the comments ***/
 
-  CreateComments(oid, comment);
+   CreateComments(oid, comment);
 
 }
 
@@ -752,58 +796,65 @@ static void CommentOperator(char *opername, List *arguments, char *comment) {
  *------------------------------------------------------------------
 */
 
-static void CommentTrigger(char *trigger, char *relname, char *comment) {
-
-  Form_pg_trigger data;
-  Relation pg_trigger, relation;
-  HeapTuple triggertuple;
-  HeapScanDesc scan;
-  ScanKeyData entry;
-  Oid oid = InvalidOid;
-  char *user;
-
-  /*** First, validate the user's action ***/
-
-  #ifndef NO_SECURITY
-  user = GetPgUserName();
-  if (!pg_ownercheck(user, relname, RELNAME)) {
-    elog(ERROR, "you are not permitted to comment on trigger '%s' %s '%s'",
-    trigger, "defined for relation", relname);
-  }
-  #endif
-
-  /*** Now, fetch the trigger oid from pg_trigger  ***/
-
-  relation = heap_openr(relname, AccessShareLock);
-  pg_trigger = heap_openr(TriggerRelationName, AccessShareLock);
-  ScanKeyEntryInitialize(&entry, 0, Anum_pg_trigger_tgrelid,
-            F_OIDEQ, RelationGetRelid(relation));
-  scan = heap_beginscan(pg_trigger, 0, SnapshotNow, 1, &entry);
-  triggertuple = heap_getnext(scan, 0);
-  while (HeapTupleIsValid(triggertuple)) {
-    data = (Form_pg_trigger) GETSTRUCT(triggertuple);
-    if (namestrcmp(&(data->tgname), trigger) == 0) {
-      oid = triggertuple->t_data->t_oid;
-      break;
-    }
-    triggertuple = heap_getnext(scan, 0);
-  }
-
-  /*** If no trigger exists for the relation specified, notify user ***/
-
-  if (oid == InvalidOid) {
-    elog(ERROR, "trigger '%s' defined for relation '%s' does not exist",
-    trigger, relname);
-  }
-
-  /*** Create the comments with the pg_trigger oid ***/
-
-  CreateComments(oid, comment);
-
-  /*** Complete the scan and close any opened relations ***/
-
-  heap_endscan(scan);
-  heap_close(pg_trigger, AccessShareLock);
-  heap_close(relation, AccessShareLock);
+static void
+CommentTrigger(char *trigger, char *relname, char *comment)
+{
+
+   Form_pg_trigger data;
+   Relation    pg_trigger,
+               relation;
+   HeapTuple   triggertuple;
+   HeapScanDesc scan;
+   ScanKeyData entry;
+   Oid         oid = InvalidOid;
+   char       *user;
+
+   /*** First, validate the user's action ***/
+
+#ifndef NO_SECURITY
+   user = GetPgUserName();
+   if (!pg_ownercheck(user, relname, RELNAME))
+   {
+       elog(ERROR, "you are not permitted to comment on trigger '%s' %s '%s'",
+            trigger, "defined for relation", relname);
+   }
+#endif
+
+   /*** Now, fetch the trigger oid from pg_trigger  ***/
+
+   relation = heap_openr(relname, AccessShareLock);
+   pg_trigger = heap_openr(TriggerRelationName, AccessShareLock);
+   ScanKeyEntryInitialize(&entry, 0, Anum_pg_trigger_tgrelid,
+                          F_OIDEQ, RelationGetRelid(relation));
+   scan = heap_beginscan(pg_trigger, 0, SnapshotNow, 1, &entry);
+   triggertuple = heap_getnext(scan, 0);
+   while (HeapTupleIsValid(triggertuple))
+   {
+       data = (Form_pg_trigger) GETSTRUCT(triggertuple);
+       if (namestrcmp(&(data->tgname), trigger) == 0)
+       {
+           oid = triggertuple->t_data->t_oid;
+           break;
+       }
+       triggertuple = heap_getnext(scan, 0);
+   }
+
+   /*** If no trigger exists for the relation specified, notify user ***/
+
+   if (oid == InvalidOid)
+   {
+       elog(ERROR, "trigger '%s' defined for relation '%s' does not exist",
+            trigger, relname);
+   }
+
+   /*** Create the comments with the pg_trigger oid ***/
+
+   CreateComments(oid, comment);
+
+   /*** Complete the scan and close any opened relations ***/
+
+   heap_endscan(scan);
+   heap_close(pg_trigger, AccessShareLock);
+   heap_close(relation, AccessShareLock);
 
 }
index 8634ab11dd5913cea5a521fc4aa2e175f86c69b5..7662b9dc28a87ff1399aa65e4a44a66ead6d7323 100644 (file)
@@ -7,7 +7,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.103 2000/03/23 21:38:58 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.104 2000/04/12 17:14:58 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -64,8 +64,8 @@ static int    CountTuples(Relation relation);
  * Static communication variables ... pretty grotty, but COPY has
  * never been reentrant...
  */
-int        lineno = 0;     /* used by elog() -- dz */
-static bool    fe_eof;
+int            lineno = 0;         /* used by elog() -- dz */
+static bool fe_eof;
 
 /*
  * These static variables are used to avoid incurring overhead for each
@@ -76,9 +76,11 @@ static bool  fe_eof;
  * to attribute_buf's data buffer!
  * encoding, if needed, can be set once at the start of the copy operation.
  */
-static StringInfoData  attribute_buf;
+static StringInfoData attribute_buf;
+
 #ifdef MULTIBYTE
-static int             encoding;
+static int encoding;
+
 #endif
 
 
@@ -113,11 +115,11 @@ CopySendData(void *databuf, int datasize, FILE *fp)
            fe_eof = true;
    }
    else
-    {
+   {
        fwrite(databuf, datasize, 1, fp);
-        if (ferror(fp))
-            elog(ERROR, "CopySendData: %s", strerror(errno));
-    }
+       if (ferror(fp))
+           elog(ERROR, "CopySendData: %s", strerror(errno));
+   }
 }
 
 static void
@@ -194,7 +196,8 @@ CopyPeekChar(FILE *fp)
 {
    if (!fp)
    {
-       int ch = pq_peekbyte();
+       int         ch = pq_peekbyte();
+
        if (ch == EOF)
            fe_eof = true;
        return ch;
@@ -280,15 +283,15 @@ DoCopy(char *relname, bool binary, bool oids, bool from, bool pipe,
     * Open and lock the relation, using the appropriate lock type.
     *
     * Note: AccessExclusive is probably overkill for copying to a relation,
-    * but that's what the code grabs on the rel's indices.  If this lock is
-    * relaxed then I think the index locks need relaxed also.
+    * but that's what the code grabs on the rel's indices.  If this lock
+    * is relaxed then I think the index locks need relaxed also.
     */
    rel = heap_openr(relname, (from ? AccessExclusiveLock : AccessShareLock));
 
    result = pg_aclcheck(relname, UserName, required_access);
    if (result != ACLCHECK_OK)
        elog(ERROR, "%s: %s", relname, aclcheck_error_strings[result]);
-    if (!pipe && !superuser())
+   if (!pipe && !superuser())
        elog(ERROR, "You must have Postgres superuser privilege to do a COPY "
             "directly to or from a file.  Anyone can COPY to stdout or "
             "from stdin.  Psql's \\copy command also works for anyone.");
@@ -345,13 +348,13 @@ DoCopy(char *relname, bool binary, bool oids, bool from, bool pipe,
        }
        else
        {
-           mode_t      oumask;     /* Pre-existing umask value */
+           mode_t      oumask; /* Pre-existing umask value */
 
-            oumask = umask((mode_t) 022);
+           oumask = umask((mode_t) 022);
 
            if (*filename != '/')
                elog(ERROR, "Relative path not allowed for server side"
-                           " COPY command.");
+                    " COPY command.");
 
 #ifndef __CYGWIN32__
            fp = AllocateFile(filename, "w");
@@ -369,9 +372,7 @@ DoCopy(char *relname, bool binary, bool oids, bool from, bool pipe,
    }
 
    if (!pipe)
-   {
        FreeFile(fp);
-   }
    else if (!from)
    {
        if (!binary)
@@ -382,9 +383,10 @@ DoCopy(char *relname, bool binary, bool oids, bool from, bool pipe,
    pfree(attribute_buf.data);
 
    /*
-    * Close the relation.  If reading, we can release the AccessShareLock
-    * we got; if writing, we should hold the lock until end of transaction
-    * to ensure that updates will be committed before lock is released.
+    * Close the relation.  If reading, we can release the AccessShareLock
+    * we got; if writing, we should hold the lock until end of
+    * transaction to ensure that updates will be committed before lock is
+    * released.
     */
    heap_close(rel, (from ? NoLock : AccessShareLock));
 }
@@ -399,9 +401,11 @@ CopyTo(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null_p
 
    int32       attr_count,
                i;
+
 #ifdef _DROP_COLUMN_HACK__
-   bool        *valid;
-#endif /* _DROP_COLUMN_HACK__ */
+   bool       *valid;
+
+#endif  /* _DROP_COLUMN_HACK__ */
    Form_pg_attribute *attr;
    FmgrInfo   *out_functions;
    Oid         out_func_oid;
@@ -435,7 +439,7 @@ CopyTo(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null_p
        typmod = (int32 *) palloc(attr_count * sizeof(int32));
 #ifdef _DROP_COLUMN_HACK__
        valid = (bool *) palloc(attr_count * sizeof(bool));
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
        for (i = 0; i < attr_count; i++)
        {
 #ifdef _DROP_COLUMN_HACK__
@@ -446,7 +450,7 @@ CopyTo(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null_p
            }
            else
                valid[i] = true;
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
            out_func_oid = (Oid) GetOutputFunction(attr[i]->atttypid);
            fmgr_info(out_func_oid, &out_functions[i]);
            elements[i] = GetTypeElement(attr[i]->atttypid);
@@ -493,7 +497,7 @@ CopyTo(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null_p
                        CopySendChar('\n', fp);
                    continue;
                }
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
                if (!isnull)
                {
                    string = (char *) (*fmgr_faddr(&out_functions[i]))
@@ -502,7 +506,7 @@ CopyTo(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null_p
                    pfree(string);
                }
                else
-                   CopySendString(null_print, fp); /* null indicator */
+                   CopySendString(null_print, fp);     /* null indicator */
 
                if (i == attr_count - 1)
                    CopySendChar('\n', fp);
@@ -723,7 +727,7 @@ CopyFrom(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null
 #ifdef _DROP_COLUMN_HACK__
            if (COLUMN_IS_DROPPED(attr[i]))
                continue;
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
            in_func_oid = (Oid) GetInputFunction(attr[i]->atttypid);
            fmgr_info(in_func_oid, &in_functions[i]);
            elements[i] = GetTypeElement(attr[i]->atttypid);
@@ -756,7 +760,7 @@ CopyFrom(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null
            byval[i] = 'n';
            continue;
        }
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
        byval[i] = (bool) IsTypeByVal(attr[i]->atttypid);
    }
 
@@ -765,7 +769,8 @@ CopyFrom(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null
 
    while (!done)
    {
-       if (QueryCancel) {
+       if (QueryCancel)
+       {
            lineno = 0;
            CancelQuery();
        }
@@ -796,7 +801,7 @@ CopyFrom(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null
                    nulls[i] = 'n';
                    continue;
                }
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
                string = CopyReadAttribute(fp, &isnull, delim, &newline, null_print);
                if (isnull)
                {
@@ -937,7 +942,7 @@ CopyFrom(Relation rel, bool binary, bool oids, FILE *fp, char *delim, char *null
                         */
                        slot->val = tuple;
                        /* SetSlotContents(slot, tuple); */
-                       if (! ExecQual((List *) indexPred[i], econtext, false))
+                       if (!ExecQual((List *) indexPred[i], econtext, false))
                            continue;
 #endif  /* OMIT_PARTIAL_INDEX */
                    }
@@ -1189,6 +1194,7 @@ static char *
 CopyReadAttribute(FILE *fp, bool *isnull, char *delim, int *newline, char *null_print)
 {
    int         c;
+
 #ifdef MULTIBYTE
    int         mblen;
    unsigned char s[2];
@@ -1222,9 +1228,7 @@ CopyReadAttribute(FILE *fp, bool *isnull, char *delim, int *newline, char *null_
            break;
        }
        if (strchr(delim, c))
-       {
            break;
-       }
        if (c == '\\')
        {
            c = CopyGetChar(fp);
@@ -1272,13 +1276,16 @@ CopyReadAttribute(FILE *fp, bool *isnull, char *delim, int *newline, char *null_
                        c = val & 0377;
                    }
                    break;
-                    /* This is a special hack to parse `\N' as <backslash-N>
-                       rather then just 'N' to provide compatibility with
-                       the default NULL output. -- pe */
-                case 'N':
-                    appendStringInfoCharMacro(&attribute_buf, '\\');
-                    c = 'N';
-                    break;
+
+                   /*
+                    * This is a special hack to parse `\N' as
+                    * <backslash-N> rather then just 'N' to provide
+                    * compatibility with the default NULL output. -- pe
+                    */
+               case 'N':
+                   appendStringInfoCharMacro(&attribute_buf, '\\');
+                   c = 'N';
+                   break;
                case 'b':
                    c = '\b';
                    break;
@@ -1332,8 +1339,8 @@ CopyReadAttribute(FILE *fp, bool *isnull, char *delim, int *newline, char *null_
    }
 #endif
 
-    if (strcmp(attribute_buf.data, null_print)==0)
-        *isnull = true;
+   if (strcmp(attribute_buf.data, null_print) == 0)
+       *isnull = true;
 
    return attribute_buf.data;
 
@@ -1346,10 +1353,12 @@ CopyAttributeOut(FILE *fp, char *server_string, char *delim)
 {
    char       *string;
    char        c;
+
 #ifdef MULTIBYTE
    char       *string_start;
    int         mblen;
    int         i;
+
 #endif
 
 #ifdef MULTIBYTE
index da0fcd479ede24f661009907d95a1f75808704e1..17dbe2cbdffdde66628b74d680de8d54dd01d288 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/creatinh.c,v 1.56 2000/01/29 16:58:34 petere Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/creatinh.c,v 1.57 2000/04/12 17:14:58 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -32,7 +32,7 @@
  */
 
 static bool checkAttrExists(const char *attributeName,
-                            const char *attributeType, List *schema);
+               const char *attributeType, List *schema);
 static List *MergeAttributes(List *schema, List *supers, List **supconstr);
 static void StoreCatalogInheritance(Oid relationId, List *supers);
 
@@ -145,14 +145,14 @@ DefineRelation(CreateStmt *stmt, char relkind)
    StoreCatalogInheritance(relationId, inheritList);
 
    /*
-    * Now add any newly specified column default values
-    * and CHECK constraints to the new relation.  These are passed
-    * to us in the form of raw parsetrees; we need to transform
-    * them to executable expression trees before they can be added.
-    * The most convenient way to do that is to apply the parser's
-    * transformExpr routine, but transformExpr doesn't work unless
-    * we have a pre-existing relation.  So, the transformation has
-    * to be postponed to this final step of CREATE TABLE.
+    * Now add any newly specified column default values and CHECK
+    * constraints to the new relation.  These are passed to us in the
+    * form of raw parsetrees; we need to transform them to executable
+    * expression trees before they can be added. The most convenient way
+    * to do that is to apply the parser's transformExpr routine, but
+    * transformExpr doesn't work unless we have a pre-existing relation.
+    * So, the transformation has to be postponed to this final step of
+    * CREATE TABLE.
     *
     * First, scan schema to find new column defaults.
     */
@@ -181,21 +181,24 @@ DefineRelation(CreateStmt *stmt, char relkind)
        return;
 
    /*
-    * We must bump the command counter to make the newly-created
-    * relation tuple visible for opening.
+    * We must bump the command counter to make the newly-created relation
+    * tuple visible for opening.
     */
    CommandCounterIncrement();
+
    /*
     * Open the new relation.
     */
    rel = heap_openr(relname, AccessExclusiveLock);
+
    /*
     * Parse and add the defaults/constraints.
     */
    AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
+
    /*
-    * Clean up.  We keep lock on new relation (although it shouldn't
-    * be visible to anyone else anyway, until commit).
+    * Clean up.  We keep lock on new relation (although it shouldn't be
+    * visible to anyone else anyway, until commit).
     */
    heap_close(rel, NoLock);
 }
@@ -220,13 +223,13 @@ RemoveRelation(char *name)
 
 /*
  * TruncateRelation --
- *                Removes all the rows from a relation
+ *               Removes all the rows from a relation
  *
  * Exceptions:
- *                BadArg if name is invalid
+ *               BadArg if name is invalid
  *
  * Note:
- *                Rows are removed, indices are truncated and reconstructed.
+ *               Rows are removed, indices are truncated and reconstructed.
  */
 void
 TruncateRelation(char *name)
@@ -284,6 +287,7 @@ MergeAttributes(List *schema, List *supers, List **supconstr)
 
        foreach(rest, lnext(entry))
        {
+
            /*
             * check for duplicated names within the new relation
             */
@@ -352,11 +356,12 @@ MergeAttributes(List *schema, List *supers, List **supconstr)
             * check validity
             *
             */
-            if (checkAttrExists(attributeName, attributeType, schema))
-                elog(ERROR, "CREATE TABLE: attribute \"%s\" already exists in inherited schema",
-                     attributeName);
+           if (checkAttrExists(attributeName, attributeType, schema))
+               elog(ERROR, "CREATE TABLE: attribute \"%s\" already exists in inherited schema",
+                    attributeName);
 
            if (checkAttrExists(attributeName, attributeType, inhSchema))
+
                /*
                 * this entry already exists
                 */
@@ -499,7 +504,7 @@ StoreCatalogInheritance(Oid relationId, List *supers)
        if (RelationGetForm(relation)->relhasindex)
        {
            Relation    idescs[Num_pg_inherits_indices];
-   
+
            CatalogOpenIndices(Num_pg_inherits_indices, Name_pg_inherits_indices, idescs);
            CatalogIndexInsert(idescs, Num_pg_inherits_indices, relation, tuple);
            CatalogCloseIndices(Num_pg_inherits_indices, idescs);
@@ -642,8 +647,9 @@ checkAttrExists(const char *attributeName, const char *attributeType, List *sche
    {
        ColumnDef  *def = lfirst(s);
 
-       if (strcmp(attributeName, def->colname)==0)
+       if (strcmp(attributeName, def->colname) == 0)
        {
+
            /*
             * attribute exists. Make sure the types are the same.
             */
index d4e88ec2dde4d237b3fc03fa07c0d7c57793b668..d09973f5402f09f909e948df3793824b14a982d4 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/dbcommands.c,v 1.52 2000/03/26 18:32:28 petere Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/dbcommands.c,v 1.53 2000/04/12 17:14:58 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -33,9 +33,9 @@
 #include "catalog/pg_shadow.h"
 #include "commands/comment.h"
 #include "miscadmin.h"
-#include "storage/bufmgr.h"        /* for DropBuffers */
-#include "storage/fd.h"            /* for closeAllVfds */
-#include "storage/sinval.h"        /* for DatabaseHasActiveBackends */
+#include "storage/bufmgr.h"        /* for DropBuffers */
+#include "storage/fd.h"            /* for closeAllVfds */
+#include "storage/sinval.h"        /* for DatabaseHasActiveBackends */
 #include "utils/builtins.h"
 #include "utils/elog.h"
 #include "utils/palloc.h"
 
 /* non-export function prototypes */
 static bool
-get_user_info(const char *name, int4 *use_sysid, bool *use_super, bool *use_createdb);
+           get_user_info(const char *name, int4 *use_sysid, bool *use_super, bool *use_createdb);
 
 static bool
-get_db_info(const char *name, char *dbpath, Oid *dbIdP, int4 *ownerIdP);
+           get_db_info(const char *name, char *dbpath, Oid *dbIdP, int4 *ownerIdP);
 
 
 
@@ -61,99 +61,104 @@ createdb(const char *dbname, const char *dbpath, int encoding)
 {
    char        buf[2 * MAXPGPATH + 100];
    char       *loc;
-    char        locbuf[512];
+   char        locbuf[512];
    int4        user_id;
-    bool        use_super, use_createdb;
+   bool        use_super,
+               use_createdb;
    Relation    pg_database_rel;
    HeapTuple   tuple;
-    TupleDesc   pg_database_dsc;
-    Datum       new_record[Natts_pg_database];
-    char        new_record_nulls[Natts_pg_database] = { ' ', ' ', ' ', ' ' };
+   TupleDesc   pg_database_dsc;
+   Datum       new_record[Natts_pg_database];
+   char        new_record_nulls[Natts_pg_database] = {' ', ' ', ' ', ' '};
 
-    if (!get_user_info(GetPgUserName(), &user_id, &use_super, &use_createdb))
-        elog(ERROR, "current user name is invalid");
+   if (!get_user_info(GetPgUserName(), &user_id, &use_super, &use_createdb))
+       elog(ERROR, "current user name is invalid");
 
-    if (!use_createdb && !use_super)
-        elog(ERROR, "CREATE DATABASE: permission denied");
+   if (!use_createdb && !use_super)
+       elog(ERROR, "CREATE DATABASE: permission denied");
 
-    if (get_db_info(dbname, NULL, NULL, NULL))
-        elog(ERROR, "CREATE DATABASE: database \"%s\" already exists", dbname);
+   if (get_db_info(dbname, NULL, NULL, NULL))
+       elog(ERROR, "CREATE DATABASE: database \"%s\" already exists", dbname);
 
-    /* don't call this in a transaction block */
+   /* don't call this in a transaction block */
    if (IsTransactionBlock())
-        elog(ERROR, "CREATE DATABASE: may not be called in a transaction block");
+       elog(ERROR, "CREATE DATABASE: may not be called in a transaction block");
 
    /* Generate directory name for the new database */
-    if (dbpath == NULL || strcmp(dbpath, dbname)==0)
-        strcpy(locbuf, dbname);
-    else
-        snprintf(locbuf, sizeof(locbuf), "%s/%s", dbpath, dbname);
+   if (dbpath == NULL || strcmp(dbpath, dbname) == 0)
+       strcpy(locbuf, dbname);
+   else
+       snprintf(locbuf, sizeof(locbuf), "%s/%s", dbpath, dbname);
 
-    loc = ExpandDatabasePath(locbuf);
+   loc = ExpandDatabasePath(locbuf);
 
    if (loc == NULL)
        elog(ERROR,
-             "The database path '%s' is invalid. "
+            "The database path '%s' is invalid. "
             "This may be due to a character that is not allowed or because the chosen "
-             "path isn't permitted for databases", dbpath);
+            "path isn't permitted for databases", dbpath);
 
-   /* close virtual file descriptors so the kernel has more available for
-       the system() calls */
+   /*
+    * close virtual file descriptors so the kernel has more available for
+    * the system() calls
+    */
    closeAllVfds();
 
-    /*
-     * Insert a new tuple into pg_database
-     */
+   /*
+    * Insert a new tuple into pg_database
+    */
    pg_database_rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
    pg_database_dsc = RelationGetDescr(pg_database_rel);
 
-    /* Form tuple */
-    new_record[Anum_pg_database_datname-1] = NameGetDatum(namein(dbname));
-    new_record[Anum_pg_database_datdba-1] = Int32GetDatum(user_id);
-    new_record[Anum_pg_database_encoding-1] = Int32GetDatum(encoding);
-    new_record[Anum_pg_database_datpath-1] = PointerGetDatum(textin(locbuf));
+   /* Form tuple */
+   new_record[Anum_pg_database_datname - 1] = NameGetDatum(namein(dbname));
+   new_record[Anum_pg_database_datdba - 1] = Int32GetDatum(user_id);
+   new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
+   new_record[Anum_pg_database_datpath - 1] = PointerGetDatum(textin(locbuf));
 
-    tuple = heap_formtuple(pg_database_dsc, new_record, new_record_nulls);
+   tuple = heap_formtuple(pg_database_dsc, new_record, new_record_nulls);
 
-    /*
-     * Update table
-     */
-    heap_insert(pg_database_rel, tuple);
+   /*
+    * Update table
+    */
+   heap_insert(pg_database_rel, tuple);
 
-    /*
-     * Update indexes (there aren't any currently)
-     */
+   /*
+    * Update indexes (there aren't any currently)
+    */
 #ifdef Num_pg_database_indices
-    if (RelationGetForm(pg_database_rel)->relhasindex) {
-        Relation idescs[Num_pg_database_indices];
-      
-        CatalogOpenIndices(Num_pg_database_indices, 
-                           Name_pg_database_indices, idescs);
-        CatalogIndexInsert(idescs, Num_pg_database_indices, pg_database_rel, 
-                           tuple);
-        CatalogCloseIndices(Num_pg_database_indices, idescs);
-    }
+   if (RelationGetForm(pg_database_rel)->relhasindex)
+   {
+       Relation    idescs[Num_pg_database_indices];
+
+       CatalogOpenIndices(Num_pg_database_indices,
+                          Name_pg_database_indices, idescs);
+       CatalogIndexInsert(idescs, Num_pg_database_indices, pg_database_rel,
+                          tuple);
+       CatalogCloseIndices(Num_pg_database_indices, idescs);
+   }
 #endif
 
    heap_close(pg_database_rel, NoLock);
 
-    /* Copy the template database to the new location */
+   /* Copy the template database to the new location */
 
-   if (mkdir(loc, S_IRWXU) != 0) {
+   if (mkdir(loc, S_IRWXU) != 0)
        elog(ERROR, "CREATE DATABASE: unable to create database directory '%s': %s", loc, strerror(errno));
-    }
 
    snprintf(buf, sizeof(buf), "cp %s%cbase%ctemplate1%c* '%s'",
             DataDir, SEP_CHAR, SEP_CHAR, SEP_CHAR, loc);
-   if (system(buf) != 0) {
-        int ret;
-        snprintf(buf, sizeof(buf), "rm -rf '%s'", loc);
-        ret = system(buf);
-        if (ret == 0)
-            elog(ERROR, "CREATE DATABASE: could not initialize database directory");
-        else
-            elog(ERROR, "CREATE DATABASE: Could not initialize database directory. Delete failed as well");
-    }
+   if (system(buf) != 0)
+   {
+       int         ret;
+
+       snprintf(buf, sizeof(buf), "rm -rf '%s'", loc);
+       ret = system(buf);
+       if (ret == 0)
+           elog(ERROR, "CREATE DATABASE: could not initialize database directory");
+       else
+           elog(ERROR, "CREATE DATABASE: Could not initialize database directory. Delete failed as well");
+   }
 }
 
 
@@ -165,18 +170,19 @@ createdb(const char *dbname, const char *dbpath, int encoding)
 void
 dropdb(const char *dbname)
 {
-   int4        user_id, db_owner;
-    bool        use_super;
+   int4        user_id,
+               db_owner;
+   bool        use_super;
    Oid         db_id;
    char       *path,
                dbpath[MAXPGPATH],
                buf[MAXPGPATH + 100];
    Relation    pgdbrel;
    HeapScanDesc pgdbscan;
-   ScanKeyData key;
+   ScanKeyData key;
    HeapTuple   tup;
 
-    AssertArg(dbname);
+   AssertArg(dbname);
 
    if (strcmp(dbname, "template1") == 0)
        elog(ERROR, "DROP DATABASE: May not be executed on the template1 database");
@@ -185,46 +191,49 @@ dropdb(const char *dbname)
        elog(ERROR, "DROP DATABASE: Cannot be executed on the currently open database");
 
    if (IsTransactionBlock())
-        elog(ERROR, "DROP DATABASE: May not be called in a transaction block");
+       elog(ERROR, "DROP DATABASE: May not be called in a transaction block");
 
-    if (!get_user_info(GetPgUserName(), &user_id, &use_super, NULL))
-        elog(ERROR, "Current user name is invalid");
+   if (!get_user_info(GetPgUserName(), &user_id, &use_super, NULL))
+       elog(ERROR, "Current user name is invalid");
 
-    if (!get_db_info(dbname, dbpath, &db_id, &db_owner))
-        elog(ERROR, "DROP DATABASE: Database \"%s\" does not exist", dbname);
+   if (!get_db_info(dbname, dbpath, &db_id, &db_owner))
+       elog(ERROR, "DROP DATABASE: Database \"%s\" does not exist", dbname);
 
-    if (user_id != db_owner && !use_super)
-        elog(ERROR, "DROP DATABASE: Permission denied");
+   if (user_id != db_owner && !use_super)
+       elog(ERROR, "DROP DATABASE: Permission denied");
 
    path = ExpandDatabasePath(dbpath);
    if (path == NULL)
        elog(ERROR,
-             "The database path '%s' is invalid. "
+            "The database path '%s' is invalid. "
             "This may be due to a character that is not allowed or because the chosen "
-             "path isn't permitted for databases", path);
+            "path isn't permitted for databases", path);
 
-   /* close virtual file descriptors so the kernel has more available for
-       the system() calls */
+   /*
+    * close virtual file descriptors so the kernel has more available for
+    * the system() calls
+    */
    closeAllVfds();
 
    /*
-    * Obtain exclusive lock on pg_database.  We need this to ensure
-    * that no new backend starts up in the target database while we
-    * are deleting it.  (Actually, a new backend might still manage to
-    * start up, because it will read pg_database without any locking
-    * to discover the database's OID.  But it will detect its error
-    * in ReverifyMyDatabase and shut down before any serious damage
-    * is done.  See postinit.c.)
+    * Obtain exclusive lock on pg_database.  We need this to ensure that
+    * no new backend starts up in the target database while we are
+    * deleting it.  (Actually, a new backend might still manage to start
+    * up, because it will read pg_database without any locking to
+    * discover the database's OID.  But it will detect its error in
+    * ReverifyMyDatabase and shut down before any serious damage is done.
+    * See postinit.c.)
     */
    pgdbrel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
 
    /*
     * Check for active backends in the target database.
     */
-   if (DatabaseHasActiveBackends(db_id)) {
+   if (DatabaseHasActiveBackends(db_id))
+   {
        heap_close(pgdbrel, AccessExclusiveLock);
        elog(ERROR, "DROP DATABASE: Database \"%s\" is being accessed by other users", dbname);
-    }
+   }
 
    /*
     * Find the database's tuple by OID (should be unique, we trust).
@@ -238,8 +247,11 @@ dropdb(const char *dbname)
    if (!HeapTupleIsValid(tup))
    {
        heap_close(pgdbrel, AccessExclusiveLock);
-        /* This error should never come up since the existence of the
-           database is checked earlier */
+
+       /*
+        * This error should never come up since the existence of the
+        * database is checked earlier
+        */
        elog(ERROR, "DROP DATABASE: Database \"%s\" doesn't exist despite earlier reports to the contrary",
             dbname);
    }
@@ -270,7 +282,7 @@ dropdb(const char *dbname)
     */
    snprintf(buf, sizeof(buf), "rm -rf '%s'", path);
    if (system(buf) != 0)
-        elog(NOTICE, "DROP DATABASE: The database directory '%s' could not be removed", path);
+       elog(NOTICE, "DROP DATABASE: The database directory '%s' could not be removed", path);
 }
 
 
@@ -285,11 +297,11 @@ get_db_info(const char *name, char *dbpath, Oid *dbIdP, int4 *ownerIdP)
    Relation    relation;
    HeapTuple   tuple;
    ScanKeyData scanKey;
-    HeapScanDesc scan;
+   HeapScanDesc scan;
 
-    AssertArg(name);
+   AssertArg(name);
 
-   relation = heap_openr(DatabaseRelationName, AccessExclusiveLock/*???*/);
+   relation = heap_openr(DatabaseRelationName, AccessExclusiveLock /* ??? */ );
 
    ScanKeyEntryInitialize(&scanKey, 0, Anum_pg_database_datname,
                           F_NAMEEQ, NameGetDatum(name));
@@ -302,76 +314,76 @@ get_db_info(const char *name, char *dbpath, Oid *dbIdP, int4 *ownerIdP)
 
    if (HeapTupleIsValid(tuple))
    {
-        text      *tmptext;
-        bool        isnull;
-    
-        /* oid of the database */
-        if (dbIdP)
-            *dbIdP = tuple->t_data->t_oid;
-        /* uid of the owner */
-        if (ownerIdP)
-        {
-            *ownerIdP = (int4) heap_getattr(tuple,
-                                            Anum_pg_database_datdba,
-                                            RelationGetDescr(relation),
-                                            &isnull);
-            if (isnull)
-                *ownerIdP = -1; /* hopefully no one has that id already ;) */
-        }
-        /* database path (as registered in pg_database) */
-        if (dbpath)
-        {
-            tmptext = (text *) heap_getattr(tuple,
-                                            Anum_pg_database_datpath,
-                                            RelationGetDescr(relation),
-                                            &isnull);
-
-            if (!isnull)
-            {
-                Assert(VARSIZE(tmptext) - VARHDRSZ < MAXPGPATH);
-
-                strncpy(dbpath, VARDATA(tmptext), VARSIZE(tmptext) - VARHDRSZ);
-                *(dbpath + VARSIZE(tmptext) - VARHDRSZ) = '\0';
-            }
-            else
-                strcpy(dbpath, "");
-        }
+       text       *tmptext;
+       bool        isnull;
+
+       /* oid of the database */
+       if (dbIdP)
+           *dbIdP = tuple->t_data->t_oid;
+       /* uid of the owner */
+       if (ownerIdP)
+       {
+           *ownerIdP = (int4) heap_getattr(tuple,
+                                           Anum_pg_database_datdba,
+                                           RelationGetDescr(relation),
+                                           &isnull);
+           if (isnull)
+               *ownerIdP = -1; /* hopefully no one has that id already ;) */
+       }
+       /* database path (as registered in pg_database) */
+       if (dbpath)
+       {
+           tmptext = (text *) heap_getattr(tuple,
+                                           Anum_pg_database_datpath,
+                                           RelationGetDescr(relation),
+                                           &isnull);
+
+           if (!isnull)
+           {
+               Assert(VARSIZE(tmptext) - VARHDRSZ < MAXPGPATH);
+
+               strncpy(dbpath, VARDATA(tmptext), VARSIZE(tmptext) - VARHDRSZ);
+               *(dbpath + VARSIZE(tmptext) - VARHDRSZ) = '\0';
+           }
+           else
+               strcpy(dbpath, "");
+       }
    }
    else
-    {
-        if (dbIdP)
-            *dbIdP = InvalidOid;
-    }
+   {
+       if (dbIdP)
+           *dbIdP = InvalidOid;
+   }
 
    heap_endscan(scan);
 
    /* We will keep the lock on the relation until end of transaction. */
    heap_close(relation, NoLock);
 
-    return HeapTupleIsValid(tuple);
+   return HeapTupleIsValid(tuple);
 }
 
 
 
 static bool
-get_user_info(const char * name, int4 *use_sysid, bool *use_super, bool *use_createdb)
+get_user_info(const char *name, int4 *use_sysid, bool *use_super, bool *use_createdb)
 {
-    HeapTuple   utup;
+   HeapTuple   utup;
 
    AssertArg(name);
    utup = SearchSysCacheTuple(SHADOWNAME,
                               PointerGetDatum(name),
                               0, 0, 0);
 
-    if (!HeapTupleIsValid(utup))
-        return false;
+   if (!HeapTupleIsValid(utup))
+       return false;
 
-    if (use_sysid)
-        *use_sysid =    ((Form_pg_shadow) GETSTRUCT(utup))->usesysid;
-    if (use_super)
-        *use_super =    ((Form_pg_shadow) GETSTRUCT(utup))->usesuper;
-    if (use_createdb)
-        *use_createdb = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
+   if (use_sysid)
+       *use_sysid = ((Form_pg_shadow) GETSTRUCT(utup))->usesysid;
+   if (use_super)
+       *use_super = ((Form_pg_shadow) GETSTRUCT(utup))->usesuper;
+   if (use_createdb)
+       *use_createdb = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
 
-    return true;
+   return true;
 }
index 2090076f2e410812f4a7238f56d973801407b06f..c77b467089b3619edcb158e3a08140c6bdd9bb59 100644 (file)
@@ -10,7 +10,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.39 2000/04/07 13:39:24 thomas Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.40 2000/04/12 17:14:58 momjian Exp $
  *
  * DESCRIPTION
  *   The "DefineFoo" routines take the parse tree and pick out the
@@ -137,12 +137,13 @@ compute_full_attributes(List *parameters, int32 *byte_pct_p,
 
    foreach(pl, parameters)
    {
-       DefElem *param = (DefElem *) lfirst(pl);
+       DefElem    *param = (DefElem *) lfirst(pl);
 
        if (strcasecmp(param->defname, "iscachable") == 0)
            *canCache_p = true;
        else if (strcasecmp(param->defname, "trusted") == 0)
        {
+
            /*
             * we don't have untrusted functions any more. The 4.2
             * implementation is lousy anyway so I took it out. -ay 10/94
@@ -233,12 +234,14 @@ CreateFunction(ProcedureStmt *stmt, CommandDest dest)
     */
 
    bool        returnsSet;
+
    /* The function returns a set of values, as opposed to a singleton. */
 
    bool        lanisPL = false;
 
    /*
-    * The following are optional user-supplied attributes of the function.
+    * The following are optional user-supplied attributes of the
+    * function.
     */
    int32       byte_pct,
                perbyte_cpu,
@@ -256,7 +259,7 @@ CreateFunction(ProcedureStmt *stmt, CommandDest dest)
            elog(ERROR,
                 "Only users with Postgres superuser privilege are "
                 "permitted to create a function "
-                "in the '%s' language.  Others may use the 'sql' language "
+             "in the '%s' language.  Others may use the 'sql' language "
                 "or the created procedural languages.",
                 languageName);
    }
@@ -316,17 +319,17 @@ CreateFunction(ProcedureStmt *stmt, CommandDest dest)
    interpret_AS_clause(languageName, stmt->as, &prosrc_str, &probin_str);
 
    /*
-    * And now that we have all the parameters, and know we're
-    * permitted to do so, go ahead and create the function.
+    * And now that we have all the parameters, and know we're permitted
+    * to do so, go ahead and create the function.
     */
    ProcedureCreate(stmt->funcname,
                    returnsSet,
                    prorettype,
                    languageName,
-                   prosrc_str,     /* converted to text later */
-                   probin_str,     /* converted to text later */
+                   prosrc_str, /* converted to text later */
+                   probin_str, /* converted to text later */
                    canCache,
-                   true,           /* (obsolete "trusted") */
+                   true,       /* (obsolete "trusted") */
                    byte_pct,
                    perbyte_cpu,
                    percall_cpu,
@@ -378,7 +381,7 @@ DefineOperator(char *oprName,
        if (!strcasecmp(defel->defname, "leftarg"))
        {
            if ((nodeTag(defel->arg) == T_TypeName)
-               && (((TypeName *)defel->arg)->setof))
+               && (((TypeName *) defel->arg)->setof))
                elog(ERROR, "setof type not implemented for leftarg");
 
            typeName1 = defGetString(defel);
@@ -388,7 +391,7 @@ DefineOperator(char *oprName,
        else if (!strcasecmp(defel->defname, "rightarg"))
        {
            if ((nodeTag(defel->arg) == T_TypeName)
-               && (((TypeName *)defel->arg)->setof))
+               && (((TypeName *) defel->arg)->setof))
                elog(ERROR, "setof type not implemented for rightarg");
 
            typeName2 = defGetString(defel);
@@ -698,16 +701,16 @@ DefineType(char *typeName, List *parameters)
 static char *
 defGetString(DefElem *def)
 {
-   char *string;
+   char       *string;
 
    if (nodeTag(def->arg) == T_String)
        string = strVal(def->arg);
    else if (nodeTag(def->arg) == T_TypeName)
-       string = ((TypeName *)def->arg)->name;
+       string = ((TypeName *) def->arg)->name;
    else
        string = NULL;
 #if 0
-       elog(ERROR, "Define: \"%s\" = what?", def->defname);
+   elog(ERROR, "Define: \"%s\" = what?", def->defname);
 #endif
 
    return string;
index 64dc164a0d590446b2c99eb170422691f163fd07..d51053c20a17724169acfccb5c07b1d0b0316ab8 100644 (file)
@@ -5,7 +5,7 @@
  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
  * Portions Copyright (c) 1994-5, Regents of the University of California
  *
- * $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.55 2000/03/14 23:06:12 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.56 2000/04/12 17:14:58 momjian Exp $
  *
  */
 
@@ -209,7 +209,7 @@ explain_outNode(StringInfo str, Plan *plan, int indent, ExplainState *es)
    switch (nodeTag(plan))
    {
        case T_IndexScan:
-           if (ScanDirectionIsBackward(((IndexScan *)plan)->indxorderdir))
+           if (ScanDirectionIsBackward(((IndexScan *) plan)->indxorderdir))
                appendStringInfo(str, " Backward");
            appendStringInfo(str, " using ");
            i = 0;
@@ -219,7 +219,7 @@ explain_outNode(StringInfo str, Plan *plan, int indent, ExplainState *es)
                Assert(relation);
                appendStringInfo(str, "%s%s",
                                 (++i > 1) ? ", " : "",
-                                stringStringInfo(RelationGetRelationName(relation)));
+                   stringStringInfo(RelationGetRelationName(relation)));
                /* drop relcache refcount from RelationIdGetRelation */
                RelationDecrementReferenceCount(relation);
            }
@@ -238,17 +238,17 @@ explain_outNode(StringInfo str, Plan *plan, int indent, ExplainState *es)
                        || (length(rte->ref->attrs) > 0))
                    {
                        appendStringInfo(str, " %s",
-                                        stringStringInfo(rte->ref->relname));
+                                   stringStringInfo(rte->ref->relname));
 
                        if (length(rte->ref->attrs) > 0)
                        {
-                           List *c;
-                           int firstEntry = true;
+                           List       *c;
+                           int         firstEntry = true;
 
                            appendStringInfo(str, " (");
-                           foreach (c, rte->ref->attrs)
+                           foreach(c, rte->ref->attrs)
                            {
-                               if (! firstEntry)
+                               if (!firstEntry)
                                {
                                    appendStringInfo(str, ", ");
                                    firstEntry = false;
index 93ad0eb63b47fdd601112ab075a1617ec64c9ba5..2577e4741b1f9a2a69daaa32ba8b863d81392f87 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/indexcmds.c,v 1.22 2000/02/25 02:58:48 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/indexcmds.c,v 1.23 2000/04/12 17:14:58 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -34,9 +34,9 @@
 #include "parser/parse_func.h"
 #include "utils/builtins.h"
 #include "utils/syscache.h"
-#include "miscadmin.h" /* ReindexDatabase() */
-#include "utils/portal.h" /* ReindexDatabase() */
-#include "catalog/catalog.h" /* ReindexDatabase() */
+#include "miscadmin.h"         /* ReindexDatabase() */
+#include "utils/portal.h"      /* ReindexDatabase() */
+#include "catalog/catalog.h"   /* ReindexDatabase() */
 
 #define IsFuncIndex(ATTR_LIST) (((IndexElem*)lfirst(ATTR_LIST))->args != NIL)
 
@@ -45,11 +45,11 @@ static void CheckPredicate(List *predList, List *rangeTable, Oid baseRelOid);
 static void CheckPredExpr(Node *predicate, List *rangeTable, Oid baseRelOid);
 static void CheckPredClause(Expr *predicate, List *rangeTable, Oid baseRelOid);
 static void FuncIndexArgs(IndexElem *funcIndex, FuncIndexInfo *funcInfo,
-                         AttrNumber *attNumP, Oid *opOidP, Oid relId);
+             AttrNumber *attNumP, Oid *opOidP, Oid relId);
 static void NormIndexAttrs(List *attList, AttrNumber *attNumP,
-                          Oid *opOidP, Oid relId);
+              Oid *opOidP, Oid relId);
 static void ProcessAttrTypename(IndexElem *attribute,
-                               Oid defType, int32 defTypmod);
+                   Oid defType, int32 defTypmod);
 static Oid GetAttrOpClass(IndexElem *attribute, Oid attrType);
 static char *GetDefaultOpClass(Oid atttypid);
 
@@ -133,7 +133,7 @@ DefineIndex(char *heapRelationName,
     */
    foreach(pl, parameterList)
    {
-       DefElem *param = (DefElem *) lfirst(pl);
+       DefElem    *param = (DefElem *) lfirst(pl);
 
        if (!strcasecmp(param->defname, "islossy"))
            lossy = TRUE;
@@ -174,7 +174,7 @@ DefineIndex(char *heapRelationName,
        namestrcpy(&fInfo.funcName, funcIndex->name);
 
        attributeNumberA = (AttrNumber *) palloc(nargs *
-                                                sizeof attributeNumberA[0]);
+                                            sizeof attributeNumberA[0]);
 
        classObjectId = (Oid *) palloc(sizeof(Oid));
 
@@ -192,7 +192,7 @@ DefineIndex(char *heapRelationName,
    else
    {
        attributeNumberA = (AttrNumber *) palloc(numberOfAttributes *
-                                                sizeof attributeNumberA[0]);
+                                            sizeof attributeNumberA[0]);
 
        classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
 
@@ -490,7 +490,7 @@ NormIndexAttrs(List *attList,   /* list of IndexElem's */
 
        atttuple = SearchSysCacheTupleCopy(ATTNAME,
                                           ObjectIdGetDatum(relId),
-                                          PointerGetDatum(attribute->name),
+                                       PointerGetDatum(attribute->name),
                                           0, 0);
        if (!HeapTupleIsValid(atttuple))
            elog(ERROR, "DefineIndex: attribute \"%s\" not found",
@@ -608,7 +608,7 @@ RemoveIndex(char *name)
  *     ...
  */
 void
-ReindexIndex(const char *name, bool force /* currently unused */)
+ReindexIndex(const char *name, bool force /* currently unused */ )
 {
    HeapTuple   tuple;
 
@@ -667,28 +667,35 @@ ReindexTable(const char *name, bool force)
  *     "ERROR" if table nonexistent.
  *     ...
  */
-extern Oid MyDatabaseId;
+extern Oid MyDatabaseId;
 void
 ReindexDatabase(const char *dbname, bool force, bool all)
 {
-   Relation    relation, relationRelation;
-   HeapTuple   usertuple, dbtuple, tuple;
-   HeapScanDesc    scan;
-   int4        user_id, db_owner;
+   Relation    relation,
+               relationRelation;
+   HeapTuple   usertuple,
+               dbtuple,
+               tuple;
+   HeapScanDesc scan;
+   int4        user_id,
+               db_owner;
    bool        superuser;
-   Oid     db_id;
-   char        *username;
-   ScanKeyData scankey;
-   PortalVariableMemory    pmem;
-   MemoryContext   old;
-   int     relcnt, relalc, i, oncealc = 200;
-   Oid     *relids = (Oid *) NULL;
+   Oid         db_id;
+   char       *username;
+   ScanKeyData scankey;
+   PortalVariableMemory pmem;
+   MemoryContext old;
+   int         relcnt,
+               relalc,
+               i,
+               oncealc = 200;
+   Oid        *relids = (Oid *) NULL;
 
    AssertArg(dbname);
 
    username = GetPgUserName();
    usertuple = SearchSysCacheTuple(SHADOWNAME, PointerGetDatum(username),
-               0, 0, 0);
+                                   0, 0, 0);
    if (!HeapTupleIsValid(usertuple))
        elog(ERROR, "Current user '%s' is invalid.", username);
    user_id = ((Form_pg_shadow) GETSTRUCT(usertuple))->usesysid;
@@ -696,7 +703,7 @@ ReindexDatabase(const char *dbname, bool force, bool all)
 
    relation = heap_openr(DatabaseRelationName, AccessShareLock);
    ScanKeyEntryInitialize(&scankey, 0, Anum_pg_database_datname,
-           F_NAMEEQ, NameGetDatum(dbname));
+                          F_NAMEEQ, NameGetDatum(dbname));
    scan = heap_beginscan(relation, 0, SnapshotNow, 1, &scankey);
    dbtuple = heap_getnext(scan, 0);
    if (!HeapTupleIsValid(dbtuple))
index dfcad83c3a8f8850b6a27d23367f56025b833db0..45d1d310e78d6fd61642f06d9bec9b2eda99805c 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/remove.c,v 1.45 2000/01/26 05:56:13 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/remove.c,v 1.46 2000/04/12 17:14:59 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -156,14 +156,15 @@ SingleOpOperatorRemove(Oid typeOid)
    {
        key[0].sk_attno = attnums[i];
        scan = heap_beginscan(rel, 0, SnapshotNow, 1, key);
-       while (HeapTupleIsValid(tup = heap_getnext(scan, 0))) {
+       while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
+       {
 
-         /*** This is apparently a routine not in use, but remove ***/
-         /*** any comments anyways ***/
+           /*** This is apparently a routine not in use, but remove ***/
+           /*** any comments anyways ***/
 
-         DeleteComments(tup->t_data->t_oid);
+           DeleteComments(tup->t_data->t_oid);
 
-         heap_delete(rel, &tup->t_self, NULL);
+           heap_delete(rel, &tup->t_self, NULL);
 
        }
 
index 454b2d0d93da4d151d353be16ea8396b0d596451..6a9c92b1e63ec752226ac0bf9c7882355ceb338c 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/rename.c,v 1.41 2000/01/26 05:56:13 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/Attic/rename.c,v 1.42 2000/04/12 17:14:59 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -76,12 +76,12 @@ renameatt(char *relname,
 #endif
 
    /*
-    * Grab an exclusive lock on the target table, which we will NOT release
-    * until end of transaction.
+    * Grab an exclusive lock on the target table, which we will NOT
+    * release until end of transaction.
     */
    targetrelation = heap_openr(relname, AccessExclusiveLock);
    relid = RelationGetRelid(targetrelation);
-   heap_close(targetrelation, NoLock); /* close rel but keep lock! */
+   heap_close(targetrelation, NoLock); /* close rel but keep lock! */
 
    /*
     * if the 'recurse' flag is set then we are supposed to rename this
@@ -160,11 +160,12 @@ renameatt(char *relname,
    /* keep system catalog indices current */
    {
        Relation    irelations[Num_pg_attr_indices];
+
        CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
        CatalogIndexInsert(irelations, Num_pg_attr_indices, attrelation, oldatttup);
        CatalogCloseIndices(Num_pg_attr_indices, irelations);
    }
-   
+
    heap_freetuple(oldatttup);
    heap_close(attrelation, RowExclusiveLock);
 }
@@ -194,8 +195,8 @@ renamerel(const char *oldrelname, const char *newrelname)
             newrelname);
 
    /*
-    * Grab an exclusive lock on the target table, which we will NOT release
-    * until end of transaction.
+    * Grab an exclusive lock on the target table, which we will NOT
+    * release until end of transaction.
     */
    targetrelation = heap_openr(oldrelname, AccessExclusiveLock);
 
@@ -211,14 +212,15 @@ renamerel(const char *oldrelname, const char *newrelname)
     *  they don't exist anyway.  So, no warning in that case.
     * ----------------
     */
-   if (IsTransactionBlock() && ! targetrelation->rd_myxactonly)
+   if (IsTransactionBlock() && !targetrelation->rd_myxactonly)
        elog(NOTICE, "Caution: RENAME TABLE cannot be rolled back, so don't abort now");
 
    /*
-    * Flush all blocks of the relation out of the buffer pool.  We need this
-    * because the blocks are marked with the relation's name as well as OID.
-    * If some backend tries to write a dirty buffer with mdblindwrt after
-    * we've renamed the physical file, we'll be in big trouble.
+    * Flush all blocks of the relation out of the buffer pool.  We need
+    * this because the blocks are marked with the relation's name as well
+    * as OID. If some backend tries to write a dirty buffer with
+    * mdblindwrt after we've renamed the physical file, we'll be in big
+    * trouble.
     *
     * Since we hold the exclusive lock on the relation, we don't have to
     * worry about more blocks being read in while we finish the rename.
@@ -227,8 +229,8 @@ renamerel(const char *oldrelname, const char *newrelname)
        elog(ERROR, "renamerel: unable to flush relation from buffer pool");
 
    /*
-    * Make sure smgr and lower levels close the relation's files.
-    * (Next access to rel will reopen them.)
+    * Make sure smgr and lower levels close the relation's files. (Next
+    * access to rel will reopen them.)
     *
     * Note: we rely on shared cache invalidation message to make other
     * backends close and re-open the files.
@@ -238,14 +240,15 @@ renamerel(const char *oldrelname, const char *newrelname)
    /*
     * Close rel, but keep exclusive lock!
     *
-    * Note: we don't do anything about updating the relcache entry;
-    * we assume it will be flushed by shared cache invalidate.
-    * XXX is this good enough?  What if relation is myxactonly?
+    * Note: we don't do anything about updating the relcache entry; we
+    * assume it will be flushed by shared cache invalidate. XXX is this
+    * good enough?  What if relation is myxactonly?
     */
    heap_close(targetrelation, NoLock);
 
    /*
-    * Find relation's pg_class tuple, and make sure newrelname isn't in use.
+    * Find relation's pg_class tuple, and make sure newrelname isn't in
+    * use.
     */
    relrelation = heap_openr(RelationRelationName, RowExclusiveLock);
 
@@ -262,8 +265,8 @@ renamerel(const char *oldrelname, const char *newrelname)
     * Perform physical rename of files.  If this fails, we haven't yet
     * done anything irreversible.
     *
-    * XXX smgr.c ought to provide an interface for this; doing it
-    * directly is bletcherous.
+    * XXX smgr.c ought to provide an interface for this; doing it directly
+    * is bletcherous.
     */
    strcpy(oldpath, relpath(oldrelname));
    strcpy(newpath, relpath(newrelname));
index 23280ec5673a21602003aef43c70efc6e8107abb..0667297d7636dbfe3f86c42f1217482693d82db1 100644 (file)
@@ -410,7 +410,9 @@ init_sequence(char *caller, char *name)
 
    if (elm != (SeqTable) NULL)
    {
-       /* We are using a seqtable entry left over from a previous xact;
+
+       /*
+        * We are using a seqtable entry left over from a previous xact;
         * must check for relid change.
         */
        elm->rel = seqrel;
@@ -424,7 +426,9 @@ init_sequence(char *caller, char *name)
    }
    else
    {
-       /* Time to make a new seqtable entry.  These entries live as long
+
+       /*
+        * Time to make a new seqtable entry.  These entries live as long
         * as the backend does, so we use plain malloc for them.
         */
        elm = (SeqTable) malloc(sizeof(SeqTableData));
index 78df4fd5e8ebdb7711817c1c5d6f0ad2a6687c09..9961ce6ff15085a4e99f32459e5dd1548e079e5f 100644 (file)
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/trigger.c,v 1.62 2000/02/29 12:28:24 wieck Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/trigger.c,v 1.63 2000/04/12 17:14:59 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -89,7 +89,7 @@ CreateTrigger(CreateTrigStmt *stmt)
            rel = heap_openr(stmt->constrrelname, NoLock);
            if (rel == NULL)
                elog(ERROR, "table \"%s\" does not exist",
-                           stmt->constrrelname);
+                    stmt->constrrelname);
            constrrelid = rel->rd_id;
            heap_close(rel, NoLock);
        }
@@ -182,12 +182,12 @@ CreateTrigger(CreateTrigStmt *stmt)
    values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(tuple->t_data->t_oid);
    values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype);
 
-   values[Anum_pg_trigger_tgenabled - 1]       = true;
-   values[Anum_pg_trigger_tgisconstraint - 1]  = stmt->isconstraint;
-   values[Anum_pg_trigger_tgconstrname - 1]    = PointerGetDatum(constrname);;
-   values[Anum_pg_trigger_tgconstrrelid - 1]   = constrrelid;
-   values[Anum_pg_trigger_tgdeferrable - 1]    = stmt->deferrable;
-   values[Anum_pg_trigger_tginitdeferred - 1]  = stmt->initdeferred;
+   values[Anum_pg_trigger_tgenabled - 1] = true;
+   values[Anum_pg_trigger_tgisconstraint - 1] = stmt->isconstraint;
+   values[Anum_pg_trigger_tgconstrname - 1] = PointerGetDatum(constrname);;
+   values[Anum_pg_trigger_tgconstrrelid - 1] = constrrelid;
+   values[Anum_pg_trigger_tgdeferrable - 1] = stmt->deferrable;
+   values[Anum_pg_trigger_tginitdeferred - 1] = stmt->initdeferred;
 
    if (stmt->args)
    {
@@ -261,10 +261,11 @@ CreateTrigger(CreateTrigStmt *stmt)
    CatalogCloseIndices(Num_pg_class_indices, ridescs);
    heap_freetuple(tuple);
    heap_close(pgrel, RowExclusiveLock);
+
    /*
     * We used to try to update the rel's relcache entry here, but that's
-    * fairly pointless since it will happen as a byproduct of the upcoming
-    * CommandCounterIncrement...
+    * fairly pointless since it will happen as a byproduct of the
+    * upcoming CommandCounterIncrement...
     */
    /* Keep lock on target rel until end of xact */
    heap_close(rel, NoLock);
@@ -301,12 +302,12 @@ DropTrigger(DropTrigStmt *stmt)
        if (namestrcmp(&(pg_trigger->tgname), stmt->trigname) == 0)
        {
 
-         /*** Delete any comments associated with this trigger ***/
+           /*** Delete any comments associated with this trigger ***/
 
-         DeleteComments(tuple->t_data->t_oid);
+           DeleteComments(tuple->t_data->t_oid);
 
-         heap_delete(tgrel, &tuple->t_self, NULL);
-         tgfound++;
+           heap_delete(tgrel, &tuple->t_self, NULL);
+           tgfound++;
 
        }
        else
@@ -337,10 +338,11 @@ DropTrigger(DropTrigStmt *stmt)
    CatalogCloseIndices(Num_pg_class_indices, ridescs);
    heap_freetuple(tuple);
    heap_close(pgrel, RowExclusiveLock);
+
    /*
     * We used to try to update the rel's relcache entry here, but that's
-    * fairly pointless since it will happen as a byproduct of the upcoming
-    * CommandCounterIncrement...
+    * fairly pointless since it will happen as a byproduct of the
+    * upcoming CommandCounterIncrement...
     */
    /* Keep lock on target rel until end of xact */
    heap_close(rel, NoLock);
@@ -360,13 +362,14 @@ RelationRemoveTriggers(Relation rel)
 
    tgscan = heap_beginscan(tgrel, 0, SnapshotNow, 1, &key);
 
-   while (HeapTupleIsValid(tup = heap_getnext(tgscan, 0))) {
+   while (HeapTupleIsValid(tup = heap_getnext(tgscan, 0)))
+   {
 
-     /*** Delete any comments associated with this trigger ***/
+       /*** Delete any comments associated with this trigger ***/
 
-     DeleteComments(tup->t_data->t_oid);
+       DeleteComments(tup->t_data->t_oid);
 
-     heap_delete(tgrel, &tup->t_self, NULL);
+       heap_delete(tgrel, &tup->t_self, NULL);
 
    }
 
@@ -385,14 +388,14 @@ RelationRemoveTriggers(Relation rel)
     * ----------
     */
    ScanKeyEntryInitialize(&key, 0, Anum_pg_trigger_tgconstrrelid,
-                           F_OIDEQ, RelationGetRelid(rel));
+                          F_OIDEQ, RelationGetRelid(rel));
 
    tgscan = heap_beginscan(tgrel, 0, SnapshotNow, 1, &key);
    while (HeapTupleIsValid(tup = heap_getnext(tgscan, 0)))
    {
-       Form_pg_trigger pg_trigger;
-       Relation        refrel;
-       DropTrigStmt    stmt;
+       Form_pg_trigger pg_trigger;
+       Relation    refrel;
+       DropTrigStmt stmt;
 
        pg_trigger = (Form_pg_trigger) GETSTRUCT(tup);
 
@@ -436,8 +439,8 @@ RelationBuildTriggers(Relation relation)
    Relation    irel = (Relation) NULL;
    ScanKeyData skey;
    HeapTupleData tuple;
-   IndexScanDesc   sd = (IndexScanDesc) NULL;
-   HeapScanDesc    tgscan = (HeapScanDesc) NULL;
+   IndexScanDesc sd = (IndexScanDesc) NULL;
+   HeapScanDesc tgscan = (HeapScanDesc) NULL;
    HeapTuple   htup;
    RetrieveIndexResult indexRes;
    Buffer      buffer;
@@ -684,13 +687,13 @@ FreeTriggerDesc(TriggerDesc *trigdesc)
 bool
 equalTriggerDescs(TriggerDesc *trigdesc1, TriggerDesc *trigdesc2)
 {
-   int     i,
-           j;
+   int         i,
+               j;
 
    /*
-    * We need not examine the "index" data, just the trigger array itself;
-    * if we have the same triggers with the same types, the derived index
-    * data should match.
+    * We need not examine the "index" data, just the trigger array
+    * itself; if we have the same triggers with the same types, the
+    * derived index data should match.
     *
     * XXX It seems possible that the same triggers could appear in different
     * orders in the two trigger arrays; do we need to handle that?
@@ -703,8 +706,8 @@ equalTriggerDescs(TriggerDesc *trigdesc1, TriggerDesc *trigdesc2)
            return false;
        for (i = 0; i < trigdesc1->numtriggers; i++)
        {
-           Trigger    *trig1 = trigdesc1->triggers + i;
-           Trigger    *trig2 = NULL;
+           Trigger    *trig1 = trigdesc1->triggers + i;
+           Trigger    *trig2 = NULL;
 
            /*
             * We can't assume that the triggers are always read from
@@ -1014,31 +1017,31 @@ ltrmark:;
  * end.
  * ----------
  */
-static GlobalMemory        deftrig_gcxt = NULL;
-static GlobalMemory        deftrig_cxt = NULL;
+static GlobalMemory deftrig_gcxt = NULL;
+static GlobalMemory deftrig_cxt = NULL;
 
 /* ----------
  * Global data that tells which triggers are actually in
  * state IMMEDIATE or DEFERRED.
  * ----------
  */
-static bool                deftrig_dfl_all_isset = false;
-static bool                deftrig_dfl_all_isdeferred = false;
-static List               *deftrig_dfl_trigstates = NIL;
+static bool deftrig_dfl_all_isset = false;
+static bool deftrig_dfl_all_isdeferred = false;
+static List *deftrig_dfl_trigstates = NIL;
 
-static bool                deftrig_all_isset;
-static bool                deftrig_all_isdeferred;
-static List               *deftrig_trigstates;
+static bool deftrig_all_isset;
+static bool deftrig_all_isdeferred;
+static List *deftrig_trigstates;
 
 /* ----------
  * The list of events during the entire transaction.
  *
  * XXX This must finally be held in a file because of the huge
- *     number of events that could occur in the real world.
+ *    number of events that could occur in the real world.
  * ----------
  */
-static int             deftrig_n_events;
-static List               *deftrig_events;
+static int deftrig_n_events;
+static List *deftrig_events;
 
 
 /* ----------
@@ -1051,9 +1054,9 @@ static List              *deftrig_events;
 static bool
 deferredTriggerCheckState(Oid tgoid, int32 itemstate)
 {
-   MemoryContext           oldcxt;
-   List                   *sl;
-   DeferredTriggerStatus   trigstate;
+   MemoryContext oldcxt;
+   List       *sl;
+   DeferredTriggerStatus trigstate;
 
    /* ----------
     * Not deferrable triggers (i.e. normal AFTER ROW triggers
@@ -1068,7 +1071,7 @@ deferredTriggerCheckState(Oid tgoid, int32 itemstate)
     * Lookup if we know an individual state for this trigger
     * ----------
     */
-   foreach (sl, deftrig_trigstates)
+   foreach(sl, deftrig_trigstates)
    {
        trigstate = (DeferredTriggerStatus) lfirst(sl);
        if (trigstate->dts_tgoid == tgoid)
@@ -1092,10 +1095,10 @@ deferredTriggerCheckState(Oid tgoid, int32 itemstate)
    oldcxt = MemoryContextSwitchTo((MemoryContext) deftrig_cxt);
 
    trigstate = (DeferredTriggerStatus)
-           palloc(sizeof(DeferredTriggerStatusData));
-   trigstate->dts_tgoid        = tgoid;
-   trigstate->dts_tgisdeferred =
-           ((itemstate & TRIGGER_DEFERRED_INITDEFERRED) != 0);
+       palloc(sizeof(DeferredTriggerStatusData));
+   trigstate->dts_tgoid = tgoid;
+   trigstate->dts_tgisdeferred =
+       ((itemstate & TRIGGER_DEFERRED_INITDEFERRED) != 0);
    deftrig_trigstates = lappend(deftrig_trigstates, trigstate);
 
    MemoryContextSwitchTo(oldcxt);
@@ -1130,8 +1133,8 @@ deferredTriggerAddEvent(DeferredTriggerEvent event)
 static DeferredTriggerEvent
 deferredTriggerGetPreviousEvent(Oid relid, ItemPointer ctid)
 {
-   DeferredTriggerEvent    previous;
-   int                     n;
+   DeferredTriggerEvent previous;
+   int         n;
 
    for (n = deftrig_n_events - 1; n >= 0; n--)
    {
@@ -1143,15 +1146,15 @@ deferredTriggerGetPreviousEvent(Oid relid, ItemPointer ctid)
            continue;
 
        if (ItemPointerGetBlockNumber(ctid) ==
-                   ItemPointerGetBlockNumber(&(previous->dte_newctid)) &&
-                   ItemPointerGetOffsetNumber(ctid) ==
-                   ItemPointerGetOffsetNumber(&(previous->dte_newctid)))
+           ItemPointerGetBlockNumber(&(previous->dte_newctid)) &&
+           ItemPointerGetOffsetNumber(ctid) ==
+           ItemPointerGetOffsetNumber(&(previous->dte_newctid)))
            return previous;
    }
 
    elog(ERROR,
-       "deferredTriggerGetPreviousEvent(): event for tuple %s not found",
-       tidout(ctid));
+      "deferredTriggerGetPreviousEvent(): event for tuple %s not found",
+        tidout(ctid));
    return NULL;
 }
 
@@ -1166,13 +1169,13 @@ deferredTriggerGetPreviousEvent(Oid relid, ItemPointer ctid)
 static void
 deferredTriggerExecute(DeferredTriggerEvent event, int itemno)
 {
-   Relation        rel;
-   TriggerData     SaveTriggerData;
-   HeapTupleData   oldtuple;
-   HeapTupleData   newtuple;
-   HeapTuple       rettuple;
-   Buffer          oldbuffer;
-   Buffer          newbuffer;
+   Relation    rel;
+   TriggerData SaveTriggerData;
+   HeapTupleData oldtuple;
+   HeapTupleData newtuple;
+   HeapTuple   rettuple;
+   Buffer      oldbuffer;
+   Buffer      newbuffer;
 
    /* ----------
     * Open the heap and fetch the required OLD and NEW tuples.
@@ -1200,31 +1203,31 @@ deferredTriggerExecute(DeferredTriggerEvent event, int itemno)
     * Setup the trigger information
     * ----------
     */
-   SaveTriggerData.tg_event    = (event->dte_event & TRIGGER_EVENT_OPMASK) |
-                                                       TRIGGER_EVENT_ROW;
+   SaveTriggerData.tg_event = (event->dte_event & TRIGGER_EVENT_OPMASK) |
+       TRIGGER_EVENT_ROW;
    SaveTriggerData.tg_relation = rel;
 
    switch (event->dte_event & TRIGGER_EVENT_OPMASK)
    {
        case TRIGGER_EVENT_INSERT:
            SaveTriggerData.tg_trigtuple = &newtuple;
-           SaveTriggerData.tg_newtuple  = NULL;
-           SaveTriggerData.tg_trigger   =
-                   rel->trigdesc->tg_after_row[TRIGGER_EVENT_INSERT][itemno];
+           SaveTriggerData.tg_newtuple = NULL;
+           SaveTriggerData.tg_trigger =
+               rel->trigdesc->tg_after_row[TRIGGER_EVENT_INSERT][itemno];
            break;
 
        case TRIGGER_EVENT_UPDATE:
            SaveTriggerData.tg_trigtuple = &oldtuple;
-           SaveTriggerData.tg_newtuple  = &newtuple;
-           SaveTriggerData.tg_trigger   =
-                   rel->trigdesc->tg_after_row[TRIGGER_EVENT_UPDATE][itemno];
+           SaveTriggerData.tg_newtuple = &newtuple;
+           SaveTriggerData.tg_trigger =
+               rel->trigdesc->tg_after_row[TRIGGER_EVENT_UPDATE][itemno];
            break;
 
        case TRIGGER_EVENT_DELETE:
            SaveTriggerData.tg_trigtuple = &oldtuple;
-           SaveTriggerData.tg_newtuple  = NULL;
-           SaveTriggerData.tg_trigger   =
-                   rel->trigdesc->tg_after_row[TRIGGER_EVENT_DELETE][itemno];
+           SaveTriggerData.tg_newtuple = NULL;
+           SaveTriggerData.tg_trigger =
+               rel->trigdesc->tg_after_row[TRIGGER_EVENT_DELETE][itemno];
            break;
    }
 
@@ -1271,11 +1274,11 @@ deferredTriggerExecute(DeferredTriggerEvent event, int itemno)
 static void
 deferredTriggerInvokeEvents(bool immediate_only)
 {
-   List                    *el;
-   DeferredTriggerEvent    event;
-   int                     still_deferred_ones;
-   int                     eventno = -1;
-   int                     i;
+   List       *el;
+   DeferredTriggerEvent event;
+   int         still_deferred_ones;
+   int         eventno = -1;
+   int         i;
 
    /* ----------
     * For now we process all events - to speedup transaction blocks
@@ -1286,7 +1289,7 @@ deferredTriggerInvokeEvents(bool immediate_only)
     * SET CONSTRAINTS ... command finishes and calls EndQuery.
     * ----------
     */
-   foreach (el, deftrig_events)
+   foreach(el, deftrig_events)
    {
        eventno++;
 
@@ -1315,8 +1318,8 @@ deferredTriggerInvokeEvents(bool immediate_only)
             * ----------
             */
            if (immediate_only && deferredTriggerCheckState(
-                               event->dte_item[i].dti_tgoid,
-                               event->dte_item[i].dti_state))
+                                           event->dte_item[i].dti_tgoid,
+                                          event->dte_item[i].dti_state))
            {
                still_deferred_ones = true;
                continue;
@@ -1367,34 +1370,34 @@ DeferredTriggerInit(void)
 void
 DeferredTriggerBeginXact(void)
 {
-   MemoryContext           oldcxt;
-   List                    *l;
-   DeferredTriggerStatus   dflstat;
-   DeferredTriggerStatus   stat;
+   MemoryContext oldcxt;
+   List       *l;
+   DeferredTriggerStatus dflstat;
+   DeferredTriggerStatus stat;
 
    if (deftrig_cxt != NULL)
        elog(FATAL,
-           "DeferredTriggerBeginXact() called while inside transaction");
+          "DeferredTriggerBeginXact() called while inside transaction");
 
    /* ----------
     * Create the per transaction memory context and copy all states
     * from the per session context to here.
     * ----------
     */
-   deftrig_cxt             = CreateGlobalMemory("DeferredTriggerXact");
-   oldcxt = MemoryContextSwitchTo((MemoryContext)deftrig_cxt);
+   deftrig_cxt = CreateGlobalMemory("DeferredTriggerXact");
+   oldcxt = MemoryContextSwitchTo((MemoryContext) deftrig_cxt);
 
-   deftrig_all_isset       = deftrig_dfl_all_isset;
-   deftrig_all_isdeferred  = deftrig_dfl_all_isdeferred;
+   deftrig_all_isset = deftrig_dfl_all_isset;
+   deftrig_all_isdeferred = deftrig_dfl_all_isdeferred;
 
-   deftrig_trigstates      = NIL;
-   foreach (l, deftrig_dfl_trigstates)
+   deftrig_trigstates = NIL;
+   foreach(l, deftrig_dfl_trigstates)
    {
        dflstat = (DeferredTriggerStatus) lfirst(l);
-       stat    = (DeferredTriggerStatus)
-                               palloc(sizeof(DeferredTriggerStatusData));
+       stat = (DeferredTriggerStatus)
+           palloc(sizeof(DeferredTriggerStatusData));
 
-       stat->dts_tgoid        = dflstat->dts_tgoid;
+       stat->dts_tgoid = dflstat->dts_tgoid;
        stat->dts_tgisdeferred = dflstat->dts_tgisdeferred;
 
        deftrig_trigstates = lappend(deftrig_trigstates, stat);
@@ -1402,8 +1405,8 @@ DeferredTriggerBeginXact(void)
 
    MemoryContextSwitchTo(oldcxt);
 
-   deftrig_n_events    = 0;
-   deftrig_events      = NIL;
+   deftrig_n_events = 0;
+   deftrig_events = NIL;
 }
 
 
@@ -1484,22 +1487,23 @@ DeferredTriggerAbortXact(void)
 void
 DeferredTriggerSetState(ConstraintsSetStmt *stmt)
 {
-   Relation                tgrel;
-   Relation                irel = (Relation) NULL;
-   List                    *l;
-   List                    *ls;
-   List                    *lnext;
-   List                    *loid = NIL;
-   MemoryContext           oldcxt;
-   bool                    found;
-   DeferredTriggerStatus   state;
-   bool            hasindex;
+   Relation    tgrel;
+   Relation    irel = (Relation) NULL;
+   List       *l;
+   List       *ls;
+   List       *lnext;
+   List       *loid = NIL;
+   MemoryContext oldcxt;
+   bool        found;
+   DeferredTriggerStatus state;
+   bool        hasindex;
 
    /* ----------
     * Handle SET CONSTRAINTS ALL ...
     * ----------
     */
-   if (stmt->constraints == NIL) {
+   if (stmt->constraints == NIL)
+   {
        if (!IsTransactionBlock())
        {
            /* ----------
@@ -1527,13 +1531,15 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
             * Set the session ALL state to known.
             * ----------
             */
-           deftrig_dfl_all_isset      = true;
+           deftrig_dfl_all_isset = true;
            deftrig_dfl_all_isdeferred = stmt->deferred;
 
            MemoryContextSwitchTo(oldcxt);
 
            return;
-       } else {
+       }
+       else
+       {
            /* ----------
             * ... inside of a transaction block
             * ----------
@@ -1559,7 +1565,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
             * Set the per transaction ALL state to known.
             * ----------
             */
-           deftrig_all_isset      = true;
+           deftrig_all_isset = true;
            deftrig_all_isdeferred = stmt->deferred;
 
            MemoryContextSwitchTo(oldcxt);
@@ -1578,23 +1584,23 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
    if (hasindex)
        irel = index_openr(TriggerConstrNameIndex);
 
-   foreach (l, stmt->constraints)
+   foreach(l, stmt->constraints)
    {
-       ScanKeyData         skey;
-       HeapTupleData       tuple;
-       IndexScanDesc       sd = (IndexScanDesc) NULL;
-       HeapScanDesc        tgscan = (HeapScanDesc) NULL;
-       HeapTuple       htup;
-       RetrieveIndexResult indexRes;
-       Buffer              buffer;
-       Form_pg_trigger     pg_trigger;
-       Oid                 constr_oid;
+       ScanKeyData skey;
+       HeapTupleData tuple;
+       IndexScanDesc sd = (IndexScanDesc) NULL;
+       HeapScanDesc tgscan = (HeapScanDesc) NULL;
+       HeapTuple   htup;
+       RetrieveIndexResult indexRes;
+       Buffer      buffer;
+       Form_pg_trigger pg_trigger;
+       Oid         constr_oid;
 
        /* ----------
         * Check that only named constraints are set explicitly
         * ----------
         */
-       if (strcmp((char *)lfirst(l), "") == 0)
+       if (strcmp((char *) lfirst(l), "") == 0)
            elog(ERROR, "unnamed constraints cannot be set explicitly");
 
        /* ----------
@@ -1605,7 +1611,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
                               (bits16) 0x0,
                               (AttrNumber) 1,
                               (RegProcedure) F_NAMEEQ,
-                              PointerGetDatum((char *)lfirst(l)));
+                              PointerGetDatum((char *) lfirst(l)));
 
        if (hasindex)
            sd = index_beginscan(irel, false, 1, &skey);
@@ -1629,9 +1635,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
                heap_fetch(tgrel, SnapshotNow, &tuple, &buffer);
                pfree(indexRes);
                if (!tuple.t_data)
-               {
                    continue;
-               }
                htup = &tuple;
            }
            else
@@ -1649,13 +1653,13 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
             */
            pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
            if (stmt->deferred && !pg_trigger->tgdeferrable &&
-                   pg_trigger->tgfoid != F_RI_FKEY_RESTRICT_UPD &&
-                   pg_trigger->tgfoid != F_RI_FKEY_RESTRICT_DEL)
+               pg_trigger->tgfoid != F_RI_FKEY_RESTRICT_UPD &&
+               pg_trigger->tgfoid != F_RI_FKEY_RESTRICT_DEL)
                elog(ERROR, "Constraint '%s' is not deferrable",
-                                   (char *)lfirst(l));
+                    (char *) lfirst(l));
 
            constr_oid = htup->t_data->t_oid;
-           loid = lappend(loid, (Node *)constr_oid);
+           loid = lappend(loid, (Node *) constr_oid);
            found = true;
 
            if (hasindex)
@@ -1667,11 +1671,11 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
         * ----------
         */
        if (!found)
-           elog(ERROR, "Constraint '%s' does not exist", (char *)lfirst(l));
+           elog(ERROR, "Constraint '%s' does not exist", (char *) lfirst(l));
 
        if (hasindex)
            index_endscan(sd);
-       else    
+       else
            heap_endscan(tgscan);
    }
    if (hasindex)
@@ -1688,10 +1692,10 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
         */
        oldcxt = MemoryContextSwitchTo((MemoryContext) deftrig_gcxt);
 
-       foreach (l, loid)
+       foreach(l, loid)
        {
            found = false;
-           foreach (ls, deftrig_dfl_trigstates)
+           foreach(ls, deftrig_dfl_trigstates)
            {
                state = (DeferredTriggerStatus) lfirst(ls);
                if (state->dts_tgoid == (Oid) lfirst(l))
@@ -1704,19 +1708,21 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
            if (!found)
            {
                state = (DeferredTriggerStatus)
-                                   palloc(sizeof(DeferredTriggerStatusData));
-               state->dts_tgoid        = (Oid) lfirst(l);
+                   palloc(sizeof(DeferredTriggerStatusData));
+               state->dts_tgoid = (Oid) lfirst(l);
                state->dts_tgisdeferred = stmt->deferred;
 
                deftrig_dfl_trigstates =
-                                   lappend(deftrig_dfl_trigstates, state);
+                   lappend(deftrig_dfl_trigstates, state);
            }
        }
 
        MemoryContextSwitchTo(oldcxt);
 
        return;
-   } else {
+   }
+   else
+   {
        /* ----------
         * Inside of a transaction block set the trigger
         * states of individual triggers on transaction level.
@@ -1724,10 +1730,10 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
         */
        oldcxt = MemoryContextSwitchTo((MemoryContext) deftrig_cxt);
 
-       foreach (l, loid)
+       foreach(l, loid)
        {
            found = false;
-           foreach (ls, deftrig_trigstates)
+           foreach(ls, deftrig_trigstates)
            {
                state = (DeferredTriggerStatus) lfirst(ls);
                if (state->dts_tgoid == (Oid) lfirst(l))
@@ -1740,12 +1746,12 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
            if (!found)
            {
                state = (DeferredTriggerStatus)
-                                   palloc(sizeof(DeferredTriggerStatusData));
-               state->dts_tgoid        = (Oid) lfirst(l);
+                   palloc(sizeof(DeferredTriggerStatusData));
+               state->dts_tgoid = (Oid) lfirst(l);
                state->dts_tgisdeferred = stmt->deferred;
 
                deftrig_trigstates =
-                                   lappend(deftrig_trigstates, state);
+                   lappend(deftrig_trigstates, state);
            }
        }
 
@@ -1764,33 +1770,33 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
  */
 void
 DeferredTriggerSaveEvent(Relation rel, int event,
-                   HeapTuple oldtup, HeapTuple newtup)
+                        HeapTuple oldtup, HeapTuple newtup)
 {
-   MemoryContext           oldcxt;
-   DeferredTriggerEvent    new_event;
-   DeferredTriggerEvent    prev_event;
-   int                     new_size;
-   int                     i;
-   int                     ntriggers;
-   Trigger               **triggers;
-   ItemPointerData         oldctid;
-   ItemPointerData         newctid;
-   TriggerData             SaveTriggerData;
+   MemoryContext oldcxt;
+   DeferredTriggerEvent new_event;
+   DeferredTriggerEvent prev_event;
+   int         new_size;
+   int         i;
+   int         ntriggers;
+   Trigger   **triggers;
+   ItemPointerData oldctid;
+   ItemPointerData newctid;
+   TriggerData SaveTriggerData;
 
    if (deftrig_cxt == NULL)
        elog(ERROR,
-           "DeferredTriggerSaveEvent() called outside of transaction");
+            "DeferredTriggerSaveEvent() called outside of transaction");
 
    /* ----------
     * Check if we're interested in this row at all
     * ----------
     */
    if (rel->trigdesc->n_after_row[TRIGGER_EVENT_INSERT] == 0 &&
-               rel->trigdesc->n_after_row[TRIGGER_EVENT_UPDATE] == 0 &&
-               rel->trigdesc->n_after_row[TRIGGER_EVENT_DELETE] == 0 &&
-               rel->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] == 0 &&
-               rel->trigdesc->n_before_row[TRIGGER_EVENT_UPDATE] == 0 &&
-               rel->trigdesc->n_before_row[TRIGGER_EVENT_DELETE] == 0)
+       rel->trigdesc->n_after_row[TRIGGER_EVENT_UPDATE] == 0 &&
+       rel->trigdesc->n_after_row[TRIGGER_EVENT_DELETE] == 0 &&
+       rel->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] == 0 &&
+       rel->trigdesc->n_before_row[TRIGGER_EVENT_UPDATE] == 0 &&
+       rel->trigdesc->n_before_row[TRIGGER_EVENT_DELETE] == 0)
        return;
 
    /* ----------
@@ -1813,14 +1819,14 @@ DeferredTriggerSaveEvent(Relation rel, int event,
    oldcxt = MemoryContextSwitchTo((MemoryContext) deftrig_cxt);
 
    ntriggers = rel->trigdesc->n_after_row[event];
-   triggers  = rel->trigdesc->tg_after_row[event];
+   triggers = rel->trigdesc->tg_after_row[event];
 
-   new_size  = sizeof(DeferredTriggerEventData) +
-               ntriggers * sizeof(DeferredTriggerEventItem);
+   new_size = sizeof(DeferredTriggerEventData) +
+       ntriggers * sizeof(DeferredTriggerEventItem);
 
    new_event = (DeferredTriggerEvent) palloc(new_size);
-   new_event->dte_event    = event & TRIGGER_EVENT_OPMASK;
-   new_event->dte_relid    = rel->rd_id;
+   new_event->dte_event = event & TRIGGER_EVENT_OPMASK;
+   new_event->dte_relid = rel->rd_id;
    ItemPointerCopy(&oldctid, &(new_event->dte_oldctid));
    ItemPointerCopy(&newctid, &(new_event->dte_newctid));
    new_event->dte_n_items = ntriggers;
@@ -1830,11 +1836,11 @@ DeferredTriggerSaveEvent(Relation rel, int event,
        new_event->dte_item[i].dti_tgoid = triggers[i]->tgoid;
        new_event->dte_item[i].dti_state =
            ((triggers[i]->tgdeferrable) ?
-                       TRIGGER_DEFERRED_DEFERRABLE : 0)    |
+            TRIGGER_DEFERRED_DEFERRABLE : 0) |
            ((triggers[i]->tginitdeferred) ?
-                       TRIGGER_DEFERRED_INITDEFERRED : 0)  |
+            TRIGGER_DEFERRED_INITDEFERRED : 0) |
            ((rel->trigdesc->n_before_row[event] > 0) ?
-                       TRIGGER_DEFERRED_HAS_BEFORE : 0);
+            TRIGGER_DEFERRED_HAS_BEFORE : 0);
    }
    MemoryContextSwitchTo(oldcxt);
 
@@ -1864,8 +1870,8 @@ DeferredTriggerSaveEvent(Relation rel, int event,
             */
            for (i = 0; i < ntriggers; i++)
            {
-               bool    is_ri_trigger;
-               bool    key_unchanged;
+               bool        is_ri_trigger;
+               bool        key_unchanged;
 
                /* ----------
                 * We are interested in RI_FKEY triggers only.
@@ -1888,11 +1894,11 @@ DeferredTriggerSaveEvent(Relation rel, int event,
                if (!is_ri_trigger)
                    continue;
 
-               SaveTriggerData.tg_event     = TRIGGER_EVENT_UPDATE;
-               SaveTriggerData.tg_relation  = rel;
+               SaveTriggerData.tg_event = TRIGGER_EVENT_UPDATE;
+               SaveTriggerData.tg_relation = rel;
                SaveTriggerData.tg_trigtuple = oldtup;
-               SaveTriggerData.tg_newtuple  = newtup;
-               SaveTriggerData.tg_trigger   = triggers[i];
+               SaveTriggerData.tg_newtuple = newtup;
+               SaveTriggerData.tg_trigger = triggers[i];
 
                CurrentTriggerData = &SaveTriggerData;
                key_unchanged = RI_FKey_keyequal_upd();
@@ -1911,7 +1917,7 @@ DeferredTriggerSaveEvent(Relation rel, int event,
                    if (prev_event)
                    {
                        if (prev_event->dte_event &
-                                   TRIGGER_DEFERRED_ROW_INSERTED)
+                           TRIGGER_DEFERRED_ROW_INSERTED)
                        {
                            /* ----------
                             * This is a row inserted during our transaction.
@@ -1919,11 +1925,11 @@ DeferredTriggerSaveEvent(Relation rel, int event,
                             * ----------
                             */
                            new_event->dte_event |=
-                                           TRIGGER_DEFERRED_ROW_INSERTED;
+                               TRIGGER_DEFERRED_ROW_INSERTED;
                            new_event->dte_event |=
-                                           TRIGGER_DEFERRED_KEY_CHANGED;
+                               TRIGGER_DEFERRED_KEY_CHANGED;
                            new_event->dte_item[i].dti_state |=
-                                           TRIGGER_DEFERRED_KEY_CHANGED;
+                               TRIGGER_DEFERRED_KEY_CHANGED;
                        }
                        else
                        {
@@ -1934,12 +1940,12 @@ DeferredTriggerSaveEvent(Relation rel, int event,
                             * ----------
                             */
                            if (prev_event->dte_item[i].dti_state &
-                                           TRIGGER_DEFERRED_KEY_CHANGED)
+                               TRIGGER_DEFERRED_KEY_CHANGED)
                            {
                                new_event->dte_item[i].dti_state |=
-                                           TRIGGER_DEFERRED_KEY_CHANGED;
+                                   TRIGGER_DEFERRED_KEY_CHANGED;
                                new_event->dte_event |=
-                                           TRIGGER_DEFERRED_KEY_CHANGED;
+                                   TRIGGER_DEFERRED_KEY_CHANGED;
                            }
                        }
                    }
@@ -1954,16 +1960,16 @@ DeferredTriggerSaveEvent(Relation rel, int event,
                    if (prev_event)
                    {
                        if (prev_event->dte_event &
-                                           TRIGGER_DEFERRED_ROW_INSERTED)
+                           TRIGGER_DEFERRED_ROW_INSERTED)
                            elog(ERROR, "triggered data change violation "
-                                   "on relation \"%s\"",
-                                   nameout(&(rel->rd_rel->relname)));
+                                "on relation \"%s\"",
+                                nameout(&(rel->rd_rel->relname)));
 
                        if (prev_event->dte_item[i].dti_state &
-                                           TRIGGER_DEFERRED_KEY_CHANGED)
+                           TRIGGER_DEFERRED_KEY_CHANGED)
                            elog(ERROR, "triggered data change violation "
-                                   "on relation \"%s\"",
-                                   nameout(&(rel->rd_rel->relname)));
+                                "on relation \"%s\"",
+                                nameout(&(rel->rd_rel->relname)));
                    }
 
                    /* ----------
@@ -1972,7 +1978,7 @@ DeferredTriggerSaveEvent(Relation rel, int event,
                     * ----------
                     */
                    new_event->dte_item[i].dti_state |=
-                                           TRIGGER_DEFERRED_KEY_CHANGED;
+                       TRIGGER_DEFERRED_KEY_CHANGED;
                    new_event->dte_event |= TRIGGER_DEFERRED_KEY_CHANGED;
                }
            }
@@ -1996,8 +2002,8 @@ DeferredTriggerSaveEvent(Relation rel, int event,
            prev_event = deferredTriggerGetPreviousEvent(rel->rd_id, &oldctid);
            if (prev_event->dte_event & TRIGGER_DEFERRED_KEY_CHANGED)
                elog(ERROR, "triggered data change violation "
-                       "on relation \"%s\"",
-                       nameout(&(rel->rd_rel->relname)));
+                    "on relation \"%s\"",
+                    nameout(&(rel->rd_rel->relname)));
 
            break;
    }
@@ -2012,5 +2018,3 @@ DeferredTriggerSaveEvent(Relation rel, int event,
 
    return;
 }
-
-
index 63676e14e48906c765333127f69b70a5f2477a5d..fe24e15b1fd1ca3b394ea856604716806308760d 100644 (file)
@@ -6,7 +6,7 @@
  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- * $Id: user.c,v 1.51 2000/03/15 07:02:56 tgl Exp $
+ * $Id: user.c,v 1.52 2000/04/12 17:14:59 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -55,11 +55,11 @@ write_password_file(Relation rel)
    char       *filename,
               *tempname;
    int         bufsize;
-    FILE       *fp;
-    mode_t      oumask;
-    HeapScanDesc scan;
-    HeapTuple   tuple;
-   TupleDesc dsc = RelationGetDescr(rel);
+   FILE       *fp;
+   mode_t      oumask;
+   HeapScanDesc scan;
+   HeapTuple   tuple;
+   TupleDesc   dsc = RelationGetDescr(rel);
 
    /*
     * Create a temporary filename to be renamed later.  This prevents the
@@ -71,74 +71,85 @@ write_password_file(Relation rel)
    tempname = (char *) palloc(bufsize);
 
    snprintf(tempname, bufsize, "%s.%d", filename, MyProcPid);
-    oumask = umask((mode_t) 077);
-    fp = AllocateFile(tempname, "w");
-    umask(oumask);
-    if (fp == NULL)
-        elog(ERROR, "%s: %s", tempname, strerror(errno));
-
-    /* read table */
-    scan = heap_beginscan(rel, false, SnapshotSelf, 0, NULL);
-    while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
-    {
-        Datum      datum_n, datum_p, datum_v;
-        bool        null_n, null_p, null_v;
+   oumask = umask((mode_t) 077);
+   fp = AllocateFile(tempname, "w");
+   umask(oumask);
+   if (fp == NULL)
+       elog(ERROR, "%s: %s", tempname, strerror(errno));
+
+   /* read table */
+   scan = heap_beginscan(rel, false, SnapshotSelf, 0, NULL);
+   while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
+   {
+       Datum       datum_n,
+                   datum_p,
+                   datum_v;
+       bool        null_n,
+                   null_p,
+                   null_v;
 
        datum_n = heap_getattr(tuple, Anum_pg_shadow_usename, dsc, &null_n);
-        if (null_n)
-            continue; /* don't allow empty users */
+       if (null_n)
+           continue;           /* don't allow empty users */
        datum_p = heap_getattr(tuple, Anum_pg_shadow_passwd, dsc, &null_p);
-        /* It could be argued that people having a null password
-           shouldn't be allowed to connect, because they need
-           to have a password set up first. If you think assuming
-           an empty password in that case is better, erase the following line. */
-        if (null_p)
-            continue;
+
+       /*
+        * It could be argued that people having a null password shouldn't
+        * be allowed to connect, because they need to have a password set
+        * up first. If you think assuming an empty password in that case
+        * is better, erase the following line.
+        */
+       if (null_p)
+           continue;
        datum_v = heap_getattr(tuple, Anum_pg_shadow_valuntil, dsc, &null_v);
 
-        /* These fake entries are not really necessary. To remove them, the parser
-           in backend/libpq/crypt.c would need to be adjusted. Initdb might also
-           need adjustments. */
-        fprintf(fp, 
-                "%s"
-                CRYPT_PWD_FILE_SEPSTR
-                "0"
-                CRYPT_PWD_FILE_SEPSTR
-                "x"
-                CRYPT_PWD_FILE_SEPSTR
-                "x"
-                CRYPT_PWD_FILE_SEPSTR
-                "x"
-                CRYPT_PWD_FILE_SEPSTR
-                "x"
-                CRYPT_PWD_FILE_SEPSTR
-                "%s"
-                CRYPT_PWD_FILE_SEPSTR
-                "%s\n",
-                nameout(DatumGetName(datum_n)),
-                null_p ? "" : textout((text*)datum_p),
-                null_v ? "\\N" : nabstimeout((AbsoluteTime)datum_v) /* this is how the parser wants it */
-                );
-        if (ferror(fp))
-            elog(ERROR, "%s: %s", tempname, strerror(errno));
-        fflush(fp);
-    }
-    heap_endscan(scan);
-    FreeFile(fp);
-
-    /*
-     * And rename the temp file to its final name, deleting the old pg_pwd.
-     */
-    rename(tempname, filename);
-
-    /*
+       /*
+        * These fake entries are not really necessary. To remove them,
+        * the parser in backend/libpq/crypt.c would need to be adjusted.
+        * Initdb might also need adjustments.
+        */
+       fprintf(fp,
+               "%s"
+               CRYPT_PWD_FILE_SEPSTR
+               "0"
+               CRYPT_PWD_FILE_SEPSTR
+               "x"
+               CRYPT_PWD_FILE_SEPSTR
+               "x"
+               CRYPT_PWD_FILE_SEPSTR
+               "x"
+               CRYPT_PWD_FILE_SEPSTR
+               "x"
+               CRYPT_PWD_FILE_SEPSTR
+               "%s"
+               CRYPT_PWD_FILE_SEPSTR
+               "%s\n",
+               nameout(DatumGetName(datum_n)),
+               null_p ? "" : textout((text *) datum_p),
+               null_v ? "\\N" : nabstimeout((AbsoluteTime) datum_v)    /* this is how the
+                                                                        * parser wants it */
+           );
+       if (ferror(fp))
+           elog(ERROR, "%s: %s", tempname, strerror(errno));
+       fflush(fp);
+   }
+   heap_endscan(scan);
+   FreeFile(fp);
+
+   /*
+    * And rename the temp file to its final name, deleting the old
+    * pg_pwd.
+    */
+   rename(tempname, filename);
+
+   /*
     * Create a flag file the postmaster will detect the next time it
     * tries to authenticate a user.  The postmaster will know to reload
     * the pg_pwd file contents.
     */
    filename = crypt_getpwdreloadfilename();
    if (creat(filename, S_IRUSR | S_IWUSR) == -1)
-        elog(ERROR, "%s: %s", filename, strerror(errno));
+       elog(ERROR, "%s: %s", filename, strerror(errno));
 
    pfree((void *) tempname);
 }
@@ -149,16 +160,17 @@ write_password_file(Relation rel)
 HeapTuple
 update_pg_pwd(void)
 {
-    Relation rel = heap_openr(ShadowRelationName,  AccessExclusiveLock);
-    write_password_file(rel);
-    heap_close(rel,  AccessExclusiveLock);
+   Relation    rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
+
+   write_password_file(rel);
+   heap_close(rel, AccessExclusiveLock);
 
    /*
-    * This is a trigger, so clean out the information provided by
-    * the trigger manager.
+    * This is a trigger, so clean out the information provided by the
+    * trigger manager.
     */
    CurrentTriggerData = NULL;
-    return NULL;
+   return NULL;
 }
 
 
@@ -173,36 +185,37 @@ CreateUser(CreateUserStmt *stmt)
    TupleDesc   pg_shadow_dsc;
    HeapScanDesc scan;
    HeapTuple   tuple;
-    Datum       new_record[Natts_pg_shadow];
-    char        new_record_nulls[Natts_pg_shadow];
+   Datum       new_record[Natts_pg_shadow];
+   char        new_record_nulls[Natts_pg_shadow];
    bool        user_exists = false,
-                sysid_exists = false,
-                havesysid;
+               sysid_exists = false,
+               havesysid;
    int         max_id = -1;
-    List       *item;
+   List       *item;
 
-    havesysid    = stmt->sysid > 0;
+   havesysid = stmt->sysid > 0;
 
-    /* Check some permissions first */
+   /* Check some permissions first */
    if (stmt->password)
        CheckPgUserAclNotNull();
 
-    if (!superuser())
-        elog(ERROR, "CREATE USER: permission denied");
+   if (!superuser())
+       elog(ERROR, "CREATE USER: permission denied");
 
-    /* The reason for the following is this:
-     * If you start a transaction block, create a user, then roll back the
-     * transaction, the pg_pwd won't get rolled back due to a bug in the
-     * Unix file system ( :}). Hence this is in the interest of security.
-     */
+   /*
+    * The reason for the following is this: If you start a transaction
+    * block, create a user, then roll back the transaction, the pg_pwd
+    * won't get rolled back due to a bug in the Unix file system ( :}).
+    * Hence this is in the interest of security.
+    */
    if (IsTransactionBlock())
-        elog(ERROR, "CREATE USER: may not be called in a transaction block");
+       elog(ERROR, "CREATE USER: may not be called in a transaction block");
 
    /*
-    * Scan the pg_shadow relation to be certain the user or id doesn't already
-    * exist.  Note we secure exclusive lock, because we also need to be
-    * sure of what the next usesysid should be, and we need to protect
-    * our update of the flat password file.
+    * Scan the pg_shadow relation to be certain the user or id doesn't
+    * already exist.  Note we secure exclusive lock, because we also need
+    * to be sure of what the next usesysid should be, and we need to
+    * protect our update of the flat password file.
     */
    pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
    pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
@@ -210,103 +223,108 @@ CreateUser(CreateUserStmt *stmt)
    scan = heap_beginscan(pg_shadow_rel, false, SnapshotNow, 0, NULL);
    while (!user_exists && !sysid_exists && HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
    {
-        Datum      datum;
-        bool        null;
+       Datum       datum;
+       bool        null;
 
        datum = heap_getattr(tuple, Anum_pg_shadow_usename, pg_shadow_dsc, &null);
        user_exists = datum && !null && (strcmp((char *) datum, stmt->user) == 0);
 
        datum = heap_getattr(tuple, Anum_pg_shadow_usesysid, pg_shadow_dsc, &null);
-        if (havesysid) /* customized id wanted */
-            sysid_exists = datum && !null && ((int)datum == stmt->sysid);
-        else /* pick 1 + max */
-        {
-            if ((int) datum > max_id)
-                max_id = (int) datum;
-        }
+       if (havesysid)          /* customized id wanted */
+           sysid_exists = datum && !null && ((int) datum == stmt->sysid);
+       else
+/* pick 1 + max */
+       {
+           if ((int) datum > max_id)
+               max_id = (int) datum;
+       }
    }
    heap_endscan(scan);
 
    if (user_exists || sysid_exists)
    {
        heap_close(pg_shadow_rel, AccessExclusiveLock);
-        if (user_exists)
-            elog(ERROR, "CREATE USER: user name \"%s\" already exists", stmt->user);
-        else
-            elog(ERROR, "CREATE USER: sysid %d is already assigned", stmt->sysid);
+       if (user_exists)
+           elog(ERROR, "CREATE USER: user name \"%s\" already exists", stmt->user);
+       else
+           elog(ERROR, "CREATE USER: sysid %d is already assigned", stmt->sysid);
        return;
    }
 
-    /*
-     * Build a tuple to insert
-     */
-    new_record[Anum_pg_shadow_usename-1] = PointerGetDatum(namein(stmt->user)); /* this truncated properly */
-    new_record[Anum_pg_shadow_usesysid-1] = Int32GetDatum(havesysid ? stmt->sysid : max_id + 1);
-
-    AssertState(BoolIsValid(stmt->createdb));
-    new_record[Anum_pg_shadow_usecreatedb-1] = (Datum)(stmt->createdb);
-    new_record[Anum_pg_shadow_usetrace-1] = (Datum)(false);
-    AssertState(BoolIsValid(stmt->createuser));
-    new_record[Anum_pg_shadow_usesuper-1] = (Datum)(stmt->createuser);
-    /* superuser gets catupd right by default */
-    new_record[Anum_pg_shadow_usecatupd-1] = (Datum)(stmt->createuser);
-
-    if (stmt->password)
-        new_record[Anum_pg_shadow_passwd-1] = PointerGetDatum(textin(stmt->password));
-    if (stmt->validUntil)
-        new_record[Anum_pg_shadow_valuntil-1] = PointerGetDatum(nabstimein(stmt->validUntil));
-
-    new_record_nulls[Anum_pg_shadow_usename-1] = ' ';
-    new_record_nulls[Anum_pg_shadow_usesysid-1] = ' ';
-
-    new_record_nulls[Anum_pg_shadow_usecreatedb-1] = ' ';
-    new_record_nulls[Anum_pg_shadow_usetrace-1] = ' ';
-    new_record_nulls[Anum_pg_shadow_usesuper-1] = ' ';
-    new_record_nulls[Anum_pg_shadow_usecatupd-1] = ' ';
-
-    new_record_nulls[Anum_pg_shadow_passwd-1] = stmt->password ? ' ' : 'n';
-    new_record_nulls[Anum_pg_shadow_valuntil-1] = stmt->validUntil ? ' ' : 'n';
-
-    tuple = heap_formtuple(pg_shadow_dsc, new_record, new_record_nulls);
-    Assert(tuple);
-
-    /*
-     * Insert a new record in the pg_shadow table
-     */
-    if (heap_insert(pg_shadow_rel, tuple) == InvalidOid)
-        elog(ERROR, "CREATE USER: heap_insert failed");
-
-    /*
-     * Update indexes
-     */
-    if (RelationGetForm(pg_shadow_rel)->relhasindex) {
-        Relation idescs[Num_pg_shadow_indices];
-      
-        CatalogOpenIndices(Num_pg_shadow_indices, 
-                           Name_pg_shadow_indices, idescs);
-        CatalogIndexInsert(idescs, Num_pg_shadow_indices, pg_shadow_rel, 
-                           tuple);
-        CatalogCloseIndices(Num_pg_shadow_indices, idescs);
-    }
+   /*
+    * Build a tuple to insert
+    */
+   new_record[Anum_pg_shadow_usename - 1] = PointerGetDatum(namein(stmt->user));       /* this truncated
+                                                                                        * properly */
+   new_record[Anum_pg_shadow_usesysid - 1] = Int32GetDatum(havesysid ? stmt->sysid : max_id + 1);
+
+   AssertState(BoolIsValid(stmt->createdb));
+   new_record[Anum_pg_shadow_usecreatedb - 1] = (Datum) (stmt->createdb);
+   new_record[Anum_pg_shadow_usetrace - 1] = (Datum) (false);
+   AssertState(BoolIsValid(stmt->createuser));
+   new_record[Anum_pg_shadow_usesuper - 1] = (Datum) (stmt->createuser);
+   /* superuser gets catupd right by default */
+   new_record[Anum_pg_shadow_usecatupd - 1] = (Datum) (stmt->createuser);
+
+   if (stmt->password)
+       new_record[Anum_pg_shadow_passwd - 1] = PointerGetDatum(textin(stmt->password));
+   if (stmt->validUntil)
+       new_record[Anum_pg_shadow_valuntil - 1] = PointerGetDatum(nabstimein(stmt->validUntil));
+
+   new_record_nulls[Anum_pg_shadow_usename - 1] = ' ';
+   new_record_nulls[Anum_pg_shadow_usesysid - 1] = ' ';
+
+   new_record_nulls[Anum_pg_shadow_usecreatedb - 1] = ' ';
+   new_record_nulls[Anum_pg_shadow_usetrace - 1] = ' ';
+   new_record_nulls[Anum_pg_shadow_usesuper - 1] = ' ';
+   new_record_nulls[Anum_pg_shadow_usecatupd - 1] = ' ';
+
+   new_record_nulls[Anum_pg_shadow_passwd - 1] = stmt->password ? ' ' : 'n';
+   new_record_nulls[Anum_pg_shadow_valuntil - 1] = stmt->validUntil ? ' ' : 'n';
+
+   tuple = heap_formtuple(pg_shadow_dsc, new_record, new_record_nulls);
+   Assert(tuple);
+
+   /*
+    * Insert a new record in the pg_shadow table
+    */
+   if (heap_insert(pg_shadow_rel, tuple) == InvalidOid)
+       elog(ERROR, "CREATE USER: heap_insert failed");
+
+   /*
+    * Update indexes
+    */
+   if (RelationGetForm(pg_shadow_rel)->relhasindex)
+   {
+       Relation    idescs[Num_pg_shadow_indices];
+
+       CatalogOpenIndices(Num_pg_shadow_indices,
+                          Name_pg_shadow_indices, idescs);
+       CatalogIndexInsert(idescs, Num_pg_shadow_indices, pg_shadow_rel,
+                          tuple);
+       CatalogCloseIndices(Num_pg_shadow_indices, idescs);
+   }
 
    /*
     * Add the user to the groups specified. We'll just call the below
-     * AlterGroup for this.
+    * AlterGroup for this.
     */
-    foreach(item, stmt->groupElts)
-    {
-        AlterGroupStmt ags;
+   foreach(item, stmt->groupElts)
+   {
+       AlterGroupStmt ags;
 
-        ags.name = strVal(lfirst(item)); /* the group name to add this in */
-        ags.action = +1;
-        ags.listUsers = lcons((void*)makeInteger(havesysid ? stmt->sysid : max_id + 1), NIL);
-        AlterGroup(&ags, "CREATE USER");
-    }
+       ags.name = strVal(lfirst(item));        /* the group name to add
+                                                * this in */
+       ags.action = +1;
+       ags.listUsers = lcons((void *) makeInteger(havesysid ? stmt->sysid : max_id + 1), NIL);
+       AlterGroup(&ags, "CREATE USER");
+   }
 
    /*
     * Write the updated pg_shadow data to the flat password file.
     */
-    write_password_file(pg_shadow_rel);
+   write_password_file(pg_shadow_rel);
+
    /*
     * Now we can clean up.
     */
@@ -321,30 +339,31 @@ CreateUser(CreateUserStmt *stmt)
 extern void
 AlterUser(AlterUserStmt *stmt)
 {
-    Datum       new_record[Natts_pg_shadow];
-    char        new_record_nulls[Natts_pg_shadow];
+   Datum       new_record[Natts_pg_shadow];
+   char        new_record_nulls[Natts_pg_shadow];
    Relation    pg_shadow_rel;
    TupleDesc   pg_shadow_dsc;
-   HeapTuple   tuple, new_tuple;
-    bool        null;
+   HeapTuple   tuple,
+               new_tuple;
+   bool        null;
 
    if (stmt->password)
        CheckPgUserAclNotNull();
 
-    /* must be superuser or just want to change your own password */
-    if (!superuser() &&
-        !(stmt->createdb==0 && stmt->createuser==0 && !stmt->validUntil
-          && stmt->password && strcmp(GetPgUserName(), stmt->user)==0))
-        elog(ERROR, "ALTER USER: permission denied");
+   /* must be superuser or just want to change your own password */
+   if (!superuser() &&
+     !(stmt->createdb == 0 && stmt->createuser == 0 && !stmt->validUntil
+       && stmt->password && strcmp(GetPgUserName(), stmt->user) == 0))
+       elog(ERROR, "ALTER USER: permission denied");
 
-    /* see comments in create user */
+   /* see comments in create user */
    if (IsTransactionBlock())
-        elog(ERROR, "ALTER USER: may not be called in a transaction block");
+       elog(ERROR, "ALTER USER: may not be called in a transaction block");
 
    /*
-    * Scan the pg_shadow relation to be certain the user exists.
-    * Note we secure exclusive lock to protect our update of the
-    * flat password file.
+    * Scan the pg_shadow relation to be certain the user exists. Note we
+    * secure exclusive lock to protect our update of the flat password
+    * file.
     */
    pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
    pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
@@ -358,107 +377,107 @@ AlterUser(AlterUserStmt *stmt)
        elog(ERROR, "ALTER USER: user \"%s\" does not exist", stmt->user);
    }
 
-    /*
-     * Build a tuple to update, perusing the information just obtained
-     */
-    new_record[Anum_pg_shadow_usename-1] = PointerGetDatum(namein(stmt->user));
-    new_record_nulls[Anum_pg_shadow_usename-1] = ' ';
-
-    /* sysid - leave as is */
-    new_record[Anum_pg_shadow_usesysid-1] = heap_getattr(tuple, Anum_pg_shadow_usesysid, pg_shadow_dsc, &null);
-    new_record_nulls[Anum_pg_shadow_usesysid-1] = null ? 'n' : ' ';
-
-    /* createdb */
-    if (stmt->createdb == 0)
-    {
-        /* don't change */
-        new_record[Anum_pg_shadow_usecreatedb-1] = heap_getattr(tuple, Anum_pg_shadow_usecreatedb, pg_shadow_dsc, &null);
-        new_record_nulls[Anum_pg_shadow_usecreatedb-1] = null ? 'n' : ' ';
-    }
-    else
-    {
-        new_record[Anum_pg_shadow_usecreatedb-1] = (Datum)(stmt->createdb > 0 ? true : false);
-        new_record_nulls[Anum_pg_shadow_usecreatedb-1] = ' ';
-    }
-
-    /* trace - leave as is */
-    new_record[Anum_pg_shadow_usetrace-1] = heap_getattr(tuple, Anum_pg_shadow_usetrace, pg_shadow_dsc, &null);
-    new_record_nulls[Anum_pg_shadow_usetrace-1] = null ? 'n' : ' ';
-
-    /* createuser (superuser) */
-    if (stmt->createuser == 0)
-    {
-        /* don't change */
-        new_record[Anum_pg_shadow_usesuper-1] = heap_getattr(tuple, Anum_pg_shadow_usesuper, pg_shadow_dsc, &null);
-        new_record_nulls[Anum_pg_shadow_usesuper-1] = null ? 'n' : ' ';
-    }
-    else
-    {
-        new_record[Anum_pg_shadow_usesuper-1] = (Datum)(stmt->createuser > 0 ? true : false);
-        new_record_nulls[Anum_pg_shadow_usesuper-1] = ' ';
-    }
-
-    /* catupd - set to false if someone's superuser priv is being yanked */
-    if (stmt->createuser < 0)
-    {
-        new_record[Anum_pg_shadow_usecatupd-1] = (Datum)(false);
-        new_record_nulls[Anum_pg_shadow_usecatupd-1] = ' ';
-    }
-    else
-    {
-        /* leave alone */
-        new_record[Anum_pg_shadow_usecatupd-1] = heap_getattr(tuple, Anum_pg_shadow_usecatupd, pg_shadow_dsc, &null);
-        new_record_nulls[Anum_pg_shadow_usecatupd-1] = null ? 'n' : ' ';
-    }
-
-    /* password */
-    if (stmt->password)
-    {
-        new_record[Anum_pg_shadow_passwd-1] = PointerGetDatum(textin(stmt->password));
-        new_record_nulls[Anum_pg_shadow_passwd-1] = ' ';
-    }
-    else
-    {
-        /* leave as is */
-        new_record[Anum_pg_shadow_passwd-1] = heap_getattr(tuple, Anum_pg_shadow_passwd, pg_shadow_dsc, &null);
-        new_record_nulls[Anum_pg_shadow_passwd-1] = null ? 'n' : ' ';
-    }
-
-    /* valid until */
-    if (stmt->validUntil)
-    {    
-        new_record[Anum_pg_shadow_valuntil-1] = PointerGetDatum(nabstimein(stmt->validUntil));
-        new_record_nulls[Anum_pg_shadow_valuntil-1] = ' ';
-    }
-    else
-    {
-        /* leave as is */
-        new_record[Anum_pg_shadow_valuntil-1] = heap_getattr(tuple, Anum_pg_shadow_valuntil, pg_shadow_dsc, &null);
-        new_record_nulls[Anum_pg_shadow_valuntil-1] = null ? 'n' : ' ';
-    }
-
-    new_tuple = heap_formtuple(pg_shadow_dsc, new_record, new_record_nulls);
-    Assert(new_tuple);
-    /* XXX check return value of this? */
-    heap_update(pg_shadow_rel, &tuple->t_self, new_tuple, NULL);
-
-
-    /* Update indexes */
-    if (RelationGetForm(pg_shadow_rel)->relhasindex)
-    {
-        Relation idescs[Num_pg_shadow_indices];
-      
-        CatalogOpenIndices(Num_pg_shadow_indices, 
-                           Name_pg_shadow_indices, idescs);
-        CatalogIndexInsert(idescs, Num_pg_shadow_indices, pg_shadow_rel, 
-                           tuple);
-        CatalogCloseIndices(Num_pg_shadow_indices, idescs);
-    }
+   /*
+    * Build a tuple to update, perusing the information just obtained
+    */
+   new_record[Anum_pg_shadow_usename - 1] = PointerGetDatum(namein(stmt->user));
+   new_record_nulls[Anum_pg_shadow_usename - 1] = ' ';
+
+   /* sysid - leave as is */
+   new_record[Anum_pg_shadow_usesysid - 1] = heap_getattr(tuple, Anum_pg_shadow_usesysid, pg_shadow_dsc, &null);
+   new_record_nulls[Anum_pg_shadow_usesysid - 1] = null ? 'n' : ' ';
+
+   /* createdb */
+   if (stmt->createdb == 0)
+   {
+       /* don't change */
+       new_record[Anum_pg_shadow_usecreatedb - 1] = heap_getattr(tuple, Anum_pg_shadow_usecreatedb, pg_shadow_dsc, &null);
+       new_record_nulls[Anum_pg_shadow_usecreatedb - 1] = null ? 'n' : ' ';
+   }
+   else
+   {
+       new_record[Anum_pg_shadow_usecreatedb - 1] = (Datum) (stmt->createdb > 0 ? true : false);
+       new_record_nulls[Anum_pg_shadow_usecreatedb - 1] = ' ';
+   }
+
+   /* trace - leave as is */
+   new_record[Anum_pg_shadow_usetrace - 1] = heap_getattr(tuple, Anum_pg_shadow_usetrace, pg_shadow_dsc, &null);
+   new_record_nulls[Anum_pg_shadow_usetrace - 1] = null ? 'n' : ' ';
+
+   /* createuser (superuser) */
+   if (stmt->createuser == 0)
+   {
+       /* don't change */
+       new_record[Anum_pg_shadow_usesuper - 1] = heap_getattr(tuple, Anum_pg_shadow_usesuper, pg_shadow_dsc, &null);
+       new_record_nulls[Anum_pg_shadow_usesuper - 1] = null ? 'n' : ' ';
+   }
+   else
+   {
+       new_record[Anum_pg_shadow_usesuper - 1] = (Datum) (stmt->createuser > 0 ? true : false);
+       new_record_nulls[Anum_pg_shadow_usesuper - 1] = ' ';
+   }
+
+   /* catupd - set to false if someone's superuser priv is being yanked */
+   if (stmt->createuser < 0)
+   {
+       new_record[Anum_pg_shadow_usecatupd - 1] = (Datum) (false);
+       new_record_nulls[Anum_pg_shadow_usecatupd - 1] = ' ';
+   }
+   else
+   {
+       /* leave alone */
+       new_record[Anum_pg_shadow_usecatupd - 1] = heap_getattr(tuple, Anum_pg_shadow_usecatupd, pg_shadow_dsc, &null);
+       new_record_nulls[Anum_pg_shadow_usecatupd - 1] = null ? 'n' : ' ';
+   }
+
+   /* password */
+   if (stmt->password)
+   {
+       new_record[Anum_pg_shadow_passwd - 1] = PointerGetDatum(textin(stmt->password));
+       new_record_nulls[Anum_pg_shadow_passwd - 1] = ' ';
+   }
+   else
+   {
+       /* leave as is */
+       new_record[Anum_pg_shadow_passwd - 1] = heap_getattr(tuple, Anum_pg_shadow_passwd, pg_shadow_dsc, &null);
+       new_record_nulls[Anum_pg_shadow_passwd - 1] = null ? 'n' : ' ';
+   }
+
+   /* valid until */
+   if (stmt->validUntil)
+   {
+       new_record[Anum_pg_shadow_valuntil - 1] = PointerGetDatum(nabstimein(stmt->validUntil));
+       new_record_nulls[Anum_pg_shadow_valuntil - 1] = ' ';
+   }
+   else
+   {
+       /* leave as is */
+       new_record[Anum_pg_shadow_valuntil - 1] = heap_getattr(tuple, Anum_pg_shadow_valuntil, pg_shadow_dsc, &null);
+       new_record_nulls[Anum_pg_shadow_valuntil - 1] = null ? 'n' : ' ';
+   }
+
+   new_tuple = heap_formtuple(pg_shadow_dsc, new_record, new_record_nulls);
+   Assert(new_tuple);
+   /* XXX check return value of this? */
+   heap_update(pg_shadow_rel, &tuple->t_self, new_tuple, NULL);
+
+
+   /* Update indexes */
+   if (RelationGetForm(pg_shadow_rel)->relhasindex)
+   {
+       Relation    idescs[Num_pg_shadow_indices];
+
+       CatalogOpenIndices(Num_pg_shadow_indices,
+                          Name_pg_shadow_indices, idescs);
+       CatalogIndexInsert(idescs, Num_pg_shadow_indices, pg_shadow_rel,
+                          tuple);
+       CatalogCloseIndices(Num_pg_shadow_indices, idescs);
+   }
 
    /*
     * Write the updated pg_shadow data to the flat password file.
     */
-    write_password_file(pg_shadow_rel);
+   write_password_file(pg_shadow_rel);
 
    /*
     * Now we can clean up.
@@ -477,13 +496,13 @@ DropUser(DropUserStmt *stmt)
 {
    Relation    pg_shadow_rel;
    TupleDesc   pg_shadow_dsc;
-    List       *item;
+   List       *item;
 
-    if (!superuser())
-        elog(ERROR, "DROP USER: permission denied");
+   if (!superuser())
+       elog(ERROR, "DROP USER: permission denied");
 
    if (IsTransactionBlock())
-        elog(ERROR, "DROP USER: may not be called in a transaction block");
+       elog(ERROR, "DROP USER: may not be called in a transaction block");
 
    /*
     * Scan the pg_shadow relation to find the usesysid of the user to be
@@ -493,103 +512,105 @@ DropUser(DropUserStmt *stmt)
    pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
    pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
 
-    foreach(item, stmt->users)
-    {
-        HeapTuple  tuple,
-            tmp_tuple;
-        Relation    pg_rel;
-        TupleDesc   pg_dsc;
-        ScanKeyData scankey;
-        HeapScanDesc scan;
-        Datum      datum;
-        bool       null;
-        int32      usesysid;
-        const char *user = strVal(lfirst(item));
-
-        tuple = SearchSysCacheTuple(SHADOWNAME,
-                                    PointerGetDatum(user),
-                                    0, 0, 0);
-        if (!HeapTupleIsValid(tuple))
-        {
-            heap_close(pg_shadow_rel, AccessExclusiveLock);
-            elog(ERROR, "DROP USER: user \"%s\" does not exist%s", user,
-                 (length(stmt->users) > 1) ? " (no users removed)" : "");
-        }
-
-        usesysid = DatumGetInt32(heap_getattr(tuple, Anum_pg_shadow_usesysid, pg_shadow_dsc, &null));
-
-        /*-------------------
-         * Check if user still owns a database. If so, error out.
-         *
-         * (It used to be that this function would drop the database automatically.
-         *  This is not only very dangerous for people that don't read the manual,
-         *  it doesn't seem to be the behaviour one would expect either.)
-         *                                                   -- petere 2000/01/14)
-         *-------------------*/
-        pg_rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
-        pg_dsc = RelationGetDescr(pg_rel);
-
-        ScanKeyEntryInitialize(&scankey, 0x0, Anum_pg_database_datdba, F_INT4EQ,
-                               Int32GetDatum(usesysid));
-
-        scan = heap_beginscan(pg_rel, false, SnapshotNow, 1, &scankey);
-
-        if (HeapTupleIsValid(tmp_tuple = heap_getnext(scan, 0)))
-        {
-            datum = heap_getattr(tmp_tuple, Anum_pg_database_datname, pg_dsc, &null);
-            heap_close(pg_shadow_rel, AccessExclusiveLock);
-            elog(ERROR, "DROP USER: user \"%s\" owns database \"%s\", cannot be removed%s",
-                 user, nameout(DatumGetName(datum)),
-                 (length(stmt->users) > 1) ? " (no users removed)" : ""
-                );
-        }
-            
-        heap_endscan(scan);
-        heap_close(pg_rel, AccessExclusiveLock);
-
-        /*
-         * Somehow we'd have to check for tables, views, etc. owned by the user
-         * as well, but those could be spread out over all sorts of databases
-         * which we don't have access to (easily).
-         */
-
-        /*
-         * Remove the user from the pg_shadow table
-         */
-        heap_delete(pg_shadow_rel, &tuple->t_self, NULL);
-
-        /*
-         * Remove user from groups
-         *
-         * try calling alter group drop user for every group
-         */
-        pg_rel = heap_openr(GroupRelationName, AccessExclusiveLock);
-        pg_dsc = RelationGetDescr(pg_rel);
-        scan = heap_beginscan(pg_rel, false, SnapshotNow, 0, NULL);
-        while (HeapTupleIsValid(tmp_tuple = heap_getnext(scan, 0)))
-        {
-            AlterGroupStmt ags;
-
-            datum = heap_getattr(tmp_tuple, Anum_pg_group_groname, pg_dsc, &null);
-
-            ags.name = nameout(DatumGetName(datum)); /* the group name from which to try to drop the user */
-            ags.action = -1;
-            ags.listUsers = lcons((void*)makeInteger(usesysid), NIL);
-            AlterGroup(&ags, "DROP USER");
-        }
-        heap_endscan(scan);
-        heap_close(pg_rel, AccessExclusiveLock);        
-    }
+   foreach(item, stmt->users)
+   {
+       HeapTuple   tuple,
+                   tmp_tuple;
+       Relation    pg_rel;
+       TupleDesc   pg_dsc;
+       ScanKeyData scankey;
+       HeapScanDesc scan;
+       Datum       datum;
+       bool        null;
+       int32       usesysid;
+       const char *user = strVal(lfirst(item));
+
+       tuple = SearchSysCacheTuple(SHADOWNAME,
+                                   PointerGetDatum(user),
+                                   0, 0, 0);
+       if (!HeapTupleIsValid(tuple))
+       {
+           heap_close(pg_shadow_rel, AccessExclusiveLock);
+           elog(ERROR, "DROP USER: user \"%s\" does not exist%s", user,
+                (length(stmt->users) > 1) ? " (no users removed)" : "");
+       }
+
+       usesysid = DatumGetInt32(heap_getattr(tuple, Anum_pg_shadow_usesysid, pg_shadow_dsc, &null));
+
+       /*-------------------
+        * Check if user still owns a database. If so, error out.
+        *
+        * (It used to be that this function would drop the database automatically.
+        *  This is not only very dangerous for people that don't read the manual,
+        *  it doesn't seem to be the behaviour one would expect either.)
+        *                                                   -- petere 2000/01/14)
+        *-------------------*/
+       pg_rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
+       pg_dsc = RelationGetDescr(pg_rel);
+
+       ScanKeyEntryInitialize(&scankey, 0x0, Anum_pg_database_datdba, F_INT4EQ,
+                              Int32GetDatum(usesysid));
+
+       scan = heap_beginscan(pg_rel, false, SnapshotNow, 1, &scankey);
+
+       if (HeapTupleIsValid(tmp_tuple = heap_getnext(scan, 0)))
+       {
+           datum = heap_getattr(tmp_tuple, Anum_pg_database_datname, pg_dsc, &null);
+           heap_close(pg_shadow_rel, AccessExclusiveLock);
+           elog(ERROR, "DROP USER: user \"%s\" owns database \"%s\", cannot be removed%s",
+                user, nameout(DatumGetName(datum)),
+                (length(stmt->users) > 1) ? " (no users removed)" : ""
+               );
+       }
+
+       heap_endscan(scan);
+       heap_close(pg_rel, AccessExclusiveLock);
+
+       /*
+        * Somehow we'd have to check for tables, views, etc. owned by the
+        * user as well, but those could be spread out over all sorts of
+        * databases which we don't have access to (easily).
+        */
+
+       /*
+        * Remove the user from the pg_shadow table
+        */
+       heap_delete(pg_shadow_rel, &tuple->t_self, NULL);
+
+       /*
+        * Remove user from groups
+        *
+        * try calling alter group drop user for every group
+        */
+       pg_rel = heap_openr(GroupRelationName, AccessExclusiveLock);
+       pg_dsc = RelationGetDescr(pg_rel);
+       scan = heap_beginscan(pg_rel, false, SnapshotNow, 0, NULL);
+       while (HeapTupleIsValid(tmp_tuple = heap_getnext(scan, 0)))
+       {
+           AlterGroupStmt ags;
+
+           datum = heap_getattr(tmp_tuple, Anum_pg_group_groname, pg_dsc, &null);
+
+           ags.name = nameout(DatumGetName(datum));    /* the group name from
+                                                        * which to try to drop
+                                                        * the user */
+           ags.action = -1;
+           ags.listUsers = lcons((void *) makeInteger(usesysid), NIL);
+           AlterGroup(&ags, "DROP USER");
+       }
+       heap_endscan(scan);
+       heap_close(pg_rel, AccessExclusiveLock);
+   }
 
    /*
     * Write the updated pg_shadow data to the flat password file.
     */
-    write_password_file(pg_shadow_rel);
+   write_password_file(pg_shadow_rel);
 
-    /*
-     * Now we can clean up.
-     */
-    heap_close(pg_shadow_rel, AccessExclusiveLock);
+   /*
+    * Now we can clean up.
+    */
+   heap_close(pg_shadow_rel, AccessExclusiveLock);
 }
 
 
@@ -609,7 +630,7 @@ CheckPgUserAclNotNull()
                               0, 0, 0);
    if (!HeapTupleIsValid(htup))
    {
-        /* BIG problem */
+       /* BIG problem */
        elog(ERROR, "IsPgUserAclNull: \"%s\" not found",
             ShadowRelationName);
    }
@@ -617,10 +638,10 @@ CheckPgUserAclNotNull()
    if (heap_attisnull(htup, Anum_pg_class_relacl))
    {
        elog(ERROR,
-             "To use passwords, you have to revoke permissions on %s "
-             "so normal users cannot read the passwords. "
-             "Try 'REVOKE ALL ON \"%s\" FROM PUBLIC'.",
-             ShadowRelationName, ShadowRelationName);
+            "To use passwords, you have to revoke permissions on %s "
+            "so normal users cannot read the passwords. "
+            "Try 'REVOKE ALL ON \"%s\" FROM PUBLIC'.",
+            ShadowRelationName, ShadowRelationName);
    }
 
    return;
@@ -637,14 +658,15 @@ CreateGroup(CreateGroupStmt *stmt)
    Relation    pg_group_rel;
    HeapScanDesc scan;
    HeapTuple   tuple;
-    TupleDesc   pg_group_dsc;
-    bool        group_exists = false,
-                sysid_exists = false;
-    int         max_id = 0;
-    Datum       new_record[Natts_pg_group];
-    char        new_record_nulls[Natts_pg_group];
-    List       *item, *newlist=NULL;
-    ArrayType  *userarray;
+   TupleDesc   pg_group_dsc;
+   bool        group_exists = false,
+               sysid_exists = false;
+   int         max_id = 0;
+   Datum       new_record[Natts_pg_group];
+   char        new_record_nulls[Natts_pg_group];
+   List       *item,
+              *newlist = NULL;
+   ArrayType  *userarray;
 
    /*
     * Make sure the user can do this.
@@ -652,12 +674,12 @@ CreateGroup(CreateGroupStmt *stmt)
    if (!superuser())
        elog(ERROR, "CREATE GROUP: permission denied");
 
-    /*
-     * There is not real reason for this, but it makes it consistent
-     * with create user, and it seems like a good idea anyway.
-     */
+   /*
+    * There is not real reason for this, but it makes it consistent with
+    * create user, and it seems like a good idea anyway.
+    */
    if (IsTransactionBlock())
-        elog(ERROR, "CREATE GROUP: may not be called in a transaction block");
+       elog(ERROR, "CREATE GROUP: may not be called in a transaction block");
 
 
    pg_group_rel = heap_openr(GroupRelationName, AccessExclusiveLock);
@@ -666,111 +688,111 @@ CreateGroup(CreateGroupStmt *stmt)
    scan = heap_beginscan(pg_group_rel, false, SnapshotNow, 0, NULL);
    while (!group_exists && !sysid_exists && HeapTupleIsValid(tuple = heap_getnext(scan, false)))
    {
-        Datum      datum;
-        bool        null;
+       Datum       datum;
+       bool        null;
 
        datum = heap_getattr(tuple, Anum_pg_group_groname, pg_group_dsc, &null);
        group_exists = datum && !null && (strcmp((char *) datum, stmt->name) == 0);
 
        datum = heap_getattr(tuple, Anum_pg_group_grosysid, pg_group_dsc, &null);
-        if (stmt->sysid >= 0) /* customized id wanted */
-            sysid_exists = datum && !null && ((int)datum == stmt->sysid);
-        else /* pick 1 + max */
-        {
-            if ((int) datum > max_id)
-                max_id = (int) datum;
-        }
+       if (stmt->sysid >= 0)   /* customized id wanted */
+           sysid_exists = datum && !null && ((int) datum == stmt->sysid);
+       else
+/* pick 1 + max */
+       {
+           if ((int) datum > max_id)
+               max_id = (int) datum;
+       }
    }
    heap_endscan(scan);
 
    if (group_exists || sysid_exists)
    {
        heap_close(pg_group_rel, AccessExclusiveLock);
-        if (group_exists)
-            elog(ERROR, "CREATE GROUP: group name \"%s\" already exists", stmt->name);
-        else
-            elog(ERROR, "CREATE GROUP: group sysid %d is already assigned", stmt->sysid);
+       if (group_exists)
+           elog(ERROR, "CREATE GROUP: group name \"%s\" already exists", stmt->name);
+       else
+           elog(ERROR, "CREATE GROUP: group sysid %d is already assigned", stmt->sysid);
    }
 
-    /*
-     * Translate the given user names to ids
-     */
-
-    foreach(item, stmt->initUsers)
-    {
-        const char * groupuser = strVal(lfirst(item));
-        Value *v;
-
-        tuple = SearchSysCacheTuple(SHADOWNAME,
-                                    PointerGetDatum(groupuser),
-                                    0, 0, 0);
-        if (!HeapTupleIsValid(tuple))
-        {
-            heap_close(pg_group_rel, AccessExclusiveLock);
-            elog(ERROR, "CREATE GROUP: user \"%s\" does not exist", groupuser);
-        }
-
-        v = makeInteger(((Form_pg_shadow) GETSTRUCT(tuple))->usesysid);
-        if (!member(v, newlist))
-            newlist = lcons(v, newlist);
-    }
-
-    /* build an array to insert */
-    if (newlist)
-    {
-        int i;
-
-        userarray = palloc(ARR_OVERHEAD(1) + length(newlist) * sizeof(int32));
-        ARR_SIZE(userarray) = ARR_OVERHEAD(1) + length(newlist) * sizeof(int32);
-        ARR_FLAGS(userarray) = 0x0;
-        ARR_NDIM(userarray) = 1; /* one dimensional array */
-        ARR_LBOUND(userarray)[0] = 1; /* axis starts at one */
-        ARR_DIMS(userarray)[0] = length(newlist); /* axis is this long */
-        /* fill the array */
-        i = 0;
-        foreach(item, newlist)
-        {
-            ((int*)ARR_DATA_PTR(userarray))[i++] = intVal(lfirst(item));
-        }
-    }
-    else
-        userarray = NULL;
-
-    /*
-     * Form a tuple to insert
-     */
-    if (stmt->sysid >=0)
-        max_id = stmt->sysid;
-    else 
-        max_id++;
-
-    new_record[Anum_pg_group_groname-1] = (Datum)(stmt->name);
-    new_record[Anum_pg_group_grosysid-1] = (Datum)(max_id);
-    new_record[Anum_pg_group_grolist-1] = (Datum)userarray;
-
-    new_record_nulls[Anum_pg_group_groname-1] = ' ';
-    new_record_nulls[Anum_pg_group_grosysid-1] = ' ';
-    new_record_nulls[Anum_pg_group_grolist-1] = userarray ? ' ' : 'n';
-
-    tuple = heap_formtuple(pg_group_dsc, new_record, new_record_nulls);
-
-    /*
-     * Insert a new record in the pg_group_table
-     */
-    heap_insert(pg_group_rel, tuple);
-
-    /*
-     * Update indexes
-     */
-    if (RelationGetForm(pg_group_rel)->relhasindex) {
-        Relation idescs[Num_pg_group_indices];
-      
-        CatalogOpenIndices(Num_pg_group_indices, 
-                           Name_pg_group_indices, idescs);
-        CatalogIndexInsert(idescs, Num_pg_group_indices, pg_group_rel, 
-                           tuple);
-        CatalogCloseIndices(Num_pg_group_indices, idescs);
-    }
+   /*
+    * Translate the given user names to ids
+    */
+
+   foreach(item, stmt->initUsers)
+   {
+       const char *groupuser = strVal(lfirst(item));
+       Value      *v;
+
+       tuple = SearchSysCacheTuple(SHADOWNAME,
+                                   PointerGetDatum(groupuser),
+                                   0, 0, 0);
+       if (!HeapTupleIsValid(tuple))
+       {
+           heap_close(pg_group_rel, AccessExclusiveLock);
+           elog(ERROR, "CREATE GROUP: user \"%s\" does not exist", groupuser);
+       }
+
+       v = makeInteger(((Form_pg_shadow) GETSTRUCT(tuple))->usesysid);
+       if (!member(v, newlist))
+           newlist = lcons(v, newlist);
+   }
+
+   /* build an array to insert */
+   if (newlist)
+   {
+       int         i;
+
+       userarray = palloc(ARR_OVERHEAD(1) + length(newlist) * sizeof(int32));
+       ARR_SIZE(userarray) = ARR_OVERHEAD(1) + length(newlist) * sizeof(int32);
+       ARR_FLAGS(userarray) = 0x0;
+       ARR_NDIM(userarray) = 1;/* one dimensional array */
+       ARR_LBOUND(userarray)[0] = 1;   /* axis starts at one */
+       ARR_DIMS(userarray)[0] = length(newlist);       /* axis is this long */
+       /* fill the array */
+       i = 0;
+       foreach(item, newlist)
+           ((int *) ARR_DATA_PTR(userarray))[i++] = intVal(lfirst(item));
+   }
+   else
+       userarray = NULL;
+
+   /*
+    * Form a tuple to insert
+    */
+   if (stmt->sysid >= 0)
+       max_id = stmt->sysid;
+   else
+       max_id++;
+
+   new_record[Anum_pg_group_groname - 1] = (Datum) (stmt->name);
+   new_record[Anum_pg_group_grosysid - 1] = (Datum) (max_id);
+   new_record[Anum_pg_group_grolist - 1] = (Datum) userarray;
+
+   new_record_nulls[Anum_pg_group_groname - 1] = ' ';
+   new_record_nulls[Anum_pg_group_grosysid - 1] = ' ';
+   new_record_nulls[Anum_pg_group_grolist - 1] = userarray ? ' ' : 'n';
+
+   tuple = heap_formtuple(pg_group_dsc, new_record, new_record_nulls);
+
+   /*
+    * Insert a new record in the pg_group_table
+    */
+   heap_insert(pg_group_rel, tuple);
+
+   /*
+    * Update indexes
+    */
+   if (RelationGetForm(pg_group_rel)->relhasindex)
+   {
+       Relation    idescs[Num_pg_group_indices];
+
+       CatalogOpenIndices(Num_pg_group_indices,
+                          Name_pg_group_indices, idescs);
+       CatalogIndexInsert(idescs, Num_pg_group_indices, pg_group_rel,
+                          tuple);
+       CatalogCloseIndices(Num_pg_group_indices, idescs);
+   }
 
    heap_close(pg_group_rel, AccessExclusiveLock);
 }
@@ -781,258 +803,272 @@ CreateGroup(CreateGroupStmt *stmt)
  * ALTER GROUP
  */
 void
-AlterGroup(AlterGroupStmt *stmt, const char * tag)
+AlterGroup(AlterGroupStmt *stmt, const char *tag)
 {
    Relation    pg_group_rel;
-    TupleDesc   pg_group_dsc;
-    HeapTuple   group_tuple;
+   TupleDesc   pg_group_dsc;
+   HeapTuple   group_tuple;
 
-    /*
+   /*
     * Make sure the user can do this.
     */
    if (!superuser())
        elog(ERROR, "%s: permission denied", tag);
 
-    /*
-     * There is not real reason for this, but it makes it consistent
-     * with alter user, and it seems like a good idea anyway.
-     */
+   /*
+    * There is not real reason for this, but it makes it consistent with
+    * alter user, and it seems like a good idea anyway.
+    */
    if (IsTransactionBlock())
-        elog(ERROR, "%s: may not be called in a transaction block", tag);
+       elog(ERROR, "%s: may not be called in a transaction block", tag);
 
 
-    pg_group_rel = heap_openr(GroupRelationName, AccessExclusiveLock);
-    pg_group_dsc = RelationGetDescr(pg_group_rel);
+   pg_group_rel = heap_openr(GroupRelationName, AccessExclusiveLock);
+   pg_group_dsc = RelationGetDescr(pg_group_rel);
 
-    /*
-     * Verify that group exists.
-     * If we find a tuple, will take that the rest of the way and make our
-     * modifications on it.
-     */
-    if (!HeapTupleIsValid(group_tuple = SearchSysCacheTupleCopy(GRONAME, PointerGetDatum(stmt->name), 0, 0, 0)))
+   /*
+    * Verify that group exists. If we find a tuple, will take that the
+    * rest of the way and make our modifications on it.
+    */
+   if (!HeapTupleIsValid(group_tuple = SearchSysCacheTupleCopy(GRONAME, PointerGetDatum(stmt->name), 0, 0, 0)))
    {
-        heap_close(pg_group_rel, AccessExclusiveLock);
+       heap_close(pg_group_rel, AccessExclusiveLock);
        elog(ERROR, "%s: group \"%s\" does not exist", tag, stmt->name);
    }
 
-    AssertState(stmt->action == +1 || stmt->action == -1);
-    /*
-     * Now decide what to do.
-     */
-    if (stmt->action == +1) /* add users, might also be invoked by create user */
-    {
-        Datum       new_record[Natts_pg_group];
-        char        new_record_nulls[Natts_pg_group] = { ' ', ' ', ' '};
-        ArrayType *newarray, *oldarray;
-        List * newlist = NULL, *item;
-        HeapTuple tuple;
-        bool null = false;
-        Datum datum = heap_getattr(group_tuple, Anum_pg_group_grolist, pg_group_dsc, &null);
-        int i;
-        
-        oldarray = (ArrayType*)datum;
-        Assert(null || ARR_NDIM(oldarray) == 1);
-        /* first add the old array to the hitherto empty list */
-        if (!null)
-            for (i = ARR_LBOUND(oldarray)[0]; i < ARR_LBOUND(oldarray)[0] + ARR_DIMS(oldarray)[0]; i++)
-            {
-                int index, arrval;
-                Value *v;
-                bool valueNull;
-                index = i;
-                arrval = DatumGetInt32(array_ref(oldarray, 1, &index, true/*by value*/,
-                                                 sizeof(int), 0, &valueNull));
-                v = makeInteger(arrval);
-                /* filter out duplicates */
-                if (!member(v, newlist))
-                    newlist = lcons(v, newlist);
-            }
-
-        /* 
-         * now convert the to be added usernames to sysids and add them
-         * to the list
-         */
-        foreach(item, stmt->listUsers)
-        {
-            Value *v;
-
-            if (strcmp(tag, "ALTER GROUP")==0)
-            {
-                /* Get the uid of the proposed user to add. */
-                tuple = SearchSysCacheTuple(SHADOWNAME,
-                                            PointerGetDatum(strVal(lfirst(item))),
-                                            0, 0, 0);
-                if (!HeapTupleIsValid(tuple))
-                {
-                    heap_close(pg_group_rel, AccessExclusiveLock);
-                    elog(ERROR, "%s: user \"%s\" does not exist", tag, strVal(lfirst(item)));
-                }
-                v = makeInteger(((Form_pg_shadow) GETSTRUCT(tuple))->usesysid);
-            }
-            else if (strcmp(tag, "CREATE USER")==0)
-            {
-                /* in this case we already know the uid and it wouldn't
-                   be in the cache anyway yet */
-                v = lfirst(item);
-            }
-            else
+   AssertState(stmt->action == +1 || stmt->action == -1);
+
+   /*
+    * Now decide what to do.
+    */
+   if (stmt->action == +1)     /* add users, might also be invoked by
+                                * create user */
+   {
+       Datum       new_record[Natts_pg_group];
+       char        new_record_nulls[Natts_pg_group] = {' ', ' ', ' '};
+       ArrayType  *newarray,
+                  *oldarray;
+       List       *newlist = NULL,
+                  *item;
+       HeapTuple   tuple;
+       bool        null = false;
+       Datum       datum = heap_getattr(group_tuple, Anum_pg_group_grolist, pg_group_dsc, &null);
+       int         i;
+
+       oldarray = (ArrayType *) datum;
+       Assert(null || ARR_NDIM(oldarray) == 1);
+       /* first add the old array to the hitherto empty list */
+       if (!null)
+           for (i = ARR_LBOUND(oldarray)[0]; i < ARR_LBOUND(oldarray)[0] + ARR_DIMS(oldarray)[0]; i++)
+           {
+               int         index,
+                           arrval;
+               Value      *v;
+               bool        valueNull;
+
+               index = i;
+               arrval = DatumGetInt32(array_ref(oldarray, 1, &index, true /* by value */ ,
+                                           sizeof(int), 0, &valueNull));
+               v = makeInteger(arrval);
+               /* filter out duplicates */
+               if (!member(v, newlist))
+                   newlist = lcons(v, newlist);
+           }
+
+       /*
+        * now convert the to be added usernames to sysids and add them to
+        * the list
+        */
+       foreach(item, stmt->listUsers)
+       {
+           Value      *v;
+
+           if (strcmp(tag, "ALTER GROUP") == 0)
+           {
+               /* Get the uid of the proposed user to add. */
+               tuple = SearchSysCacheTuple(SHADOWNAME,
+                                  PointerGetDatum(strVal(lfirst(item))),
+                                           0, 0, 0);
+               if (!HeapTupleIsValid(tuple))
+               {
+                   heap_close(pg_group_rel, AccessExclusiveLock);
+                   elog(ERROR, "%s: user \"%s\" does not exist", tag, strVal(lfirst(item)));
+               }
+               v = makeInteger(((Form_pg_shadow) GETSTRUCT(tuple))->usesysid);
+           }
+           else if (strcmp(tag, "CREATE USER") == 0)
            {
-                elog(ERROR, "AlterGroup: unknown tag %s", tag);
+
+               /*
+                * in this case we already know the uid and it wouldn't be
+                * in the cache anyway yet
+                */
+               v = lfirst(item);
+           }
+           else
+           {
+               elog(ERROR, "AlterGroup: unknown tag %s", tag);
                v = NULL;       /* keep compiler quiet */
            }
 
-            if (!member(v, newlist))
-                newlist = lcons(v, newlist);
-            else
-                /* we silently assume here that this error will only come up
-                   in a ALTER GROUP statement */
-                elog(NOTICE, "%s: user \"%s\" is already in group \"%s\"", tag, strVal(lfirst(item)), stmt->name);
-        }
-             
-        newarray = palloc(ARR_OVERHEAD(1) + length(newlist) * sizeof(int32));
-        ARR_SIZE(newarray) = ARR_OVERHEAD(1) + length(newlist) * sizeof(int32);
-        ARR_FLAGS(newarray) = 0x0;
-        ARR_NDIM(newarray) = 1; /* one dimensional array */
-        ARR_LBOUND(newarray)[0] = 1; /* axis starts at one */
-        ARR_DIMS(newarray)[0] = length(newlist); /* axis is this long */
-        /* fill the array */
-        i = 0;
-        foreach(item, newlist)
-        {
-            ((int*)ARR_DATA_PTR(newarray))[i++] = intVal(lfirst(item));
-        }
-        
-        /*
-         * Form a tuple with the new array and write it back.
-         */
-        new_record[Anum_pg_group_groname-1] = (Datum)(stmt->name);
-        new_record[Anum_pg_group_grosysid-1] = heap_getattr(group_tuple, Anum_pg_group_grosysid, pg_group_dsc, &null);
-        new_record[Anum_pg_group_grolist-1] = PointerGetDatum(newarray);
-
-        tuple = heap_formtuple(pg_group_dsc, new_record, new_record_nulls);
-        heap_update(pg_group_rel, &group_tuple->t_self, tuple, NULL);
-
-        /* Update indexes */
-        if (RelationGetForm(pg_group_rel)->relhasindex) {
-            Relation idescs[Num_pg_group_indices];
-      
-            CatalogOpenIndices(Num_pg_group_indices, 
-                               Name_pg_group_indices, idescs);
-            CatalogIndexInsert(idescs, Num_pg_group_indices, pg_group_rel, 
-                               tuple);
-            CatalogCloseIndices(Num_pg_group_indices, idescs);
-        }
-    } /* endif alter group add user */
-
-    else if (stmt->action == -1) /*drop users from group */
-    {
-        Datum         datum;
-        bool          null;
-        bool          is_dropuser = strcmp(tag, "DROP USER")==0;
-        
-        datum = heap_getattr(group_tuple, Anum_pg_group_grolist, pg_group_dsc, &null);
-        if (null)
-        {
-            if (!is_dropuser)
-                elog(NOTICE, "ALTER GROUP: group \"%s\" does not have any members", stmt->name);
-        }
-        else
-        {
-            HeapTuple    tuple;
-            Datum       new_record[Natts_pg_group];
-            char        new_record_nulls[Natts_pg_group] = { ' ', ' ', ' '};
-            ArrayType    *oldarray, *newarray;
-            List * newlist = NULL, *item;
-            int i;
-
-            oldarray = (ArrayType*)datum;
-            Assert(ARR_NDIM(oldarray) == 1);
-            /* first add the old array to the hitherto empty list */
-            for (i = ARR_LBOUND(oldarray)[0]; i < ARR_LBOUND(oldarray)[0] + ARR_DIMS(oldarray)[0]; i++)
-            {
-                int index, arrval;
-                Value *v;
-                bool valueNull;
-                index = i;
-                arrval = DatumGetInt32(array_ref(oldarray, 1, &index, true/*by value*/,
-                                                 sizeof(int), 0, &valueNull));
-                v = makeInteger(arrval);
-                /* filter out duplicates */
-                if (!member(v, newlist))
-                    newlist = lcons(v, newlist);
-            }
-
-            /* 
-             * now convert the to be dropped usernames to sysids and remove
-             * them from the list
-             */
-            foreach(item, stmt->listUsers)
-            {
-                Value *v;
-                if (!is_dropuser)
-                {
-                    /* Get the uid of the proposed user to drop. */
-                    tuple = SearchSysCacheTuple(SHADOWNAME,
-                                                PointerGetDatum(strVal(lfirst(item))),
-                                                0, 0, 0);
-                    if (!HeapTupleIsValid(tuple))
-                    {
-                        heap_close(pg_group_rel, AccessExclusiveLock);
-                        elog(ERROR, "ALTER GROUP: user \"%s\" does not exist", strVal(lfirst(item)));
-                    }
-                    v = makeInteger(((Form_pg_shadow) GETSTRUCT(tuple))->usesysid);
-                }
-                else
-                {
-                    /* for dropuser we already know the uid */
-                    v = lfirst(item);
-                }
-                if (member(v, newlist))
-                    newlist = LispRemove(v, newlist);
-                else if (!is_dropuser)
-                    elog(NOTICE, "ALTER GROUP: user \"%s\" is not in group \"%s\"", strVal(lfirst(item)), stmt->name);
-            }
-
-            newarray = palloc(ARR_OVERHEAD(1) + length(newlist) * sizeof(int32));
-            ARR_SIZE(newarray) = ARR_OVERHEAD(1) + length(newlist) * sizeof(int32);
-            ARR_FLAGS(newarray) = 0x0;
-            ARR_NDIM(newarray) = 1; /* one dimensional array */
-            ARR_LBOUND(newarray)[0] = 1; /* axis starts at one */
-            ARR_DIMS(newarray)[0] = length(newlist); /* axis is this long */
-            /* fill the array */
-            i = 0;
-            foreach(item, newlist)
-            {
-                ((int*)ARR_DATA_PTR(newarray))[i++] = intVal(lfirst(item));
-            }
-        
-            /*
-             * Insert the new tuple with the updated user list
-             */
-            new_record[Anum_pg_group_groname-1] = (Datum)(stmt->name);
-            new_record[Anum_pg_group_grosysid-1] = heap_getattr(group_tuple, Anum_pg_group_grosysid, pg_group_dsc, &null);
-            new_record[Anum_pg_group_grolist-1] = PointerGetDatum(newarray);
-
-            tuple = heap_formtuple(pg_group_dsc, new_record, new_record_nulls);
-            heap_update(pg_group_rel, &group_tuple->t_self, tuple, NULL);
-
-            /* Update indexes */
-            if (RelationGetForm(pg_group_rel)->relhasindex) {
-                Relation idescs[Num_pg_group_indices];
-      
-                CatalogOpenIndices(Num_pg_group_indices, 
-                                   Name_pg_group_indices, idescs);
-                CatalogIndexInsert(idescs, Num_pg_group_indices, pg_group_rel, 
-                                   tuple);
-                CatalogCloseIndices(Num_pg_group_indices, idescs);
-            }
-
-        } /* endif group not null */
-    } /* endif alter group drop user */
-
-    heap_close(pg_group_rel, AccessExclusiveLock);
-
-    pfree(group_tuple);
+           if (!member(v, newlist))
+               newlist = lcons(v, newlist);
+           else
+
+               /*
+                * we silently assume here that this error will only come
+                * up in a ALTER GROUP statement
+                */
+               elog(NOTICE, "%s: user \"%s\" is already in group \"%s\"", tag, strVal(lfirst(item)), stmt->name);
+       }
+
+       newarray = palloc(ARR_OVERHEAD(1) + length(newlist) * sizeof(int32));
+       ARR_SIZE(newarray) = ARR_OVERHEAD(1) + length(newlist) * sizeof(int32);
+       ARR_FLAGS(newarray) = 0x0;
+       ARR_NDIM(newarray) = 1; /* one dimensional array */
+       ARR_LBOUND(newarray)[0] = 1;    /* axis starts at one */
+       ARR_DIMS(newarray)[0] = length(newlist);        /* axis is this long */
+       /* fill the array */
+       i = 0;
+       foreach(item, newlist)
+           ((int *) ARR_DATA_PTR(newarray))[i++] = intVal(lfirst(item));
+
+       /*
+        * Form a tuple with the new array and write it back.
+        */
+       new_record[Anum_pg_group_groname - 1] = (Datum) (stmt->name);
+       new_record[Anum_pg_group_grosysid - 1] = heap_getattr(group_tuple, Anum_pg_group_grosysid, pg_group_dsc, &null);
+       new_record[Anum_pg_group_grolist - 1] = PointerGetDatum(newarray);
+
+       tuple = heap_formtuple(pg_group_dsc, new_record, new_record_nulls);
+       heap_update(pg_group_rel, &group_tuple->t_self, tuple, NULL);
+
+       /* Update indexes */
+       if (RelationGetForm(pg_group_rel)->relhasindex)
+       {
+           Relation    idescs[Num_pg_group_indices];
+
+           CatalogOpenIndices(Num_pg_group_indices,
+                              Name_pg_group_indices, idescs);
+           CatalogIndexInsert(idescs, Num_pg_group_indices, pg_group_rel,
+                              tuple);
+           CatalogCloseIndices(Num_pg_group_indices, idescs);
+       }
+   }                           /* endif alter group add user */
+
+   else if (stmt->action == -1)/* drop users from group */
+   {
+       Datum       datum;
+       bool        null;
+       bool        is_dropuser = strcmp(tag, "DROP USER") == 0;
+
+       datum = heap_getattr(group_tuple, Anum_pg_group_grolist, pg_group_dsc, &null);
+       if (null)
+       {
+           if (!is_dropuser)
+               elog(NOTICE, "ALTER GROUP: group \"%s\" does not have any members", stmt->name);
+       }
+       else
+       {
+           HeapTuple   tuple;
+           Datum       new_record[Natts_pg_group];
+           char        new_record_nulls[Natts_pg_group] = {' ', ' ', ' '};
+           ArrayType  *oldarray,
+                      *newarray;
+           List       *newlist = NULL,
+                      *item;
+           int         i;
+
+           oldarray = (ArrayType *) datum;
+           Assert(ARR_NDIM(oldarray) == 1);
+           /* first add the old array to the hitherto empty list */
+           for (i = ARR_LBOUND(oldarray)[0]; i < ARR_LBOUND(oldarray)[0] + ARR_DIMS(oldarray)[0]; i++)
+           {
+               int         index,
+                           arrval;
+               Value      *v;
+               bool        valueNull;
+
+               index = i;
+               arrval = DatumGetInt32(array_ref(oldarray, 1, &index, true /* by value */ ,
+                                           sizeof(int), 0, &valueNull));
+               v = makeInteger(arrval);
+               /* filter out duplicates */
+               if (!member(v, newlist))
+                   newlist = lcons(v, newlist);
+           }
+
+           /*
+            * now convert the to be dropped usernames to sysids and
+            * remove them from the list
+            */
+           foreach(item, stmt->listUsers)
+           {
+               Value      *v;
+
+               if (!is_dropuser)
+               {
+                   /* Get the uid of the proposed user to drop. */
+                   tuple = SearchSysCacheTuple(SHADOWNAME,
+                                  PointerGetDatum(strVal(lfirst(item))),
+                                               0, 0, 0);
+                   if (!HeapTupleIsValid(tuple))
+                   {
+                       heap_close(pg_group_rel, AccessExclusiveLock);
+                       elog(ERROR, "ALTER GROUP: user \"%s\" does not exist", strVal(lfirst(item)));
+                   }
+                   v = makeInteger(((Form_pg_shadow) GETSTRUCT(tuple))->usesysid);
+               }
+               else
+               {
+                   /* for dropuser we already know the uid */
+                   v = lfirst(item);
+               }
+               if (member(v, newlist))
+                   newlist = LispRemove(v, newlist);
+               else if (!is_dropuser)
+                   elog(NOTICE, "ALTER GROUP: user \"%s\" is not in group \"%s\"", strVal(lfirst(item)), stmt->name);
+           }
+
+           newarray = palloc(ARR_OVERHEAD(1) + length(newlist) * sizeof(int32));
+           ARR_SIZE(newarray) = ARR_OVERHEAD(1) + length(newlist) * sizeof(int32);
+           ARR_FLAGS(newarray) = 0x0;
+           ARR_NDIM(newarray) = 1;     /* one dimensional array */
+           ARR_LBOUND(newarray)[0] = 1;        /* axis starts at one */
+           ARR_DIMS(newarray)[0] = length(newlist);    /* axis is this long */
+           /* fill the array */
+           i = 0;
+           foreach(item, newlist)
+               ((int *) ARR_DATA_PTR(newarray))[i++] = intVal(lfirst(item));
+
+           /*
+            * Insert the new tuple with the updated user list
+            */
+           new_record[Anum_pg_group_groname - 1] = (Datum) (stmt->name);
+           new_record[Anum_pg_group_grosysid - 1] = heap_getattr(group_tuple, Anum_pg_group_grosysid, pg_group_dsc, &null);
+           new_record[Anum_pg_group_grolist - 1] = PointerGetDatum(newarray);
+
+           tuple = heap_formtuple(pg_group_dsc, new_record, new_record_nulls);
+           heap_update(pg_group_rel, &group_tuple->t_self, tuple, NULL);
+
+           /* Update indexes */
+           if (RelationGetForm(pg_group_rel)->relhasindex)
+           {
+               Relation    idescs[Num_pg_group_indices];
+
+               CatalogOpenIndices(Num_pg_group_indices,
+                                  Name_pg_group_indices, idescs);
+               CatalogIndexInsert(idescs, Num_pg_group_indices, pg_group_rel,
+                                  tuple);
+               CatalogCloseIndices(Num_pg_group_indices, idescs);
+           }
+
+       }                       /* endif group not null */
+   }                           /* endif alter group drop user */
+
+   heap_close(pg_group_rel, AccessExclusiveLock);
+
+   pfree(group_tuple);
 }
 
 
@@ -1046,52 +1082,52 @@ DropGroup(DropGroupStmt *stmt)
    Relation    pg_group_rel;
    HeapScanDesc scan;
    HeapTuple   tuple;
-    TupleDesc   pg_group_dsc;
-    bool        gro_exists = false;
+   TupleDesc   pg_group_dsc;
+   bool        gro_exists = false;
 
-    /*
+   /*
     * Make sure the user can do this.
     */
    if (!superuser())
        elog(ERROR, "DROP GROUP: permission denied");
 
-    /*
-     * There is not real reason for this, but it makes it consistent
-     * with drop user, and it seems like a good idea anyway.
-     */
+   /*
+    * There is not real reason for this, but it makes it consistent with
+    * drop user, and it seems like a good idea anyway.
+    */
    if (IsTransactionBlock())
-        elog(ERROR, "DROP GROUP: may not be called in a transaction block");
+       elog(ERROR, "DROP GROUP: may not be called in a transaction block");
 
-    /*
-     * Scan the pg_group table and delete all matching groups.
-     */
+   /*
+    * Scan the pg_group table and delete all matching groups.
+    */
    pg_group_rel = heap_openr(GroupRelationName, AccessExclusiveLock);
    pg_group_dsc = RelationGetDescr(pg_group_rel);
    scan = heap_beginscan(pg_group_rel, false, SnapshotNow, 0, NULL);
 
    while (HeapTupleIsValid(tuple = heap_getnext(scan, false)))
    {
-        Datum datum;
-        bool null;
-
-        datum = heap_getattr(tuple, Anum_pg_group_groname, pg_group_dsc, &null);
-        if (datum && !null && strcmp((char*)datum, stmt->name)==0)
-        {
-            gro_exists = true;
-            heap_delete(pg_group_rel, &tuple->t_self, NULL);
-        }
+       Datum       datum;
+       bool        null;
+
+       datum = heap_getattr(tuple, Anum_pg_group_groname, pg_group_dsc, &null);
+       if (datum && !null && strcmp((char *) datum, stmt->name) == 0)
+       {
+           gro_exists = true;
+           heap_delete(pg_group_rel, &tuple->t_self, NULL);
+       }
    }
 
    heap_endscan(scan);
 
-    /*
-     * Did we find any?
-     */
-    if (!gro_exists)
-    {
-        heap_close(pg_group_rel, AccessExclusiveLock);
+   /*
+    * Did we find any?
+    */
+   if (!gro_exists)
+   {
+       heap_close(pg_group_rel, AccessExclusiveLock);
        elog(ERROR, "DROP GROUP: group \"%s\" does not exist", stmt->name);
-    }
+   }
 
    heap_close(pg_group_rel, AccessExclusiveLock);
 }
index 5c300c69398935a6333dfbc24ce370fafb4d816b..834438b798651ca181e577b23f72b739aaaad139 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.146 2000/04/06 18:12:07 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.147 2000/04/12 17:14:59 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -102,15 +102,17 @@ static char *vc_show_rusage(struct rusage * ru0);
 
 /*
  * This routines handle a special cross-transaction portal.
- * However it is automatically closed in case of abort. 
+ * However it is automatically closed in case of abort.
  */
-void CommonSpecialPortalOpen(void)
+void
+CommonSpecialPortalOpen(void)
 {
    char       *pname;
 
 
    if (CommonSpecialPortalInUse)
        elog(ERROR, "CommonSpecialPortal is in use");
+
    /*
     * Create a portal for safe memory across transactions. We need to
     * palloc the name space for it because our hash function expects the
@@ -130,7 +132,8 @@ void CommonSpecialPortalOpen(void)
    CommonSpecialPortalInUse = true;
 }
 
-void CommonSpecialPortalClose(void)
+void
+CommonSpecialPortalClose(void)
 {
    /* Clear flag first, to avoid recursion if PortalDrop elog's */
    CommonSpecialPortalInUse = false;
@@ -141,16 +144,18 @@ void CommonSpecialPortalClose(void)
    PortalDrop(&vc_portal);
 }
 
-PortalVariableMemory CommonSpecialPortalGetMemory(void)
+PortalVariableMemory
+CommonSpecialPortalGetMemory(void)
 {
    return PortalGetVariableMemory(vc_portal);
 }
 
-bool CommonSpecialPortalIsOpen(void)
+bool
+CommonSpecialPortalIsOpen(void)
 {
    return CommonSpecialPortalInUse;
-} 
+}
+
 void
 vacuum(char *vacrel, bool verbose, bool analyze, List *va_spec)
 {
@@ -208,9 +213,9 @@ vacuum(char *vacrel, bool verbose, bool analyze, List *va_spec)
     * Start up the vacuum cleaner.
     *
     * NOTE: since this commits the current transaction, the memory holding
-    * any passed-in parameters gets freed here.  We must have already copied
-    * pass-by-reference parameters to safe storage.  Don't make me fix this
-    * again!
+    * any passed-in parameters gets freed here.  We must have already
+    * copied pass-by-reference parameters to safe storage.  Don't make me
+    * fix this again!
     */
    vc_init();
 
@@ -316,11 +321,12 @@ vc_getrels(NameData *VacRelP)
 
    if (NameStr(*VacRelP))
    {
+
        /*
         * we could use the cache here, but it is clearer to use scankeys
         * for both vacuum cases, bjm 2000/01/19
         */
-       char *nontemp_relname;
+       char       *nontemp_relname;
 
        /* We must re-map temp table names bjm 2000-04-06 */
        if ((nontemp_relname =
@@ -414,7 +420,7 @@ vc_vacone(Oid relid, bool analyze, List *va_cols)
    int32       nindices,
                i;
    VRelStats  *vacrelstats;
-   bool       reindex = false;
+   bool        reindex = false;
 
    StartTransactionCommand();
 
@@ -678,7 +684,7 @@ static void
 vc_scanheap(VRelStats *vacrelstats, Relation onerel,
            VPageList vacuum_pages, VPageList fraged_pages)
 {
-   BlockNumber nblocks,
+   BlockNumber nblocks,
                blkno;
    ItemId      itemid;
    Buffer      buf;
@@ -1201,7 +1207,7 @@ vc_repair_frag(VRelStats *vacrelstats, Relation onerel,
                last_vacuum_block = -1;
            }
            if (num_fraged_pages > 0 &&
-               fraged_pages->vpl_pagedesc[num_fraged_pages - 1]->vpd_blkno ==
+           fraged_pages->vpl_pagedesc[num_fraged_pages - 1]->vpd_blkno ==
                (BlockNumber) blkno)
            {
                /* page is in fraged_pages too; remove it */
@@ -1456,8 +1462,8 @@ vc_repair_frag(VRelStats *vacrelstats, Relation onerel,
                         * we stop shrinking here. I could try to find
                         * real parent row but want not to do it because
                         * of real solution will be implemented anyway,
-                        * latter, and we are too close to 6.5 release.
-                        * vadim 06/11/99
+                        * latter, and we are too close to 6.5 release. -
+                        * vadim 06/11/99
                         */
                        if (Ptp.t_data->t_xmax != tp.t_data->t_xmin)
                        {
@@ -1539,20 +1545,23 @@ vc_repair_frag(VRelStats *vacrelstats, Relation onerel,
                     * to get t_infomask of inserted heap tuple !!!
                     */
                    ToPage = BufferGetPage(cur_buffer);
+
                    /*
                     * If this page was not used before - clean it.
                     *
                     * This path is different from the other callers of
                     * vc_vacpage, because we have already incremented the
                     * vpd's vpd_offsets_used field to account for the
-                    * tuple(s) we expect to move onto the page.  Therefore
-                    * vc_vacpage's check for vpd_offsets_used == 0 is wrong.
-                    * But since that's a good debugging check for all other
-                    * callers, we work around it here rather than remove it.
+                    * tuple(s) we expect to move onto the page. Therefore
+                    * vc_vacpage's check for vpd_offsets_used == 0 is
+                    * wrong. But since that's a good debugging check for
+                    * all other callers, we work around it here rather
+                    * than remove it.
                     */
                    if (!PageIsEmpty(ToPage) && vtmove[ti].cleanVpd)
                    {
-                       int sv_offsets_used = destvpd->vpd_offsets_used;
+                       int         sv_offsets_used = destvpd->vpd_offsets_used;
+
                        destvpd->vpd_offsets_used = 0;
                        vc_vacpage(ToPage, destvpd);
                        destvpd->vpd_offsets_used = sv_offsets_used;
@@ -2267,7 +2276,7 @@ vc_attrstats(Relation onerel, VRelStats *vacrelstats, HeapTuple tuple)
 #ifdef _DROP_COLUMN_HACK__
        if (COLUMN_IS_DROPPED(stats->attr))
            continue;
-#endif /* _DROP_COLUMN_HACK__ */
+#endif  /* _DROP_COLUMN_HACK__ */
        value = heap_getattr(tuple,
                             stats->attr->attnum, tupDesc, &isnull);
 
index 6432d3c2b8f7e76ed2a7768c97d1e953a47cd576..367b17aa64c52e3e35373faf17f0795b4f8b7131 100644 (file)
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.33 2000/04/07 13:39:24 thomas Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.34 2000/04/12 17:15:00 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -436,7 +436,7 @@ parse_geqo(char *value)
 
    if (strcasecmp(tok, "on") == 0)
    {
-       int     new_geqo_rels = GEQO_RELS;
+       int         new_geqo_rels = GEQO_RELS;
 
        if (val != NULL)
        {
@@ -505,7 +505,7 @@ static bool
 show_effective_cache_size()
 {
    elog(NOTICE, "EFFECTIVE_CACHE_SIZE is %g (%dK pages)",
-        effective_cache_size, BLCKSZ/1024);
+        effective_cache_size, BLCKSZ / 1024);
    return TRUE;
 }
 
@@ -656,12 +656,12 @@ reset_cpu_operator_cost()
  * DATE_STYLE
  *
  * NOTE: set_default_datestyle() is called during backend startup to check
- * if the PGDATESTYLE environment variable is set.  We want the env var
+ * if the PGDATESTYLE environment variable is set. We want the env var
  * to determine the value that "RESET DateStyle" will reset to!
  */
 
 /* These get initialized from the "master" values in init/globals.c */
-static int DefaultDateStyle;
+static int DefaultDateStyle;
 static bool DefaultEuroDates;
 
 static bool
@@ -777,8 +777,9 @@ set_default_datestyle(void)
 {
    char       *DBDate;
 
-   /* Initialize from compile-time defaults in init/globals.c.
-    * NB: this is a necessary step; consider PGDATESTYLE="DEFAULT".
+   /*
+    * Initialize from compile-time defaults in init/globals.c. NB: this
+    * is a necessary step; consider PGDATESTYLE="DEFAULT".
     */
    DefaultDateStyle = DateStyle;
    DefaultEuroDates = EuroDates;
@@ -788,9 +789,11 @@ set_default_datestyle(void)
    if (DBDate == NULL)
        return;
 
-   /* Make a modifiable copy --- overwriting the env var doesn't seem
+   /*
+    * Make a modifiable copy --- overwriting the env var doesn't seem
     * like a good idea, even though we currently won't look at it again.
-    * Note that we cannot use palloc at this early stage of initialization.
+    * Note that we cannot use palloc at this early stage of
+    * initialization.
     */
    DBDate = strdup(DBDate);
 
@@ -1041,9 +1044,8 @@ reset_XactIsoLevel()
 static bool
 parse_pg_options(char *value)
 {
-   if (!superuser()) {
+   if (!superuser())
        elog(ERROR, "Only users with superuser privilege can set pg_options");
-   }
    if (value == NULL)
        read_pg_options(0);
    else
@@ -1061,9 +1063,8 @@ show_pg_options(void)
 static bool
 reset_pg_options(void)
 {
-   if (!superuser()) {
+   if (!superuser())
        elog(ERROR, "Only users with superuser privilege can set pg_options");
-   }
    read_pg_options(0);
    return (TRUE);
 }
@@ -1075,7 +1076,7 @@ reset_pg_options(void)
 static bool
 parse_random_seed(char *value)
 {
-   double seed = 0;
+   double      seed = 0;
 
    if (value == NULL)
        reset_random_seed();
@@ -1097,7 +1098,7 @@ show_random_seed(void)
 static bool
 reset_random_seed(void)
 {
-   double seed = 0.5;
+   double      seed = 0.5;
 
    setseed(&seed);
    return (TRUE);
index cdde7c198015fed2b1e18005d2ee76d19b80c892..579465bf0b8916d11842e8c611319e602ebf709d 100644 (file)
@@ -6,7 +6,7 @@
  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- * $Id: execAmi.c,v 1.45 2000/01/26 05:56:21 momjian Exp $
+ * $Id: execAmi.c,v 1.46 2000/04/12 17:15:07 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -235,9 +235,10 @@ ExecCloseR(Plan *node)
        heap_endscan(scanDesc);
 
    /*
-    * endscan released AccessShareLock acquired by beginscan.  If we are
-    * holding any stronger locks on the rel, they should be held till end of
-    * xact.  Therefore, we need only close the rel and not release locks.
+    * endscan released AccessShareLock acquired by beginscan.  If we are
+    * holding any stronger locks on the rel, they should be held till end
+    * of xact.  Therefore, we need only close the rel and not release
+    * locks.
     */
    if (relation != NULL)
        heap_close(relation, NoLock);
@@ -423,7 +424,7 @@ ExecMarkPos(Plan *node)
 {
    switch (nodeTag(node))
    {
-       case T_SeqScan:
+           case T_SeqScan:
            ExecSeqMarkPos((SeqScan *) node);
            break;
 
index bbcba0fbc12c7db2f78001d2082856ab5db4e2aa..c879417baf6df0eeb887acc55325397700ae46e8 100644 (file)
@@ -27,7 +27,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.112 2000/04/07 07:24:47 vadim Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.113 2000/04/12 17:15:08 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -48,7 +48,7 @@
 
 /* XXX no points for style */
 extern TupleTableSlot *EvalPlanQual(EState *estate, Index rti,
-                                   ItemPointer tid);
+            ItemPointer tid);
 
 /* decls for local routines only used within this module */
 static TupleDesc InitPlan(CmdType operation,
@@ -75,13 +75,14 @@ static void ExecReplace(TupleTableSlot *slot, ItemPointer tupleid,
 static TupleTableSlot *EvalPlanQualNext(EState *estate);
 static void EndEvalPlanQual(EState *estate);
 static void ExecCheckQueryPerms(CmdType operation, Query *parseTree,
-                               Plan *plan);
+                   Plan *plan);
 static void ExecCheckPlanPerms(Plan *plan, CmdType operation,
-                              int resultRelation, bool resultIsScanned);
+                  int resultRelation, bool resultIsScanned);
 static void ExecCheckRTPerms(List *rangeTable, CmdType operation,
-                            int resultRelation, bool resultIsScanned);
+                int resultRelation, bool resultIsScanned);
 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation,
-                             bool isResultRelation, bool resultIsScanned);
+                 bool isResultRelation, bool resultIsScanned);
+
 /* end of local decls */
 
 
@@ -460,14 +461,14 @@ ExecCheckPlanPerms(Plan *plan, CmdType operation,
 
    foreach(subp, plan->initPlan)
    {
-       SubPlan    *subplan = (SubPlan *) lfirst(subp);
+       SubPlan    *subplan = (SubPlan *) lfirst(subp);
 
        ExecCheckRTPerms(subplan->rtable, CMD_SELECT, 0, false);
        ExecCheckPlanPerms(subplan->plan, CMD_SELECT, 0, false);
    }
    foreach(subp, plan->subPlan)
    {
-       SubPlan    *subplan = (SubPlan *) lfirst(subp);
+       SubPlan    *subplan = (SubPlan *) lfirst(subp);
 
        ExecCheckRTPerms(subplan->rtable, CMD_SELECT, 0, false);
        ExecCheckPlanPerms(subplan->plan, CMD_SELECT, 0, false);
@@ -485,49 +486,51 @@ ExecCheckPlanPerms(Plan *plan, CmdType operation,
    switch (nodeTag(plan))
    {
        case T_Append:
-       {
-           Append     *app = (Append *) plan;
-           List       *appendplans;
-
-           if (app->inheritrelid > 0)
            {
-               /*
-                * Append implements expansion of inheritance; all members
-                * of inheritrtable list will be plugged into same RTE slot.
-                * Therefore, they are either all result relations or none.
-                */
-               List       *rtable;
+               Append     *app = (Append *) plan;
+               List       *appendplans;
 
-               foreach(rtable, app->inheritrtable)
+               if (app->inheritrelid > 0)
                {
-                   ExecCheckRTEPerms((RangeTblEntry *) lfirst(rtable),
-                                     operation,
-                                     (app->inheritrelid == resultRelation),
-                                     resultIsScanned);
-               }
-           }
-           else
-           {
-               /* Append implements UNION, which must be a SELECT */
-               List       *rtables;
 
-               foreach(rtables, app->unionrtables)
+                   /*
+                    * Append implements expansion of inheritance; all
+                    * members of inheritrtable list will be plugged into
+                    * same RTE slot. Therefore, they are either all
+                    * result relations or none.
+                    */
+                   List       *rtable;
+
+                   foreach(rtable, app->inheritrtable)
+                   {
+                       ExecCheckRTEPerms((RangeTblEntry *) lfirst(rtable),
+                                         operation,
+                                  (app->inheritrelid == resultRelation),
+                                         resultIsScanned);
+                   }
+               }
+               else
                {
-                   ExecCheckRTPerms((List *) lfirst(rtables),
-                                    CMD_SELECT, 0, false);
+                   /* Append implements UNION, which must be a SELECT */
+                   List       *rtables;
+
+                   foreach(rtables, app->unionrtables)
+                   {
+                       ExecCheckRTPerms((List *) lfirst(rtables),
+                                        CMD_SELECT, 0, false);
+                   }
                }
-           }
 
-           /* Check appended plans */
-           foreach(appendplans, app->appendplans)
-           {
-               ExecCheckPlanPerms((Plan *) lfirst(appendplans),
-                                  operation,
-                                  resultRelation,
-                                  resultIsScanned);
+               /* Check appended plans */
+               foreach(appendplans, app->appendplans)
+               {
+                   ExecCheckPlanPerms((Plan *) lfirst(appendplans),
+                                      operation,
+                                      resultRelation,
+                                      resultIsScanned);
+               }
+               break;
            }
-           break;
-       }
 
        default:
            break;
@@ -539,7 +542,7 @@ ExecCheckPlanPerms(Plan *plan, CmdType operation,
  *     Check access permissions for all relations listed in a range table.
  *
  * If resultRelation is not 0, it is the RT index of the relation to be
- * treated as the result relation.  All other relations are assumed to be
+ * treated as the result relation. All other relations are assumed to be
  * read-only for the query.
  */
 static void
@@ -576,10 +579,11 @@ ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation,
 
    if (rte->skipAcl)
    {
+
        /*
-        * This happens if the access to this table is due to a view
-        * query rewriting - the rewrite handler already checked the
-        * permissions against the view owner, so we just skip this entry.
+        * This happens if the access to this table is due to a view query
+        * rewriting - the rewrite handler already checked the permissions
+        * against the view owner, so we just skip this entry.
         */
        return;
    }
@@ -620,14 +624,12 @@ ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation,
            default:
                elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
                     operation);
-               aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
+               aclcheck_result = ACLCHECK_OK;  /* keep compiler quiet */
                break;
        }
    }
    else
-   {
        aclcheck_result = CHECK(ACL_RD);
-   }
 
    if (aclcheck_result != ACLCHECK_OK)
        elog(ERROR, "%s: %s",
@@ -734,8 +736,9 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
        /*
         * If there are indices on the result relation, open them and save
         * descriptors in the result relation info, so that we can add new
-        * index entries for the tuples we add/update.  We need not do this
-        * for a DELETE, however, since deletion doesn't affect indexes.
+        * index entries for the tuples we add/update.  We need not do
+        * this for a DELETE, however, since deletion doesn't affect
+        * indexes.
         */
        if (resultRelationDesc->rd_rel->relhasindex &&
            operation != CMD_DELETE)
@@ -805,10 +808,11 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
    targetList = plan->targetlist;
 
    /*
-    * Now that we have the target list, initialize the junk filter if needed.
-    * SELECT and INSERT queries need a filter if there are any junk attrs
-    * in the tlist.  UPDATE and DELETE always need one, since there's always
-    * a junk 'ctid' attribute present --- no need to look first.
+    * Now that we have the target list, initialize the junk filter if
+    * needed. SELECT and INSERT queries need a filter if there are any
+    * junk attrs in the tlist.  UPDATE and DELETE always need one, since
+    * there's always a junk 'ctid' attribute present --- no need to look
+    * first.
     */
    {
        bool        junk_filter_needed = false;
@@ -948,8 +952,8 @@ EndPlan(Plan *plan, EState *estate)
    }
 
    /*
-    * close the result relations if necessary,
-    * but hold locks on them until xact commit
+    * close the result relations if necessary, but hold locks on them
+    * until xact commit
     */
    if (resultRelationInfo != NULL)
    {
@@ -1708,10 +1712,10 @@ ExecRelCheck(Relation rel, HeapTuple tuple, EState *estate)
 
        /*
         * NOTE: SQL92 specifies that a NULL result from a constraint
-        * expression is not to be treated as a failure.  Therefore,
-        * tell ExecQual to return TRUE for NULL.
+        * expression is not to be treated as a failure.  Therefore, tell
+        * ExecQual to return TRUE for NULL.
         */
-       if (! ExecQual(qual, econtext, true))
+       if (!ExecQual(qual, econtext, true))
            return check[i].ccname;
    }
 
@@ -1738,7 +1742,7 @@ ExecConstraints(char *caller, Relation rel, HeapTuple tuple, EState *estate)
        {
            if (rel->rd_att->attrs[attrChk - 1]->attnotnull && heap_attisnull(tuple, attrChk))
                elog(ERROR, "%s: Fail to add null value in not null attribute %s",
-                 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
+                    caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
        }
    }
 
@@ -1791,7 +1795,7 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
            Assert(oldepq->rti != 0);
            /* stop execution */
            ExecEndNode(epq->plan, epq->plan);
-           epqstate->es_tupleTable->next = 0;
+           epqstate->es_tupleTable->next = 0;
            heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
            epqstate->es_evTuple[epq->rti - 1] = NULL;
            /* push current PQ to freePQ stack */
@@ -1861,7 +1865,7 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
    if (endNode)
    {
        ExecEndNode(epq->plan, epq->plan);
-       epqstate->es_tupleTable->next = 0;
+       epqstate->es_tupleTable->next = 0;
    }
 
    /* free old RTE' tuple */
@@ -1949,10 +1953,10 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
            estate->es_evalPlanQual = (Pointer) epq;
        }
        else
-       {                                   
-           epq->rti = 0;                   /* this is the first (oldest) */
-           estate->es_useEvalPlan = false; /* PQ - mark as free and      */
-           return (NULL);                  /* continue Query execution   */
+       {
+           epq->rti = 0;       /* this is the first (oldest) */
+           estate->es_useEvalPlan = false;     /* PQ - mark as free and      */
+           return (NULL);      /* continue Query execution   */
        }
    }
 
@@ -1961,7 +1965,7 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
               estate->es_origPlan->nParamExec * sizeof(ParamExecData));
    memset(epqstate->es_evTupleNull, false,
           length(estate->es_range_table) * sizeof(bool));
-    Assert(epqstate->es_tupleTable->next == 0);
+   Assert(epqstate->es_tupleTable->next == 0);
    ExecInitNode(epq->plan, epqstate, NULL);
 
    /*
@@ -1992,16 +1996,16 @@ lpqnext:;
    if (TupIsNull(slot))
    {
        ExecEndNode(epq->plan, epq->plan);
-       epqstate->es_tupleTable->next = 0;
+       epqstate->es_tupleTable->next = 0;
        heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
        epqstate->es_evTuple[epq->rti - 1] = NULL;
        /* pop old PQ from the stack */
        oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
        if (oldepq == (evalPlanQual *) NULL)
        {
-           epq->rti = 0;                   /* this is the first (oldest) */
-           estate->es_useEvalPlan = false; /* PQ - mark as free and      */
-           return (NULL);                  /* continue Query execution   */
+           epq->rti = 0;       /* this is the first (oldest) */
+           estate->es_useEvalPlan = false;     /* PQ - mark as free and      */
+           return (NULL);      /* continue Query execution   */
        }
        Assert(oldepq->rti != 0);
        /* push current PQ to freePQ stack */
@@ -2031,7 +2035,7 @@ EndEvalPlanQual(EState *estate)
    for (;;)
    {
        ExecEndNode(epq->plan, epq->plan);
-       epqstate->es_tupleTable->next = 0;
+       epqstate->es_tupleTable->next = 0;
        if (epqstate->es_evTuple[epq->rti - 1] != NULL)
        {
            heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
@@ -2041,8 +2045,8 @@ EndEvalPlanQual(EState *estate)
        oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
        if (oldepq == (evalPlanQual *) NULL)
        {
-           epq->rti = 0;                   /* this is the first (oldest) */
-           estate->es_useEvalPlan = false; /* PQ - mark as free */
+           epq->rti = 0;       /* this is the first (oldest) */
+           estate->es_useEvalPlan = false;     /* PQ - mark as free */
            break;
        }
        Assert(oldepq->rti != 0);
index a319e2c2b37c678624d6b66f167765eec752c282..58307e6a695e15568eb1f72b20f64a3c2e632dee 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.68 2000/02/20 21:32:04 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.69 2000/04/12 17:15:08 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -108,12 +108,14 @@ ExecEvalArrayRef(ArrayRef *arrayRef,
    }
    else
    {
-       /* Null refexpr indicates we are doing an INSERT into an array column.
-        * For now, we just take the refassgnexpr (which the parser will have
-        * ensured is an array value) and return it as-is, ignoring any
-        * subscripts that may have been supplied in the INSERT column list.
-        * This is a kluge, but it's not real clear what the semantics ought
-        * to be...
+
+       /*
+        * Null refexpr indicates we are doing an INSERT into an array
+        * column. For now, we just take the refassgnexpr (which the
+        * parser will have ensured is an array value) and return it
+        * as-is, ignoring any subscripts that may have been supplied in
+        * the INSERT column list. This is a kluge, but it's not real
+        * clear what the semantics ought to be...
         */
        array_scanner = NULL;
    }
@@ -153,16 +155,15 @@ ExecEvalArrayRef(ArrayRef *arrayRef,
        lIndex = lower.indx;
    }
    else
-   {
        lIndex = NULL;
-   }
 
    if (arrayRef->refassgnexpr != NULL)
    {
-       Datum sourceData = ExecEvalExpr(arrayRef->refassgnexpr,
-                                       econtext,
-                                       isNull,
-                                       &dummy);
+       Datum       sourceData = ExecEvalExpr(arrayRef->refassgnexpr,
+                                             econtext,
+                                             isNull,
+                                             &dummy);
+
        if (*isNull)
            return (Datum) NULL;
 
@@ -209,7 +210,7 @@ ExecEvalArrayRef(ArrayRef *arrayRef,
 static Datum
 ExecEvalAggref(Aggref *aggref, ExprContext *econtext, bool *isNull)
 {
-   if (econtext->ecxt_aggvalues == NULL) /* safety check */
+   if (econtext->ecxt_aggvalues == NULL)       /* safety check */
        elog(ERROR, "ExecEvalAggref: no aggregates in this expression context");
 
    *isNull = econtext->ecxt_aggnulls[aggref->aggno];
@@ -281,7 +282,7 @@ ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
    Assert(attnum <= 0 ||
           (attnum - 1 <= tuple_type->natts - 1 &&
            tuple_type->attrs[attnum - 1] != NULL &&
-           variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
+         variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
 
    /*
     * If the attribute number is invalid, then we are supposed to return
@@ -633,7 +634,7 @@ ExecEvalFuncArgs(FunctionCachePtr fcache,
         */
        argV[i] = ExecEvalExpr((Node *) lfirst(arg),
                               econtext,
-                              & nullVect[i],
+                              &nullVect[i],
                               argIsDone);
 
        if (!(*argIsDone))
@@ -779,9 +780,9 @@ ExecMakeFunctionResult(Node *node,
            result = postquel_function(funcNode, (char **) argV,
                                       isNull, isDone);
 
-           if (! *isDone)
+           if (!*isDone)
                break;          /* got a result from current argument */
-           if (! fcache->hasSetArg)
+           if (!fcache->hasSetArg)
                break;          /* input not a set, so done */
 
            /* OK, get the next argument... */
@@ -789,7 +790,11 @@ ExecMakeFunctionResult(Node *node,
 
            if (argDone)
            {
-               /* End of arguments, so reset the setArg flag and say "Done" */
+
+               /*
+                * End of arguments, so reset the setArg flag and say
+                * "Done"
+                */
                fcache->setArg = (char *) NULL;
                fcache->hasSetArg = false;
                *isDone = true;
@@ -797,7 +802,8 @@ ExecMakeFunctionResult(Node *node,
                break;
            }
 
-           /* If we reach here, loop around to run the function on the
+           /*
+            * If we reach here, loop around to run the function on the
             * new argument.
             */
        }
@@ -1003,20 +1009,22 @@ ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull)
    AnyNull = false;
 
    /*
-    * If any of the clauses is TRUE, the OR result is TRUE regardless
-    * of the states of the rest of the clauses, so we can stop evaluating
+    * If any of the clauses is TRUE, the OR result is TRUE regardless of
+    * the states of the rest of the clauses, so we can stop evaluating
     * and return TRUE immediately.  If none are TRUE and one or more is
     * NULL, we return NULL; otherwise we return FALSE.  This makes sense
     * when you interpret NULL as "don't know": if we have a TRUE then the
     * OR is TRUE even if we aren't sure about some of the other inputs.
     * If all the known inputs are FALSE, but we have one or more "don't
     * knows", then we have to report that we "don't know" what the OR's
-    * result should be --- perhaps one of the "don't knows" would have been
-    * TRUE if we'd known its value.  Only when all the inputs are known
-    * to be FALSE can we state confidently that the OR's result is FALSE.
+    * result should be --- perhaps one of the "don't knows" would have
+    * been TRUE if we'd known its value.  Only when all the inputs are
+    * known to be FALSE can we state confidently that the OR's result is
+    * FALSE.
     */
    foreach(clause, clauses)
    {
+
        /*
         * We don't iterate over sets in the quals, so pass in an isDone
         * flag, but ignore it.
@@ -1025,6 +1033,7 @@ ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull)
                                    econtext,
                                    isNull,
                                    &isDone);
+
        /*
         * if we have a non-null true result, then return it.
         */
@@ -1059,12 +1068,13 @@ ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull)
     * If any of the clauses is FALSE, the AND result is FALSE regardless
     * of the states of the rest of the clauses, so we can stop evaluating
     * and return FALSE immediately.  If none are FALSE and one or more is
-    * NULL, we return NULL; otherwise we return TRUE.  This makes sense
+    * NULL, we return NULL; otherwise we return TRUE.  This makes sense
     * when you interpret NULL as "don't know", using the same sort of
     * reasoning as for OR, above.
     */
    foreach(clause, clauses)
    {
+
        /*
         * We don't iterate over sets in the quals, so pass in an isDone
         * flag, but ignore it.
@@ -1073,6 +1083,7 @@ ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull)
                                    econtext,
                                    isNull,
                                    &isDone);
+
        /*
         * if we have a non-null false result, then return it.
         */
@@ -1084,7 +1095,7 @@ ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull)
 
    /* AnyNull is true if at least one clause evaluated to NULL */
    *isNull = AnyNull;
-   return (Datum) (! AnyNull);
+   return (Datum) (!AnyNull);
 }
 
 /* ----------------------------------------------------------------
@@ -1129,7 +1140,7 @@ ExecEvalCase(CaseExpr *caseExpr, ExprContext *econtext, bool *isNull)
         * case statement is satisfied.  A NULL result from the test is
         * not considered true.
         */
-       if (DatumGetInt32(clause_value) != 0 && ! *isNull)
+       if (DatumGetInt32(clause_value) != 0 && !*isNull)
        {
            return ExecEvalExpr(wclause->result,
                                econtext,
@@ -1258,7 +1269,7 @@ ExecEvalExpr(Node *expression,
                    default:
                        elog(ERROR, "ExecEvalExpr: unknown expression type %d",
                             expr->opType);
-                       retDatum = 0; /* keep compiler quiet */
+                       retDatum = 0;   /* keep compiler quiet */
                        break;
                }
                break;
@@ -1332,7 +1343,7 @@ ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
    IncrProcessed();
 
    /*
-    * Evaluate the qual conditions one at a time.  If we find a FALSE
+    * Evaluate the qual conditions one at a time.  If we find a FALSE
     * result, we can stop evaluating and return FALSE --- the AND result
     * must be FALSE.  Also, if we find a NULL result when resultForNull
     * is FALSE, we can stop and return FALSE --- the AND result must be
@@ -1353,14 +1364,15 @@ ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
 
        /*
         * If there is a null clause, consider the qualification to fail.
-        * XXX is this still correct for constraints?  It probably shouldn't
-        * happen at all ...
+        * XXX is this still correct for constraints?  It probably
+        * shouldn't happen at all ...
         */
        if (clause == NULL)
            return false;
+
        /*
-        * pass isDone, but ignore it.  We don't iterate over multiple returns
-        * in the qualifications.
+        * pass isDone, but ignore it.  We don't iterate over multiple
+        * returns in the qualifications.
         */
        expr_value = ExecEvalExpr(clause, econtext, &isNull, &isDone);
 
@@ -1429,7 +1441,8 @@ ExecTargetList(List *targetlist,
    HeapTuple   newTuple;
    bool        isNull;
    bool        haveDoneIters;
-   static struct tupleDesc NullTupleDesc; /* we assume this inits to zeroes */
+   static struct tupleDesc NullTupleDesc;      /* we assume this inits to
+                                                * zeroes */
 
    /*
     * debugging stuff
@@ -1512,7 +1525,8 @@ ExecTargetList(List *targetlist,
                if (itemIsDone[resind])
                    haveDoneIters = true;
                else
-                   *isDone = false; /* we have undone Iters in the list */
+                   *isDone = false;    /* we have undone Iters in the
+                                        * list */
            }
        }
        else
@@ -1571,7 +1585,9 @@ ExecTargetList(List *targetlist,
    {
        if (*isDone)
        {
-           /* all Iters are done, so return a null indicating tlist set
+
+           /*
+            * all Iters are done, so return a null indicating tlist set
             * expansion is complete.
             */
            newTuple = NULL;
@@ -1579,21 +1595,24 @@ ExecTargetList(List *targetlist,
        }
        else
        {
-           /* We have some done and some undone Iters.  Restart the done ones
-            * so that we can deliver a tuple (if possible).
+
+           /*
+            * We have some done and some undone Iters.  Restart the done
+            * ones so that we can deliver a tuple (if possible).
             *
             * XXX this code is a crock, because it only works for Iters at
-            * the top level of tlist expressions, and doesn't even work right
-            * for them: you should get all possible combinations of Iter
-            * results, but you won't unless the numbers of values returned by
-            * each are relatively prime.  Should have a mechanism more like
-            * aggregate functions, where we make a list of all Iters
-            * contained in the tlist and cycle through their values in a
-            * methodical fashion.  To do someday; can't get excited about
-            * fixing a Berkeley feature that's not in SQL92.  (The only
-            * reason we're doing this much is that we have to be sure all
-            * the Iters are run to completion, or their subplan executors
-            * will have unreleased resources, e.g. pinned buffers...)
+            * the top level of tlist expressions, and doesn't even work
+            * right for them: you should get all possible combinations of
+            * Iter results, but you won't unless the numbers of values
+            * returned by each are relatively prime.  Should have a
+            * mechanism more like aggregate functions, where we make a
+            * list of all Iters contained in the tlist and cycle through
+            * their values in a methodical fashion.  To do someday; can't
+            * get excited about fixing a Berkeley feature that's not in
+            * SQL92.  (The only reason we're doing this much is that we
+            * have to be sure all the Iters are run to completion, or
+            * their subplan executors will have unreleased resources,
+            * e.g. pinned buffers...)
             */
            foreach(tl, targetlist)
            {
@@ -1605,16 +1624,18 @@ ExecTargetList(List *targetlist,
                    resdom = tle->resdom;
                    resind = resdom->resno - 1;
 
-                   if (IsA(expr, Iter) && itemIsDone[resind])
+                   if (IsA(expr, Iter) &&itemIsDone[resind])
                    {
                        constvalue = (Datum) ExecEvalExpr(expr,
                                                          econtext,
                                                          &isNull,
-                                                         &itemIsDone[resind]);
+                                                   &itemIsDone[resind]);
                        if (itemIsDone[resind])
                        {
-                           /* Oh dear, this Iter is returning an empty set.
-                            * Guess we can't make a tuple after all.
+
+                           /*
+                            * Oh dear, this Iter is returning an empty
+                            * set. Guess we can't make a tuple after all.
                             */
                            *isDone = true;
                            newTuple = NULL;
@@ -1639,6 +1660,7 @@ ExecTargetList(List *targetlist,
    newTuple = (HeapTuple) heap_formtuple(targettype, values, null_head);
 
 exit:
+
    /*
     * free the status arrays if we palloc'd them
     */
index 1cbae3519a9e24ee6721206a64ce68cbe4b745f0..578b8b806812a15bd9f7abaec82cf8a0ce57f7c9 100644 (file)
@@ -15,7 +15,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/execTuples.c,v 1.36 2000/01/27 18:11:27 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/execTuples.c,v 1.37 2000/04/12 17:15:08 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -188,8 +188,8 @@ ExecCreateTupleTable(int initialSize)   /* initial number of slots in
  * --------------------------------
  */
 void
-ExecDropTupleTable(TupleTable table, /* tuple table */
-                     bool shouldFree)  /* true if we should free slot
+ExecDropTupleTable(TupleTable table,   /* tuple table */
+                  bool shouldFree)     /* true if we should free slot
                                         * contents */
 {
    int         next;           /* next available slot */
@@ -262,7 +262,7 @@ TupleTableSlot *                /* return: the slot allocated in the tuple
 ExecAllocTableSlot(TupleTable table)
 {
    int         slotnum;        /* new slot number */
-   TupleTableSlot*   slot;
+   TupleTableSlot *slot;
 
    /* ----------------
     *  sanity checks
@@ -335,8 +335,8 @@ ExecAllocTableSlot(TupleTable table)
  *
  *     tuple:  tuple to store
  *     slot:   slot to store it in
- *     buffer: disk buffer if tuple is in a disk page, else InvalidBuffer
- *     shouldFree: true if ExecClearTuple should pfree() the tuple
+ *     buffer: disk buffer if tuple is in a disk page, else InvalidBuffer
+ *     shouldFree: true if ExecClearTuple should pfree() the tuple
  *                 when done with it
  *
  * If 'buffer' is not InvalidBuffer, the tuple table code acquires a pin
@@ -350,7 +350,7 @@ ExecAllocTableSlot(TupleTable table)
  * Another case where it is 'false' is when the referenced tuple is held
  * in a tuple table slot belonging to a lower-level executor Proc node.
  * In this case the lower-level slot retains ownership and responsibility
- * for eventually releasing the tuple.  When this method is used, we must
+ * for eventually releasing the tuple. When this method is used, we must
  * be certain that the upper-level Proc node will lose interest in the tuple
  * sooner than the lower-level one does!  If you're not certain, copy the
  * lower-level tuple with heap_copytuple and let the upper-level table
@@ -385,7 +385,8 @@ ExecStoreTuple(HeapTuple tuple,
    slot->ttc_buffer = buffer;
    slot->ttc_shouldFree = shouldFree;
 
-   /* If tuple is on a disk page, keep the page pinned as long as we hold
+   /*
+    * If tuple is on a disk page, keep the page pinned as long as we hold
     * a pointer into it.
     */
    if (BufferIsValid(buffer))
@@ -426,7 +427,7 @@ ExecClearTuple(TupleTableSlot *slot)    /* slot in which to store tuple */
 
    slot->val = (HeapTuple) NULL;
 
-   slot->ttc_shouldFree = true; /* probably useless code... */
+   slot->ttc_shouldFree = true;/* probably useless code... */
 
    /* ----------------
     *  Drop the pin on the referenced buffer, if there is one.
@@ -776,6 +777,7 @@ NodeGetResultTupleSlot(Plan *node)
        case T_TidScan:
            {
                CommonScanState *scanstate = ((IndexScan *) node)->scan.scanstate;
+
                slot = scanstate->cstate.cs_ResultTupleSlot;
            }
            break;
index 8f15ac1ed180b18493ecb850d2bf5c9c47fa8a55..e3783473f96efdc98717e7257b276c437841a41f 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/execUtils.c,v 1.54 2000/02/18 09:29:57 inoue Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/execUtils.c,v 1.55 2000/04/12 17:15:08 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -776,7 +776,7 @@ ExecOpenIndices(Oid resultRelationOid,
    if (!RelationGetForm(resultRelationInfo->ri_RelationDesc)->relhasindex)
        return;
    if (IsIgnoringSystemIndexes() &&
-       IsSystemRelationName(RelationGetRelationName(resultRelationInfo->ri_RelationDesc)))
+       IsSystemRelationName(RelationGetRelationName(resultRelationInfo->ri_RelationDesc)))
        return;
    /* ----------------
     *  open pg_index
@@ -923,8 +923,8 @@ ExecOpenIndices(Oid resultRelationOid,
 
                /*
                 * Hack for not btree and hash indices: they use relation
-                * level exclusive locking on update (i.e. - they are
-                * not ready for MVCC) and so we have to exclusively lock
+                * level exclusive locking on update (i.e. - they are not
+                * ready for MVCC) and so we have to exclusively lock
                 * indices here to prevent deadlocks if we will scan them
                 * - index_beginscan places AccessShareLock, indices
                 * update methods don't use locks at all. We release this
@@ -1186,7 +1186,7 @@ ExecInsertIndexTuples(TupleTableSlot *slot,
            econtext->ecxt_scantuple = slot;
 
            /* Skip this index-update if the predicate isn't satisfied */
-           if (! ExecQual((List *) predicate, econtext, false))
+           if (!ExecQual((List *) predicate, econtext, false))
                continue;
        }
 
index 3854978029b2393a7f5c1f0f3b59d905164c027d..c8d119df482001972556148a76b87734becbf7b1 100644 (file)
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/functions.c,v 1.32 2000/04/04 21:44:39 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/functions.c,v 1.33 2000/04/12 17:15:09 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -150,6 +150,7 @@ init_execution_state(FunctionCachePtr fcache,
 static TupleDesc
 postquel_start(execution_state *es)
 {
+
    /*
     * Do nothing for utility commands. (create, destroy...)  DZ -
     * 30-8-1996
@@ -166,9 +167,9 @@ postquel_getnext(execution_state *es)
 
    if (es->qd->operation == CMD_UTILITY)
    {
+
        /*
-        * Process a utility command. (create, destroy...)  DZ -
-        * 30-8-1996
+        * Process a utility command. (create, destroy...)  DZ - 30-8-1996
         */
        ProcessUtility(es->qd->parsetree->utilityStmt, es->qd->dest);
        if (!LAST_POSTQUEL_COMMAND(es))
@@ -184,6 +185,7 @@ postquel_getnext(execution_state *es)
 static void
 postquel_end(execution_state *es)
 {
+
    /*
     * Do nothing for utility commands. (create, destroy...)  DZ -
     * 30-8-1996
index 961440cc66d99a893a99501cbe578862a2d136c8..e2db06f84d140690bf2e9673783015bc7de00da0 100644 (file)
@@ -15,7 +15,7 @@
  *      value1 = finalfunc(value1, value2)
  *
  *   If initcond1 is NULL then the first non-NULL input_value is
- *   assigned directly to value1.  sfunc1 isn't applied until value1
+ *   assigned directly to value1.  sfunc1 isn't applied until value1
  *   is non-NULL.
  *
  *   sfunc1 is never applied when the current tuple's input_value is NULL.
@@ -24,7 +24,7 @@
  *   (usenulls was formerly used for COUNT(*), but is no longer needed for
  *   that purpose; as of 10/1999 the support for usenulls is dead code.
  *   I have not removed it because it seems like a potentially useful
- *   feature for user-defined aggregates.  We'd just need to add a
+ *   feature for user-defined aggregates.  We'd just need to add a
  *   flag column to pg_aggregate and a parameter to CREATE AGGREGATE...)
  *
  *
@@ -32,7 +32,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/nodeAgg.c,v 1.62 2000/01/26 05:56:22 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/nodeAgg.c,v 1.63 2000/04/12 17:15:09 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -56,6 +56,7 @@
  */
 typedef struct AggStatePerAggData
 {
+
    /*
     * These values are set up during ExecInitAgg() and do not change
     * thereafter:
@@ -68,6 +69,7 @@ typedef struct AggStatePerAggData
    Oid         xfn1_oid;
    Oid         xfn2_oid;
    Oid         finalfn_oid;
+
    /*
     * fmgr lookup data for transfer functions --- only valid when
     * corresponding oid is not InvalidOid
@@ -75,18 +77,21 @@ typedef struct AggStatePerAggData
    FmgrInfo    xfn1;
    FmgrInfo    xfn2;
    FmgrInfo    finalfn;
+
    /*
-    * Type of input data and Oid of sort operator to use for it;
-    * only set/used when aggregate has DISTINCT flag.  (These are not
-    * used directly by nodeAgg, but must be passed to the Tuplesort object.)
+    * Type of input data and Oid of sort operator to use for it; only
+    * set/used when aggregate has DISTINCT flag.  (These are not used
+    * directly by nodeAgg, but must be passed to the Tuplesort object.)
     */
    Oid         inputType;
    Oid         sortOperator;
+
    /*
-    * fmgr lookup data for input type's equality operator --- only set/used
-    * when aggregate has DISTINCT flag.
+    * fmgr lookup data for input type's equality operator --- only
+    * set/used when aggregate has DISTINCT flag.
     */
    FmgrInfo    equalfn;
+
    /*
     * initial values from pg_aggregate entry
     */
@@ -94,6 +99,7 @@ typedef struct AggStatePerAggData
    Datum       initValue2;     /* for transtype2 */
    bool        initValue1IsNull,
                initValue2IsNull;
+
    /*
     * We need the len and byval info for the agg's input and transition
     * data types in order to know how to copy/delete values.
@@ -106,14 +112,14 @@ typedef struct AggStatePerAggData
                transtype2ByVal;
 
    /*
-    * These values are working state that is initialized at the start
-    * of an input tuple group and updated for each input tuple.
+    * These values are working state that is initialized at the start of
+    * an input tuple group and updated for each input tuple.
     *
     * For a simple (non DISTINCT) aggregate, we just feed the input values
-    * straight to the transition functions.  If it's DISTINCT, we pass the
-    * input values into a Tuplesort object; then at completion of the input
-    * tuple group, we scan the sorted values, eliminate duplicates, and run
-    * the transition functions on the rest.
+    * straight to the transition functions.  If it's DISTINCT, we pass
+    * the input values into a Tuplesort object; then at completion of the
+    * input tuple group, we scan the sorted values, eliminate duplicates,
+    * and run the transition functions on the rest.
     */
 
    Tuplesortstate *sortstate;  /* sort object, if a DISTINCT agg */
@@ -123,20 +129,22 @@ typedef struct AggStatePerAggData
    bool        value1IsNull,
                value2IsNull;
    bool        noInitValue;    /* true if value1 not set yet */
+
    /*
-    * Note: right now, noInitValue always has the same value as value1IsNull.
-    * But we should keep them separate because once the fmgr interface is
-    * fixed, we'll need to distinguish a null returned by transfn1 from
-    * a null we haven't yet replaced with an input value.
+    * Note: right now, noInitValue always has the same value as
+    * value1IsNull. But we should keep them separate because once the
+    * fmgr interface is fixed, we'll need to distinguish a null returned
+    * by transfn1 from a null we haven't yet replaced with an input
+    * value.
     */
 } AggStatePerAggData;
 
 
-static void initialize_aggregate (AggStatePerAgg peraggstate);
-static void advance_transition_functions (AggStatePerAgg peraggstate,
-                                         Datum newVal, bool isNull);
-static void finalize_aggregate (AggStatePerAgg peraggstate,
-                               Datum *resultVal, bool *resultIsNull);
+static void initialize_aggregate(AggStatePerAgg peraggstate);
+static void advance_transition_functions(AggStatePerAgg peraggstate,
+                            Datum newVal, bool isNull);
+static void finalize_aggregate(AggStatePerAgg peraggstate,
+                  Datum *resultVal, bool *resultIsNull);
 static Datum copyDatum(Datum val, int typLen, bool typByVal);
 
 
@@ -144,17 +152,19 @@ static Datum copyDatum(Datum val, int typLen, bool typByVal);
  * Initialize one aggregate for a new set of input values.
  */
 static void
-initialize_aggregate (AggStatePerAgg peraggstate)
+initialize_aggregate(AggStatePerAgg peraggstate)
 {
-   Aggref         *aggref = peraggstate->aggref;
+   Aggref     *aggref = peraggstate->aggref;
 
    /*
     * Start a fresh sort operation for each DISTINCT aggregate.
     */
    if (aggref->aggdistinct)
    {
-       /* In case of rescan, maybe there could be an uncompleted
-        * sort operation?  Clean it up if so.
+
+       /*
+        * In case of rescan, maybe there could be an uncompleted sort
+        * operation?  Clean it up if so.
         */
        if (peraggstate->sortstate)
            tuplesort_end(peraggstate->sortstate);
@@ -169,8 +179,8 @@ initialize_aggregate (AggStatePerAgg peraggstate)
     * (Re)set value1 and value2 to their initial values.
     */
    if (OidIsValid(peraggstate->xfn1_oid) &&
-       ! peraggstate->initValue1IsNull)
-       peraggstate->value1 = copyDatum(peraggstate->initValue1, 
+       !peraggstate->initValue1IsNull)
+       peraggstate->value1 = copyDatum(peraggstate->initValue1,
                                        peraggstate->transtype1Len,
                                        peraggstate->transtype1ByVal);
    else
@@ -178,8 +188,8 @@ initialize_aggregate (AggStatePerAgg peraggstate)
    peraggstate->value1IsNull = peraggstate->initValue1IsNull;
 
    if (OidIsValid(peraggstate->xfn2_oid) &&
-       ! peraggstate->initValue2IsNull)
-       peraggstate->value2 = copyDatum(peraggstate->initValue2, 
+       !peraggstate->initValue2IsNull)
+       peraggstate->value2 = copyDatum(peraggstate->initValue2,
                                        peraggstate->transtype2Len,
                                        peraggstate->transtype2ByVal);
    else
@@ -205,8 +215,8 @@ initialize_aggregate (AggStatePerAgg peraggstate)
  * out before reaching here.
  */
 static void
-advance_transition_functions (AggStatePerAgg peraggstate,
-                             Datum newVal, bool isNull)
+advance_transition_functions(AggStatePerAgg peraggstate,
+                            Datum newVal, bool isNull)
 {
    Datum       args[2];
 
@@ -214,6 +224,7 @@ advance_transition_functions (AggStatePerAgg peraggstate,
    {
        if (peraggstate->noInitValue)
        {
+
            /*
             * value1 has not been initialized. This is the first non-NULL
             * input value. We use it as the initial value for value1.
@@ -238,7 +249,7 @@ advance_transition_functions (AggStatePerAgg peraggstate,
            newVal = (Datum) fmgr_c(&peraggstate->xfn1,
                                    (FmgrValues *) args,
                                    &isNull);
-           if (! peraggstate->transtype1ByVal)
+           if (!peraggstate->transtype1ByVal)
                pfree(peraggstate->value1);
            peraggstate->value1 = newVal;
        }
@@ -252,7 +263,7 @@ advance_transition_functions (AggStatePerAgg peraggstate,
        newVal = (Datum) fmgr_c(&peraggstate->xfn2,
                                (FmgrValues *) args,
                                &isNull);
-       if (! peraggstate->transtype2ByVal)
+       if (!peraggstate->transtype2ByVal)
            pfree(peraggstate->value2);
        peraggstate->value2 = newVal;
    }
@@ -262,17 +273,18 @@ advance_transition_functions (AggStatePerAgg peraggstate,
  * Compute the final value of one aggregate.
  */
 static void
-finalize_aggregate (AggStatePerAgg peraggstate,
-                   Datum *resultVal, bool *resultIsNull)
+finalize_aggregate(AggStatePerAgg peraggstate,
+                  Datum *resultVal, bool *resultIsNull)
 {
    Aggref     *aggref = peraggstate->aggref;
    char       *args[2];
 
    /*
     * If it's a DISTINCT aggregate, all we've done so far is to stuff the
-    * input values into the sort object.  Complete the sort, then run
-    * the transition functions on the non-duplicate values.  Note that
-    * DISTINCT always suppresses nulls, per SQL spec, regardless of usenulls.
+    * input values into the sort object.  Complete the sort, then run the
+    * transition functions on the non-duplicate values.  Note that
+    * DISTINCT always suppresses nulls, per SQL spec, regardless of
+    * usenulls.
     */
    if (aggref->aggdistinct)
    {
@@ -289,41 +301,41 @@ finalize_aggregate (AggStatePerAgg peraggstate,
                continue;
            if (haveOldVal)
            {
-               Datum   equal;
+               Datum       equal;
 
                equal = (Datum) (*fmgr_faddr(&peraggstate->equalfn)) (oldVal,
-                                                                     newVal);
+                                                                newVal);
                if (DatumGetInt32(equal) != 0)
                {
-                   if (! peraggstate->inputtypeByVal)
+                   if (!peraggstate->inputtypeByVal)
                        pfree(DatumGetPointer(newVal));
                    continue;
                }
            }
            advance_transition_functions(peraggstate, newVal, false);
-           if (haveOldVal && ! peraggstate->inputtypeByVal)
+           if (haveOldVal && !peraggstate->inputtypeByVal)
                pfree(DatumGetPointer(oldVal));
            oldVal = newVal;
            haveOldVal = true;
        }
-       if (haveOldVal && ! peraggstate->inputtypeByVal)
+       if (haveOldVal && !peraggstate->inputtypeByVal)
            pfree(DatumGetPointer(oldVal));
        tuplesort_end(peraggstate->sortstate);
        peraggstate->sortstate = NULL;
    }
 
    /*
-    * Now apply the agg's finalfn, or substitute the appropriate transition
-    * value if there is no finalfn.
+    * Now apply the agg's finalfn, or substitute the appropriate
+    * transition value if there is no finalfn.
     *
-    * XXX For now, only apply finalfn if we got at least one
-    * non-null input value.  This prevents zero divide in AVG().
-    * If we had cleaner handling of null inputs/results in functions,
-    * we could probably take out this hack and define the result
-    * for no inputs as whatever finalfn returns for null input.
+    * XXX For now, only apply finalfn if we got at least one non-null input
+    * value.  This prevents zero divide in AVG(). If we had cleaner
+    * handling of null inputs/results in functions, we could probably
+    * take out this hack and define the result for no inputs as whatever
+    * finalfn returns for null input.
     */
    if (OidIsValid(peraggstate->finalfn_oid) &&
-       ! peraggstate->noInitValue)
+       !peraggstate->noInitValue)
    {
        if (peraggstate->finalfn.fn_nargs > 1)
        {
@@ -361,17 +373,17 @@ finalize_aggregate (AggStatePerAgg peraggstate,
        elog(ERROR, "ExecAgg: no valid transition functions??");
 
    /*
-    * Release any per-group working storage, unless we're passing
-    * it back as the result of the aggregate.
+    * Release any per-group working storage, unless we're passing it back
+    * as the result of the aggregate.
     */
    if (OidIsValid(peraggstate->xfn1_oid) &&
-       ! peraggstate->value1IsNull &&
-       ! peraggstate->transtype1ByVal)
+       !peraggstate->value1IsNull &&
+       !peraggstate->transtype1ByVal)
        pfree(peraggstate->value1);
-   
+
    if (OidIsValid(peraggstate->xfn2_oid) &&
-       ! peraggstate->value2IsNull &&
-       ! peraggstate->transtype2ByVal)
+       !peraggstate->value2IsNull &&
+       !peraggstate->transtype2ByVal)
        pfree(peraggstate->value2);
 }
 
@@ -383,8 +395,8 @@ finalize_aggregate (AggStatePerAgg peraggstate,
  *   the appropriate attribute for each aggregate function use (Aggref
  *   node) appearing in the targetlist or qual of the node.  The number
  *   of tuples to aggregate over depends on whether a GROUP BY clause is
- *   present.  We can produce an aggregate result row per group, or just
- *   one for the whole query.  The value of each aggregate is stored in
+ *   present.  We can produce an aggregate result row per group, or just
+ *   one for the whole query.  The value of each aggregate is stored in
  *   the expression context to be used when ExecProject evaluates the
  *   result tuple.
  *
@@ -403,7 +415,7 @@ ExecAgg(Agg *node)
    ProjectionInfo *projInfo;
    Datum      *aggvalues;
    bool       *aggnulls;
-   AggStatePerAgg  peragg;
+   AggStatePerAgg peragg;
    TupleTableSlot *resultSlot;
    HeapTuple   inputTuple;
    int         aggno;
@@ -437,7 +449,7 @@ ExecAgg(Agg *node)
         */
        for (aggno = 0; aggno < aggstate->numaggs; aggno++)
        {
-           AggStatePerAgg  peraggstate = &peragg[aggno];
+           AggStatePerAgg peraggstate = &peragg[aggno];
 
            initialize_aggregate(peraggstate);
        }
@@ -459,9 +471,9 @@ ExecAgg(Agg *node)
 
            for (aggno = 0; aggno < aggstate->numaggs; aggno++)
            {
-               AggStatePerAgg  peraggstate = &peragg[aggno];
-               Aggref         *aggref = peraggstate->aggref;
-               Datum           newVal;
+               AggStatePerAgg peraggstate = &peragg[aggno];
+               Aggref     *aggref = peraggstate->aggref;
+               Datum       newVal;
 
                newVal = ExecEvalExpr(aggref->target, econtext,
                                      &isNull, &isDone);
@@ -479,37 +491,37 @@ ExecAgg(Agg *node)
 
            /*
             * Keep a copy of the first input tuple for the projection.
-            * (We only need one since only the GROUP BY columns in it
-            * can be referenced, and these will be the same for all
-            * tuples aggregated over.)
+            * (We only need one since only the GROUP BY columns in it can
+            * be referenced, and these will be the same for all tuples
+            * aggregated over.)
             */
            if (!inputTuple)
                inputTuple = heap_copytuple(outerslot->val);
        }
 
        /*
-        * Done scanning input tuple group.
-        * Finalize each aggregate calculation.
+        * Done scanning input tuple group. Finalize each aggregate
+        * calculation.
         */
        for (aggno = 0; aggno < aggstate->numaggs; aggno++)
        {
-           AggStatePerAgg  peraggstate = &peragg[aggno];
+           AggStatePerAgg peraggstate = &peragg[aggno];
 
            finalize_aggregate(peraggstate,
-                              & aggvalues[aggno], & aggnulls[aggno]);
+                              &aggvalues[aggno], &aggnulls[aggno]);
        }
 
        /*
         * If the outerPlan is a Group node, we will reach here after each
         * group.  We are not done unless the Group node is done (a little
-        * ugliness here while we reach into the Group's state to find out).
-        * Furthermore, when grouping we return nothing at all unless we
-        * had some input tuple(s).  By the nature of Group, there are
-        * no empty groups, so if we get here with no input the whole scan
-        * is empty.
+        * ugliness here while we reach into the Group's state to find
+        * out). Furthermore, when grouping we return nothing at all
+        * unless we had some input tuple(s).  By the nature of Group,
+        * there are no empty groups, so if we get here with no input the
+        * whole scan is empty.
         *
-        * If the outerPlan isn't a Group, we are done when we get here,
-        * and we will emit a (single) tuple even if there were no input
+        * If the outerPlan isn't a Group, we are done when we get here, and
+        * we will emit a (single) tuple even if there were no input
         * tuples.
         */
        if (IsA(outerPlan, Group))
@@ -523,17 +535,18 @@ ExecAgg(Agg *node)
        else
        {
            aggstate->agg_done = true;
+
            /*
-            * If inputtuple==NULL (ie, the outerPlan didn't return anything),
-            * create a dummy all-nulls input tuple for use by execProject.
-            * 99.44% of the time this is a waste of cycles, because
-            * ordinarily the projected output tuple's targetlist cannot
-            * contain any direct (non-aggregated) references to input
-            * columns, so the dummy tuple will not be referenced.  However
-            * there are special cases where this isn't so --- in particular
-            * an UPDATE involving an aggregate will have a targetlist
-            * reference to ctid.  We need to return a null for ctid in that
-            * situation, not coredump.
+            * If inputtuple==NULL (ie, the outerPlan didn't return
+            * anything), create a dummy all-nulls input tuple for use by
+            * execProject. 99.44% of the time this is a waste of cycles,
+            * because ordinarily the projected output tuple's targetlist
+            * cannot contain any direct (non-aggregated) references to
+            * input columns, so the dummy tuple will not be referenced.
+            * However there are special cases where this isn't so --- in
+            * particular an UPDATE involving an aggregate will have a
+            * targetlist reference to ctid.  We need to return a null for
+            * ctid in that situation, not coredump.
             *
             * The values returned for the aggregates will be the initial
             * values of the transition functions.
@@ -550,7 +563,7 @@ ExecAgg(Agg *node)
                /* watch out for null input tuples, though... */
                if (tupType && tupValue)
                {
-                   null_array = (char *) palloc(sizeof(char)*tupType->natts);
+                   null_array = (char *) palloc(sizeof(char) * tupType->natts);
                    for (attnum = 0; attnum < tupType->natts; attnum++)
                        null_array[attnum] = 'n';
                    inputTuple = heap_formtuple(tupType, tupValue, null_array);
@@ -571,17 +584,17 @@ ExecAgg(Agg *node)
 
        /*
         * Form a projection tuple using the aggregate results and the
-        * representative input tuple.  Store it in the result tuple slot.
+        * representative input tuple.  Store it in the result tuple slot.
         */
        resultSlot = ExecProject(projInfo, &isDone);
 
        /*
-        * If the completed tuple does not match the qualifications,
-        * it is ignored and we loop back to try to process another group.
+        * If the completed tuple does not match the qualifications, it is
+        * ignored and we loop back to try to process another group.
         * Otherwise, return the tuple.
         */
    }
-   while (! ExecQual(node->plan.qual, econtext, false));
+   while (!ExecQual(node->plan.qual, econtext, false));
 
    return resultSlot;
 }
@@ -596,13 +609,13 @@ ExecAgg(Agg *node)
 bool
 ExecInitAgg(Agg *node, EState *estate, Plan *parent)
 {
-   AggState       *aggstate;
-   AggStatePerAgg  peragg;
-   Plan           *outerPlan;
-   ExprContext    *econtext;
-   int             numaggs,
-                   aggno;
-   List           *alist;
+   AggState   *aggstate;
+   AggStatePerAgg peragg;
+   Plan       *outerPlan;
+   ExprContext *econtext;
+   int         numaggs,
+               aggno;
+   List       *alist;
 
    /*
     * assign the node's execution state
@@ -620,21 +633,23 @@ ExecInitAgg(Agg *node, EState *estate, Plan *parent)
     * find aggregates in targetlist and quals
     *
     * Note: pull_agg_clauses also checks that no aggs contain other agg
-    * calls in their arguments.  This would make no sense under SQL semantics
-    * anyway (and it's forbidden by the spec).  Because that is true, we
-    * don't need to worry about evaluating the aggs in any particular order.
+    * calls in their arguments.  This would make no sense under SQL
+    * semantics anyway (and it's forbidden by the spec).  Because that is
+    * true, we don't need to worry about evaluating the aggs in any
+    * particular order.
     */
    aggstate->aggs = nconc(pull_agg_clause((Node *) node->plan.targetlist),
                           pull_agg_clause((Node *) node->plan.qual));
    aggstate->numaggs = numaggs = length(aggstate->aggs);
    if (numaggs <= 0)
    {
+
        /*
-        * This used to be treated as an error, but we can't do that anymore
-        * because constant-expression simplification could optimize away
-        * all of the Aggrefs in the targetlist and qual.  So, just make a
-        * debug note, and force numaggs positive so that palloc()s below
-        * don't choke.
+        * This used to be treated as an error, but we can't do that
+        * anymore because constant-expression simplification could
+        * optimize away all of the Aggrefs in the targetlist and qual.
+        * So, just make a debug note, and force numaggs positive so that
+        * palloc()s below don't choke.
         */
        elog(DEBUG, "ExecInitAgg: could not find any aggregate functions");
        numaggs = 1;
@@ -655,8 +670,8 @@ ExecInitAgg(Agg *node, EState *estate, Plan *parent)
    ExecInitResultTupleSlot(estate, &aggstate->csstate.cstate);
 
    /*
-    * Set up aggregate-result storage in the expr context,
-    * and also allocate my private per-agg working storage
+    * Set up aggregate-result storage in the expr context, and also
+    * allocate my private per-agg working storage
     */
    econtext = aggstate->csstate.cstate.cs_ExprContext;
    econtext->ecxt_aggvalues = (Datum *) palloc(sizeof(Datum) * numaggs);
@@ -693,15 +708,15 @@ ExecInitAgg(Agg *node, EState *estate, Plan *parent)
    aggno = -1;
    foreach(alist, aggstate->aggs)
    {
-       Aggref         *aggref = (Aggref *) lfirst(alist);
-       AggStatePerAgg  peraggstate = &peragg[++aggno];
-       char           *aggname = aggref->aggname;
-       HeapTuple       aggTuple;
+       Aggref     *aggref = (Aggref *) lfirst(alist);
+       AggStatePerAgg peraggstate = &peragg[++aggno];
+       char       *aggname = aggref->aggname;
+       HeapTuple   aggTuple;
        Form_pg_aggregate aggform;
-       Type            typeInfo;
-       Oid             xfn1_oid,
-                       xfn2_oid,
-                       finalfn_oid;
+       Type        typeInfo;
+       Oid         xfn1_oid,
+                   xfn2_oid,
+                   finalfn_oid;
 
        /* Mark Aggref node with its associated index in the result array */
        aggref->aggno = aggno;
@@ -762,9 +777,7 @@ ExecInitAgg(Agg *node, EState *estate, Plan *parent)
        }
 
        if (OidIsValid(finalfn_oid))
-       {
            fmgr_info(finalfn_oid, &peraggstate->finalfn);
-       }
 
        if (aggref->aggdistinct)
        {
@@ -848,7 +861,7 @@ copyDatum(Datum val, int typLen, bool typByVal)
        return val;
    else
    {
-       char   *newVal;
+       char       *newVal;
 
        if (typLen == -1)       /* variable length type? */
            typLen = VARSIZE((struct varlena *) DatumGetPointer(val));
index f5c5701fd25c8e1e62f715cecc434628f7f259a9..1200d9e6ba92b4caea555545daaa7fc8c19f01cb 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/nodeAppend.c,v 1.29 2000/01/26 05:56:22 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/nodeAppend.c,v 1.30 2000/04/12 17:15:09 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -251,9 +251,9 @@ ExecInitAppend(Append *node, EState *estate, Plan *parent)
 
        foreach(rtentryP, rtable)
        {
-           RangeTblEntry  *rtentry = lfirst(rtentryP);
-           Oid             reloid;
-           RelationInfo   *rri;
+           RangeTblEntry *rtentry = lfirst(rtentryP);
+           Oid         reloid;
+           RelationInfo *rri;
 
            reloid = rtentry->relid;
            rri = makeNode(RelationInfo);
@@ -304,6 +304,7 @@ ExecInitAppend(Append *node, EState *estate, Plan *parent)
        {
            JunkFilter *j = ExecInitJunkFilter(initNode->targetlist,
                                               ExecGetTupType(initNode));
+
            junkList = lappend(junkList, j);
        }
 
index cad023776d8ea3c51c59d6a0b330c60486b4785c..1a35ea578e9bc1624018b188a97913ed7c84a8b6 100644 (file)
@@ -15,7 +15,7 @@
  *   locate group boundaries.
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/nodeGroup.c,v 1.33 2000/01/27 18:11:27 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/nodeGroup.c,v 1.34 2000/04/12 17:15:09 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -97,8 +97,9 @@ ExecGroupEveryTuple(Group *node)
    {
        grpstate->grp_useFirstTuple = FALSE;
 
-       /* note we rely on subplan to hold ownership of the tuple
-        * for as long as we need it; we don't copy it.
+       /*
+        * note we rely on subplan to hold ownership of the tuple for as
+        * long as we need it; we don't copy it.
         */
        ExecStoreTuple(grpstate->grp_firstTuple,
                       grpstate->csstate.css_ScanTupleSlot,
@@ -122,17 +123,20 @@ ExecGroupEveryTuple(Group *node)
        }
        else
        {
+
            /*
             * Compare with first tuple and see if this tuple is of the
             * same group.
             */
-           if (! execTuplesMatch(firsttuple, outerTuple,
-                                 tupdesc,
-                                 node->numCols, node->grpColIdx,
-                                 grpstate->eqfunctions))
+           if (!execTuplesMatch(firsttuple, outerTuple,
+                                tupdesc,
+                                node->numCols, node->grpColIdx,
+                                grpstate->eqfunctions))
            {
+
                /*
-                * No; save the tuple to return it next time, and return NULL
+                * No; save the tuple to return it next time, and return
+                * NULL
                 */
                grpstate->grp_useFirstTuple = TRUE;
                heap_freetuple(firsttuple);
@@ -142,8 +146,9 @@ ExecGroupEveryTuple(Group *node)
            }
        }
 
-       /* note we rely on subplan to hold ownership of the tuple
-        * for as long as we need it; we don't copy it.
+       /*
+        * note we rely on subplan to hold ownership of the tuple for as
+        * long as we need it; we don't copy it.
         */
        ExecStoreTuple(outerTuple,
                       grpstate->csstate.css_ScanTupleSlot,
@@ -227,13 +232,13 @@ ExecGroupOneTuple(Group *node)
        outerTuple = outerslot->val;
 
        /*
-        * Compare with first tuple and see if this tuple is of the
-        * same group.
+        * Compare with first tuple and see if this tuple is of the same
+        * group.
         */
-       if (! execTuplesMatch(firsttuple, outerTuple,
-                             tupdesc,
-                             node->numCols, node->grpColIdx,
-                             grpstate->eqfunctions))
+       if (!execTuplesMatch(firsttuple, outerTuple,
+                            tupdesc,
+                            node->numCols, node->grpColIdx,
+                            grpstate->eqfunctions))
            break;
    }
 
@@ -244,8 +249,9 @@ ExecGroupOneTuple(Group *node)
     */
    projInfo = grpstate->csstate.cstate.cs_ProjInfo;
 
-   /* note we rely on subplan to hold ownership of the tuple
-    * for as long as we need it; we don't copy it.
+   /*
+    * note we rely on subplan to hold ownership of the tuple for as long
+    * as we need it; we don't copy it.
     */
    ExecStoreTuple(firsttuple,
                   grpstate->csstate.css_ScanTupleSlot,
@@ -418,7 +424,7 @@ execTuplesMatch(HeapTuple tuple1,
     * start comparing at the last field (least significant sort key).
     * That's the most likely to be different...
     */
-   for (i = numCols; --i >= 0; )
+   for (i = numCols; --i >= 0;)
    {
        AttrNumber  att = matchColIdx[i];
        Datum       attr1,
@@ -445,7 +451,7 @@ execTuplesMatch(HeapTuple tuple1,
 
        /* Apply the type-specific equality function */
 
-       equal = (Datum) (*fmgr_faddr(& eqfunctions[i])) (attr1, attr2);
+       equal = (Datum) (*fmgr_faddr(&eqfunctions[i])) (attr1, attr2);
 
        if (DatumGetInt32(equal) == 0)
            return FALSE;
@@ -459,7 +465,7 @@ execTuplesMatch(HeapTuple tuple1,
  *     Look up the equality functions needed for execTuplesMatch.
  *     The result is a palloc'd array.
  */
-FmgrInfo *
+FmgrInfo   *
 execTuplesMatchPrepare(TupleDesc tupdesc,
                       int numCols,
                       AttrNumber *matchColIdx)
@@ -481,7 +487,7 @@ execTuplesMatchPrepare(TupleDesc tupdesc,
                 typeidTypeName(typid));
        }
        pgopform = (Form_pg_operator) GETSTRUCT(eq_operator);
-       fmgr_info(pgopform->oprcode, & eqfunctions[i]);
+       fmgr_info(pgopform->oprcode, &eqfunctions[i]);
    }
 
    return eqfunctions;
index 16fcd225a8eb0645698deaa44099cb80ac5fe44f..d6fdce309de9a49ca599cab80a839193434ed088 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/nodeIndexscan.c,v 1.48 2000/04/07 00:30:41 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/nodeIndexscan.c,v 1.49 2000/04/12 17:15:09 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -106,7 +106,7 @@ IndexNext(IndexScan *node)
            direction = BackwardScanDirection;
        else if (ScanDirectionIsBackward(direction))
            direction = ForwardScanDirection;
-   }  
+   }
    snapshot = estate->es_snapshot;
    scanstate = node->scan.scanstate;
    indexstate = node->indxstate;
@@ -195,11 +195,11 @@ IndexNext(IndexScan *node)
                List       *qual;
 
                /*
-                *  store the scanned tuple in the scan tuple slot of
-                *  the scan state.  Eventually we will only do this and not
-                *  return a tuple.  Note: we pass 'false' because tuples
-                *  returned by amgetnext are pointers onto disk pages and
-                *  must not be pfree()'d.
+                * store the scanned tuple in the scan tuple slot of the
+                * scan state.  Eventually we will only do this and not
+                * return a tuple.  Note: we pass 'false' because tuples
+                * returned by amgetnext are pointers onto disk pages and
+                * must not be pfree()'d.
                 */
                ExecStoreTuple(tuple,   /* tuple to store */
                               slot,    /* slot to store in */
@@ -208,16 +208,17 @@ IndexNext(IndexScan *node)
 
                /*
                 * At this point we have an extra pin on the buffer,
-                * because ExecStoreTuple incremented the pin count.
-                * Drop our local pin.
+                * because ExecStoreTuple incremented the pin count. Drop
+                * our local pin.
                 */
                ReleaseBuffer(buffer);
 
                /*
                 * We must check to see if the current tuple was already
-                * matched by an earlier index, so we don't double-report it.
-                * We do this by passing the tuple through ExecQual and
-                * checking for failure with all previous qualifications.
+                * matched by an earlier index, so we don't double-report
+                * it. We do this by passing the tuple through ExecQual
+                * and checking for failure with all previous
+                * qualifications.
                 */
                scanstate->cstate.cs_ExprContext->ecxt_scantuple = slot;
                qual = node->indxqualorig;
@@ -234,7 +235,7 @@ IndexNext(IndexScan *node)
                    qual = lnext(qual);
                }
                if (!prev_matches)
-                   return slot;        /* OK to return tuple */
+                   return slot;/* OK to return tuple */
                /* Duplicate tuple, so drop it and loop back for another */
                ExecClearTuple(slot);
            }
@@ -380,13 +381,14 @@ ExecIndexReScan(IndexScan *node, ExprContext *exprCtxt, Plan *parent)
                    scanexpr = (run_keys[j] == RIGHT_OP) ?
                        (Node *) get_rightop(clause) :
                        (Node *) get_leftop(clause);
+
                    /*
                     * pass in isDone but ignore it.  We don't iterate in
                     * quals
                     */
                    scanvalue = (Datum)
                        ExecEvalExpr(scanexpr,
-                               node->scan.scanstate->cstate.cs_ExprContext,
+                            node->scan.scanstate->cstate.cs_ExprContext,
                                     &isNull, &isDone);
                    scan_keys[j].sk_argument = scanvalue;
                    if (isNull)
@@ -750,7 +752,7 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent)
            clause = nth(j, qual);
 
            op = (Oper *) clause->oper;
-           if (!IsA(clause, Expr) || !IsA(op, Oper))
+           if (!IsA(clause, Expr) ||!IsA(op, Oper))
                elog(ERROR, "ExecInitIndexScan: indxqual not an opclause!");
 
            opid = op->opid;
@@ -801,7 +803,7 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent)
 
            Assert(leftop != NULL);
 
-           if (IsA(leftop, Var) && var_is_rel((Var *) leftop))
+           if (IsA(leftop, Var) &&var_is_rel((Var *) leftop))
            {
                /* ----------------
                 *  if the leftop is a "rel-var", then it means
@@ -884,7 +886,7 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent)
 
            Assert(rightop != NULL);
 
-           if (IsA(rightop, Var) && var_is_rel((Var *) rightop))
+           if (IsA(rightop, Var) &&var_is_rel((Var *) rightop))
            {
                /* ----------------
                 *  here we make sure only one op identifies the
@@ -1049,10 +1051,8 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent)
                  &currentRelation,     /* return: rel desc */
                  (Pointer *) &currentScanDesc);        /* return: scan desc */
 
-if (!RelationGetForm(currentRelation)->relhasindex)
-{
-   elog(ERROR, "indexes of the relation %u was inactivated", reloid);
-}
+   if (!RelationGetForm(currentRelation)->relhasindex)
+       elog(ERROR, "indexes of the relation %u was inactivated", reloid);
    scanstate->css_currentRelation = currentRelation;
    scanstate->css_currentScanDesc = currentScanDesc;
 
index 9a70851e9f713a4c39619d21b0dbb23b3c09af67..362aef88d3ab0c5a3c233fb6237591507c85813f 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/nodeSort.c,v 1.25 2000/01/26 05:56:23 momjian Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/nodeSort.c,v 1.26 2000/04/12 17:15:09 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -126,7 +126,7 @@ ExecSort(Sort *node)
     * ----------------
     */
 
-   if (! sortstate->sort_Done)
+   if (!sortstate->sort_Done)
    {
        Plan       *outerNode;
        TupleDesc   tupDesc;
@@ -156,7 +156,7 @@ ExecSort(Sort *node)
        sortkeys = (ScanKey) sortstate->sort_Keys;
 
        tuplesortstate = tuplesort_begin_heap(tupDesc, keycount, sortkeys,
-                                             true /* randomAccess */);
+                                             true /* randomAccess */ );
 
        sortstate->tuplesortstate = (void *) tuplesortstate;
 
@@ -371,7 +371,7 @@ ExecSortMarkPos(Sort *node)
     *  if we haven't sorted yet, just return
     * ----------------
     */
-   if (! sortstate->sort_Done)
+   if (!sortstate->sort_Done)
        return;
 
    tuplesort_markpos((Tuplesortstate *) sortstate->tuplesortstate);
@@ -392,7 +392,7 @@ ExecSortRestrPos(Sort *node)
     *  if we haven't sorted yet, just return.
     * ----------------
     */
-   if (! sortstate->sort_Done)
+   if (!sortstate->sort_Done)
        return;
 
    /* ----------------
@@ -412,14 +412,14 @@ ExecReScanSort(Sort *node, ExprContext *exprCtxt, Plan *parent)
     * not NULL then it will be re-scanned by ExecProcNode, else - no
     * reason to re-scan it at all.
     */
-   if (! sortstate->sort_Done)
+   if (!sortstate->sort_Done)
        return;
 
    ExecClearTuple(sortstate->csstate.cstate.cs_ResultTupleSlot);
 
    /*
-    * If subnode is to be rescanned then we forget previous sort
-    * results; we have to re-read the subplan and re-sort.
+    * If subnode is to be rescanned then we forget previous sort results;
+    * we have to re-read the subplan and re-sort.
     *
     * Otherwise we can just rewind and rescan the sorted output.
     */
@@ -430,7 +430,5 @@ ExecReScanSort(Sort *node, ExprContext *exprCtxt, Plan *parent)
        sortstate->tuplesortstate = NULL;
    }
    else
-   {
        tuplesort_rescan((Tuplesortstate *) sortstate->tuplesortstate);
-   }
 }
index ed09a0bc9f22f26389ceeb9a89ff541525db60c1..99b09f685a0cd21f2bf0748aeb63fe09c1207134 100644 (file)
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/nodeSubplan.c,v 1.24 2000/03/23 07:32:58 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/nodeSubplan.c,v 1.25 2000/04/12 17:15:10 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -67,20 +67,20 @@ ExecSubPlan(SubPlan *node, List *pvar, ExprContext *econtext, bool *isNull)
    ExecReScan(plan, (ExprContext *) NULL, plan);
 
    /*
-    * For all sublink types except EXPR_SUBLINK, the result is boolean
-    * as are the results of the combining operators.  We combine results
+    * For all sublink types except EXPR_SUBLINK, the result is boolean as
+    * are the results of the combining operators.  We combine results
     * within a tuple (if there are multiple columns) using OR semantics
     * if "useor" is true, AND semantics if not.  We then combine results
     * across tuples (if the subplan produces more than one) using OR
     * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
     * (MULTIEXPR_SUBLINK doesn't allow multiple tuples from the subplan.)
     * NULL results from the combining operators are handled according to
-    * the usual SQL semantics for OR and AND.  The result for no input
+    * the usual SQL semantics for OR and AND.  The result for no input
     * tuples is FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
     * MULTIEXPR_SUBLINK.
     *
     * For EXPR_SUBLINK we require the subplan to produce no more than one
-    * tuple, else an error is raised.  If zero tuples are produced, we
+    * tuple, else an error is raised.  If zero tuples are produced, we
     * return NULL.  Assuming we get a tuple, we just return its first
     * column (there can be only one non-junk column in this case).
     */
@@ -106,13 +106,14 @@ ExecSubPlan(SubPlan *node, List *pvar, ExprContext *econtext, bool *isNull)
            if (found)
                elog(ERROR, "More than one tuple returned by a subselect used as an expression.");
            found = true;
+
            /*
-            * We need to copy the subplan's tuple in case the result is of
-            * pass-by-ref type --- our return value will point into this
-            * copied tuple!  Can't use the subplan's instance of the tuple
-            * since it won't still be valid after next ExecProcNode() call.
-            * node->curTuple keeps track of the copied tuple for eventual
-            * freeing.
+            * We need to copy the subplan's tuple in case the result is
+            * of pass-by-ref type --- our return value will point into
+            * this copied tuple!  Can't use the subplan's instance of the
+            * tuple since it won't still be valid after next
+            * ExecProcNode() call. node->curTuple keeps track of the
+            * copied tuple for eventual freeing.
             */
            tup = heap_copytuple(tup);
            if (node->curTuple)
@@ -129,7 +130,8 @@ ExecSubPlan(SubPlan *node, List *pvar, ExprContext *econtext, bool *isNull)
 
        found = true;
 
-       /* For ALL, ANY, and MULTIEXPR sublinks, iterate over combining
+       /*
+        * For ALL, ANY, and MULTIEXPR sublinks, iterate over combining
         * operators for columns of tuple.
         */
        foreach(lst, sublink->oper)
@@ -140,14 +142,14 @@ ExecSubPlan(SubPlan *node, List *pvar, ExprContext *econtext, bool *isNull)
            bool        expnull;
 
            /*
-            * The righthand side of the expression should be either a Const
-            * or a function call or RelabelType node taking a Const as arg
-            * (these nodes represent run-time type coercions inserted by
-            * the parser to get to the input type needed by the operator).
-            * Find the Const node and insert the actual righthand-side value
-            * into it.
+            * The righthand side of the expression should be either a
+            * Const or a function call or RelabelType node taking a Const
+            * as arg (these nodes represent run-time type coercions
+            * inserted by the parser to get to the input type needed by
+            * the operator). Find the Const node and insert the actual
+            * righthand-side value into it.
             */
-           if (! IsA(con, Const))
+           if (!IsA(con, Const))
            {
                switch (con->type)
                {
@@ -161,16 +163,18 @@ ExecSubPlan(SubPlan *node, List *pvar, ExprContext *econtext, bool *isNull)
                        /* will fail below */
                        break;
                }
-               if (! IsA(con, Const))
+               if (!IsA(con, Const))
                    elog(ERROR, "ExecSubPlan: failed to find placeholder for subplan result");
            }
            con->constvalue = heap_getattr(tup, col, tdesc,
                                           &(con->constisnull));
+
            /*
             * Now we can eval the combining operator for this column.
             */
            expresult = ExecEvalExpr((Node *) expr, econtext, &expnull,
                                     (bool *) NULL);
+
            /*
             * Combine the result into the row result as appropriate.
             */
@@ -240,14 +244,16 @@ ExecSubPlan(SubPlan *node, List *pvar, ExprContext *econtext, bool *isNull)
 
    if (!found)
    {
-       /* deal with empty subplan result.  result/isNull were previously
+
+       /*
+        * deal with empty subplan result.  result/isNull were previously
         * initialized correctly for all sublink types except EXPR and
         * MULTIEXPR; for those, return NULL.
         */
        if (subLinkType == EXPR_SUBLINK || subLinkType == MULTIEXPR_SUBLINK)
        {
-               result = (Datum) false;
-               *isNull = true;
+           result = (Datum) false;
+           *isNull = true;
        }
    }
 
@@ -354,9 +360,9 @@ ExecSetParamPlan(SubPlan *node)
 
        /*
         * We need to copy the subplan's tuple in case any of the params
-        * are pass-by-ref type --- the pointers stored in the param structs
-        * will point at this copied tuple!  node->curTuple keeps track
-        * of the copied tuple for eventual freeing.
+        * are pass-by-ref type --- the pointers stored in the param
+        * structs will point at this copied tuple!  node->curTuple keeps
+        * track of the copied tuple for eventual freeing.
         */
        tup = heap_copytuple(tup);
        if (node->curTuple)
index 7d9c6748637cf77a0ee12409ac9ba67ced0a7132..31cdc20523533af670dbabe60eb200285abef03d 100644 (file)
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *   $Header: /cvsroot/pgsql/src/backend/executor/nodeTidscan.c,v 1.5 2000/04/07 00:30:41 tgl Exp $
+ *   $Header: /cvsroot/pgsql/src/backend/executor/nodeTidscan.c,v 1.6 2000/04/12 17:15:10 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
 #include "access/heapam.h"
 #include "parser/parsetree.h"
 
-static int TidListCreate(List *, ExprContext *, ItemPointer *);
+static int TidListCreate(List *, ExprContext *, ItemPointer *);
 static TupleTableSlot *TidNext(TidScan *node);
 
 static int
 TidListCreate(List *evalList, ExprContext *econtext, ItemPointer *tidList)
 {
-   List        *lst;
-   ItemPointer itemptr;
+   List       *lst;
+   ItemPointer itemptr;
    bool        isNull;
-   int     numTids = 0;
+   int         numTids = 0;
 
-   foreach (lst, evalList)
+   foreach(lst, evalList)
    {
-       itemptr = (ItemPointer)ExecEvalExpr(lfirst(lst), econtext,
-               &isNull, (bool *)0);
+       itemptr = (ItemPointer) ExecEvalExpr(lfirst(lst), econtext,
+                                            &isNull, (bool *) 0);
        if (itemptr && ItemPointerIsValid(itemptr))
        {
            tidList[numTids] = itemptr;
@@ -67,20 +67,21 @@ TidListCreate(List *evalList, ExprContext *econtext, ItemPointer *tidList)
 static TupleTableSlot *
 TidNext(TidScan *node)
 {
-   EState      *estate;
+   EState     *estate;
    CommonScanState *scanstate;
-   TidScanState    *tidstate;
-   ScanDirection   direction;
+   TidScanState *tidstate;
+   ScanDirection direction;
    Snapshot    snapshot;
    Relation    heapRelation;
    HeapTuple   tuple;
-   TupleTableSlot  *slot;
+   TupleTableSlot *slot;
    Buffer      buffer = InvalidBuffer;
-   int     numTids;
+   int         numTids;
 
    bool        bBackward;
-   int     tidNumber;
-   ItemPointer *tidList, itemptr;
+   int         tidNumber;
+   ItemPointer *tidList,
+               itemptr;
 
    /* ----------------
     *  extract necessary information from tid scan node
@@ -108,7 +109,7 @@ TidNext(TidScan *node)
        ExecClearTuple(slot);
        if (estate->es_evTupleNull[node->scan.scanrelid - 1])
            return slot;        /* return empty slot */
-       
+
        /* probably ought to use ExecStoreTuple here... */
        slot->val = estate->es_evTuple[node->scan.scanrelid - 1];
        slot->ttc_shouldFree = false;
@@ -159,7 +160,7 @@ TidNext(TidScan *node)
        if (tuple->t_data != NULL)
        {
            bool        prev_matches = false;
-           int     prev_tid;
+           int         prev_tid;
 
            /* ----------------
             *  store the scanned tuple in the scan tuple slot of