From 089003fb462fcce46c02bf47322b429f73c33c50 Mon Sep 17 00:00:00 2001 From: Bruce Momjian Date: Mon, 4 Aug 2003 00:43:34 +0000 Subject: [PATCH] pgindent run. --- contrib/btree_gist/btree_common.c | 2 +- contrib/btree_gist/btree_gist.h | 1 - contrib/cube/cube.c | 76 +- contrib/dbase/dbf2pg.c | 10 +- contrib/dblink/dblink.c | 163 +- contrib/dbmirror/pending.c | 29 +- contrib/dbsize/dbsize.c | 2 +- contrib/earthdistance/earthdistance.c | 13 +- contrib/findoidjoins/findoidjoins.c | 85 +- contrib/fulltextindex/fti.c | 6 +- contrib/fuzzystrmatch/fuzzystrmatch.c | 6 +- contrib/intagg/int_aggregate.c | 6 +- contrib/intarray/_int.h | 66 +- contrib/intarray/_int_bool.c | 5 +- contrib/intarray/_int_gist.c | 53 +- contrib/intarray/_int_tool.c | 3 +- contrib/ltree/_ltree_op.c | 50 +- contrib/ltree/lquery_op.c | 52 +- contrib/ltree/ltree_io.c | 24 +- contrib/ltree/ltree_op.c | 117 +- contrib/oid2name/oid2name.c | 4 +- contrib/pg_autovacuum/pg_autovacuum.c | 1743 +++++++++------- contrib/pg_autovacuum/pg_autovacuum.h | 129 +- contrib/pg_dumplo/main.c | 4 +- contrib/pgbench/pgbench.c | 4 +- contrib/pgcrypto/openssl.c | 79 +- contrib/pgcrypto/pgcrypto.c | 4 +- contrib/pgstattuple/pgstattuple.c | 4 +- contrib/spi/autoinc.c | 4 +- contrib/spi/insert_username.c | 6 +- contrib/spi/moddatetime.c | 4 +- contrib/spi/refint.c | 10 +- contrib/spi/timetravel.c | 239 +-- contrib/tablefunc/tablefunc.c | 234 ++- contrib/tsearch/morph.c | 5 +- contrib/tsearch2/common.c | 101 +- contrib/tsearch2/common.h | 16 +- contrib/tsearch2/dict.c | 313 +-- contrib/tsearch2/dict.h | 51 +- contrib/tsearch2/dict_ex.c | 58 +- contrib/tsearch2/dict_ispell.c | 158 +- contrib/tsearch2/dict_snowball.c | 111 +- contrib/tsearch2/dict_syn.c | 173 +- contrib/tsearch2/ispell/spell.c | 856 ++++---- contrib/tsearch2/ispell/spell.h | 77 +- contrib/tsearch2/prs_dcfg.c | 222 +- contrib/tsearch2/query.c | 163 +- contrib/tsearch2/query.h | 10 +- contrib/tsearch2/rank.c | 721 ++++--- contrib/tsearch2/snmap.c | 94 +- contrib/tsearch2/snmap.h | 30 +- contrib/tsearch2/snowball/api.c | 94 +- contrib/tsearch2/snowball/api.h | 25 +- contrib/tsearch2/snowball/english_stem.c | 1844 +++++++++-------- contrib/tsearch2/snowball/english_stem.h | 5 +- contrib/tsearch2/snowball/header.h | 52 +- contrib/tsearch2/snowball/russian_stem.c | 1242 ++++++----- contrib/tsearch2/snowball/russian_stem.h | 5 +- contrib/tsearch2/snowball/utilities.c | 731 ++++--- contrib/tsearch2/stopword.c | 127 +- contrib/tsearch2/ts_cfg.c | 639 +++--- contrib/tsearch2/ts_cfg.h | 111 +- contrib/tsearch2/ts_stat.c | 531 ++--- contrib/tsearch2/ts_stat.h | 14 +- contrib/tsearch2/tsvector.c | 508 +++-- contrib/tsearch2/tsvector.h | 37 +- contrib/tsearch2/tsvector_op.c | 358 ++-- contrib/tsearch2/wordparser/deflex.c | 5 +- contrib/tsearch2/wparser.c | 598 +++--- contrib/tsearch2/wparser.h | 38 +- contrib/tsearch2/wparser_def.c | 344 +-- contrib/xml/pgxml_dom.c | 8 +- src/backend/access/common/heaptuple.c | 4 +- src/backend/access/common/indextuple.c | 8 +- src/backend/access/common/printtup.c | 58 +- src/backend/access/gist/gistscan.c | 9 +- src/backend/access/hash/hashfunc.c | 20 +- src/backend/access/hash/hashovfl.c | 6 +- src/backend/access/heap/heapam.c | 16 +- src/backend/access/index/indexam.c | 51 +- src/backend/access/nbtree/nbtinsert.c | 55 +- src/backend/access/nbtree/nbtpage.c | 149 +- src/backend/access/nbtree/nbtree.c | 90 +- src/backend/access/nbtree/nbtsearch.c | 91 +- src/backend/access/nbtree/nbtsort.c | 6 +- src/backend/access/nbtree/nbtxlog.c | 224 +- src/backend/access/rtree/rtscan.c | 10 +- src/backend/access/transam/clog.c | 4 +- src/backend/access/transam/rmgr.c | 6 +- src/backend/access/transam/slru.c | 94 +- src/backend/access/transam/xact.c | 58 +- src/backend/access/transam/xlog.c | 251 +-- src/backend/bootstrap/bootstrap.c | 42 +- src/backend/catalog/aclchk.c | 61 +- src/backend/catalog/dependency.c | 86 +- src/backend/catalog/heap.c | 41 +- src/backend/catalog/index.c | 65 +- src/backend/catalog/namespace.c | 32 +- src/backend/catalog/pg_aggregate.c | 42 +- src/backend/catalog/pg_constraint.c | 19 +- src/backend/catalog/pg_conversion.c | 10 +- src/backend/catalog/pg_operator.c | 8 +- src/backend/catalog/pg_proc.c | 44 +- src/backend/catalog/pg_type.c | 27 +- src/backend/commands/aggregatecmds.c | 10 +- src/backend/commands/alter.c | 82 +- src/backend/commands/analyze.c | 8 +- src/backend/commands/async.c | 13 +- src/backend/commands/cluster.c | 133 +- src/backend/commands/comment.c | 35 +- src/backend/commands/conversioncmds.c | 8 +- src/backend/commands/copy.c | 209 +- src/backend/commands/dbcommands.c | 60 +- src/backend/commands/define.c | 5 +- src/backend/commands/explain.c | 40 +- src/backend/commands/functioncmds.c | 51 +- src/backend/commands/indexcmds.c | 85 +- src/backend/commands/opclasscmds.c | 18 +- src/backend/commands/operatorcmds.c | 6 +- src/backend/commands/portalcmds.c | 64 +- src/backend/commands/prepare.c | 58 +- src/backend/commands/proclang.c | 12 +- src/backend/commands/schemacmds.c | 14 +- src/backend/commands/sequence.c | 54 +- src/backend/commands/tablecmds.c | 285 +-- src/backend/commands/trigger.c | 228 +- src/backend/commands/typecmds.c | 326 +-- src/backend/commands/user.c | 56 +- src/backend/commands/vacuum.c | 61 +- src/backend/commands/vacuumlazy.c | 30 +- src/backend/commands/variable.c | 85 +- src/backend/commands/view.c | 6 +- src/backend/executor/execAmi.c | 28 +- src/backend/executor/execGrouping.c | 12 +- src/backend/executor/execMain.c | 123 +- src/backend/executor/execProcnode.c | 18 +- src/backend/executor/execQual.c | 361 ++-- src/backend/executor/execScan.c | 23 +- src/backend/executor/execTuples.c | 8 +- src/backend/executor/execUtils.c | 62 +- src/backend/executor/functions.c | 28 +- src/backend/executor/nodeAgg.c | 168 +- src/backend/executor/nodeAppend.c | 4 +- src/backend/executor/nodeHash.c | 4 +- src/backend/executor/nodeHashjoin.c | 44 +- src/backend/executor/nodeIndexscan.c | 7 +- src/backend/executor/nodeLimit.c | 41 +- src/backend/executor/nodeMaterial.c | 21 +- src/backend/executor/nodeMergejoin.c | 28 +- src/backend/executor/nodeNestloop.c | 10 +- src/backend/executor/nodeResult.c | 4 +- src/backend/executor/nodeSeqscan.c | 20 +- src/backend/executor/nodeSubplan.c | 275 +-- src/backend/executor/nodeSubqueryscan.c | 17 +- src/backend/executor/nodeUnique.c | 8 +- src/backend/executor/spi.c | 29 +- src/backend/executor/tstoreReceiver.c | 10 +- src/backend/lib/stringinfo.c | 12 +- src/backend/libpq/auth.c | 42 +- src/backend/libpq/be-fsstubs.c | 6 +- src/backend/libpq/be-secure.c | 23 +- src/backend/libpq/crypt.c | 7 +- src/backend/libpq/hba.c | 73 +- src/backend/libpq/ip.c | 151 +- src/backend/libpq/md5.c | 6 +- src/backend/libpq/pqcomm.c | 88 +- src/backend/libpq/pqformat.c | 81 +- src/backend/main/main.c | 21 +- src/backend/nodes/bitmapset.c | 174 +- src/backend/nodes/copyfuncs.c | 64 +- src/backend/nodes/equalfuncs.c | 109 +- src/backend/nodes/list.c | 19 +- src/backend/nodes/nodes.c | 4 +- src/backend/nodes/outfuncs.c | 48 +- src/backend/nodes/readfuncs.c | 59 +- src/backend/optimizer/geqo/geqo_eval.c | 25 +- src/backend/optimizer/geqo/geqo_main.c | 6 +- src/backend/optimizer/geqo/geqo_misc.c | 4 +- src/backend/optimizer/path/allpaths.c | 31 +- src/backend/optimizer/path/costsize.c | 286 +-- src/backend/optimizer/path/indxpath.c | 191 +- src/backend/optimizer/path/joinpath.c | 41 +- src/backend/optimizer/path/joinrels.c | 42 +- src/backend/optimizer/path/orindxpath.c | 4 +- src/backend/optimizer/path/pathkeys.c | 57 +- src/backend/optimizer/path/tidpath.c | 6 +- src/backend/optimizer/plan/createplan.c | 183 +- src/backend/optimizer/plan/initsplan.c | 165 +- src/backend/optimizer/plan/planmain.c | 15 +- src/backend/optimizer/plan/planner.c | 222 +- src/backend/optimizer/plan/setrefs.c | 74 +- src/backend/optimizer/plan/subselect.c | 173 +- src/backend/optimizer/prep/prepjointree.c | 107 +- src/backend/optimizer/prep/prepqual.c | 18 +- src/backend/optimizer/prep/preptlist.c | 24 +- src/backend/optimizer/prep/prepunion.c | 20 +- src/backend/optimizer/util/clauses.c | 236 ++- src/backend/optimizer/util/joininfo.c | 14 +- src/backend/optimizer/util/pathnode.c | 29 +- src/backend/optimizer/util/plancat.c | 28 +- src/backend/optimizer/util/relnode.c | 9 +- src/backend/optimizer/util/restrictinfo.c | 17 +- src/backend/optimizer/util/tlist.c | 6 +- src/backend/optimizer/util/var.c | 43 +- src/backend/parser/analyze.c | 249 +-- src/backend/parser/parse_agg.c | 99 +- src/backend/parser/parse_clause.c | 54 +- src/backend/parser/parse_coerce.c | 212 +- src/backend/parser/parse_expr.c | 164 +- src/backend/parser/parse_func.c | 82 +- src/backend/parser/parse_node.c | 10 +- src/backend/parser/parse_oper.c | 65 +- src/backend/parser/parse_relation.c | 43 +- src/backend/parser/parse_target.c | 22 +- src/backend/parser/parse_type.c | 8 +- src/backend/port/beos/sem.c | 4 +- src/backend/port/dynloader/darwin.c | 4 +- src/backend/port/dynloader/linux.c | 4 +- src/backend/port/dynloader/linux.h | 3 +- src/backend/port/dynloader/win32.c | 8 +- src/backend/port/ipc_test.c | 14 +- src/backend/port/posix_sema.c | 3 +- src/backend/port/sysv_sema.c | 10 +- src/backend/port/sysv_shmem.c | 34 +- src/backend/port/win32/sema.c | 13 +- src/backend/postmaster/pgstat.c | 67 +- src/backend/postmaster/postmaster.c | 231 ++- src/backend/regex/regc_color.c | 412 ++-- src/backend/regex/regc_cvec.c | 185 +- src/backend/regex/regc_lex.c | 1506 +++++++------- src/backend/regex/regc_locale.c | 968 +++++---- src/backend/regex/regc_nfa.c | 856 ++++---- src/backend/regex/regcomp.c | 1838 ++++++++-------- src/backend/regex/rege_dfa.c | 416 ++-- src/backend/regex/regerror.c | 118 +- src/backend/regex/regexec.c | 776 +++---- src/backend/regex/regfree.c | 16 +- src/backend/rewrite/rewriteDefine.c | 26 +- src/backend/rewrite/rewriteHandler.c | 113 +- src/backend/rewrite/rewriteManip.c | 17 +- src/backend/storage/buffer/bufmgr.c | 22 +- src/backend/storage/file/fd.c | 14 +- src/backend/storage/freespace/freespace.c | 215 +- src/backend/storage/ipc/ipc.c | 6 +- src/backend/storage/ipc/ipci.c | 3 +- src/backend/storage/ipc/sinval.c | 9 +- src/backend/storage/lmgr/deadlock.c | 35 +- src/backend/storage/lmgr/lock.c | 65 +- src/backend/storage/lmgr/proc.c | 25 +- src/backend/storage/page/bufpage.c | 15 +- src/backend/storage/smgr/md.c | 15 +- src/backend/tcop/dest.c | 9 +- src/backend/tcop/fastpath.c | 56 +- src/backend/tcop/postgres.c | 406 ++-- src/backend/tcop/pquery.c | 229 +- src/backend/tcop/utility.c | 145 +- src/backend/utils/adt/acl.c | 89 +- src/backend/utils/adt/array_userfuncs.c | 91 +- src/backend/utils/adt/arrayfuncs.c | 230 +- src/backend/utils/adt/ascii.c | 22 +- src/backend/utils/adt/char.c | 4 +- src/backend/utils/adt/date.c | 70 +- src/backend/utils/adt/datetime.c | 86 +- src/backend/utils/adt/float.c | 10 +- src/backend/utils/adt/formatting.c | 81 +- src/backend/utils/adt/geo_ops.c | 16 +- src/backend/utils/adt/inet_net_ntop.c | 178 +- src/backend/utils/adt/inet_net_pton.c | 116 +- src/backend/utils/adt/int.c | 6 +- src/backend/utils/adt/int8.c | 6 +- src/backend/utils/adt/like.c | 4 +- src/backend/utils/adt/like_match.c | 4 +- src/backend/utils/adt/mac.c | 8 +- src/backend/utils/adt/nabstime.c | 22 +- src/backend/utils/adt/name.c | 4 +- src/backend/utils/adt/network.c | 256 +-- src/backend/utils/adt/not_in.c | 4 +- src/backend/utils/adt/numeric.c | 285 +-- src/backend/utils/adt/numutils.c | 4 +- src/backend/utils/adt/oid.c | 6 +- src/backend/utils/adt/oracle_compat.c | 17 +- src/backend/utils/adt/pg_locale.c | 8 +- src/backend/utils/adt/pgstatfuncs.c | 14 +- src/backend/utils/adt/pseudotypes.c | 4 +- src/backend/utils/adt/regexp.c | 32 +- src/backend/utils/adt/regproc.c | 14 +- src/backend/utils/adt/ri_triggers.c | 193 +- src/backend/utils/adt/ruleutils.c | 592 +++--- src/backend/utils/adt/selfuncs.c | 160 +- src/backend/utils/adt/sets.c | 7 +- src/backend/utils/adt/timestamp.c | 170 +- src/backend/utils/adt/varbit.c | 14 +- src/backend/utils/adt/varchar.c | 20 +- src/backend/utils/adt/varlena.c | 69 +- src/backend/utils/adt/xid.c | 4 +- src/backend/utils/cache/catcache.c | 6 +- src/backend/utils/cache/inval.c | 4 +- src/backend/utils/cache/lsyscache.c | 10 +- src/backend/utils/cache/relcache.c | 62 +- src/backend/utils/error/elog.c | 175 +- src/backend/utils/fmgr/dfmgr.c | 8 +- src/backend/utils/fmgr/fmgr.c | 32 +- src/backend/utils/init/findbe.c | 9 +- src/backend/utils/init/miscinit.c | 94 +- src/backend/utils/init/postinit.c | 28 +- src/backend/utils/mb/conv.c | 10 +- src/backend/utils/mb/mbutils.c | 26 +- src/backend/utils/mb/wchar.c | 10 +- src/backend/utils/misc/guc.c | 135 +- src/backend/utils/misc/help_config.c | 24 +- src/backend/utils/mmgr/aset.c | 22 +- src/backend/utils/mmgr/mcxt.c | 7 +- src/backend/utils/mmgr/portalmem.c | 53 +- src/backend/utils/sort/logtape.c | 6 +- src/backend/utils/sort/tuplesort.c | 14 +- src/backend/utils/sort/tuplestore.c | 37 +- src/backend/utils/time/tqual.c | 34 +- src/bin/pg_controldata/pg_controldata.c | 24 +- src/bin/pg_dump/common.c | 8 +- src/bin/pg_dump/dumputils.c | 75 +- src/bin/pg_dump/dumputils.h | 12 +- src/bin/pg_dump/pg_backup_archiver.c | 54 +- src/bin/pg_dump/pg_backup_archiver.h | 12 +- src/bin/pg_dump/pg_backup_custom.c | 20 +- src/bin/pg_dump/pg_backup_tar.c | 23 +- src/bin/pg_dump/pg_dump.c | 161 +- src/bin/pg_dump/pg_dump.h | 6 +- src/bin/pg_dump/pg_dumpall.c | 14 +- src/bin/pg_dump/pg_restore.c | 6 +- src/bin/pg_encoding/pg_encoding.c | 10 +- src/bin/pg_resetxlog/pg_resetxlog.c | 6 +- src/bin/psql/command.c | 32 +- src/bin/psql/common.c | 220 +- src/bin/psql/copy.c | 17 +- src/bin/psql/describe.c | 61 +- src/bin/psql/help.c | 14 +- src/bin/psql/input.c | 56 +- src/bin/psql/large_obj.c | 6 +- src/bin/psql/mainloop.c | 67 +- src/bin/psql/mbprint.c | 8 +- src/bin/psql/print.c | 20 +- src/bin/psql/print.h | 5 +- src/bin/psql/prompt.c | 60 +- src/bin/psql/sprompt.c | 13 +- src/bin/psql/startup.c | 8 +- src/bin/psql/stringutils.c | 31 +- src/bin/psql/tab-complete.c | 163 +- src/bin/psql/variables.c | 56 +- src/bin/psql/variables.h | 37 +- src/bin/scripts/clusterdb.c | 30 +- src/bin/scripts/common.c | 6 +- src/bin/scripts/common.h | 19 +- src/bin/scripts/createdb.c | 4 +- src/bin/scripts/createlang.c | 20 +- src/bin/scripts/createuser.c | 11 +- src/bin/scripts/dropdb.c | 4 +- src/bin/scripts/droplang.c | 15 +- src/bin/scripts/vacuumdb.c | 34 +- src/include/access/genam.h | 12 +- src/include/access/heapam.h | 4 +- src/include/access/nbtree.h | 33 +- src/include/access/printtup.h | 8 +- src/include/access/relscan.h | 6 +- src/include/access/slru.h | 22 +- src/include/access/xact.h | 12 +- src/include/access/xlog.h | 4 +- src/include/c.h | 25 +- src/include/catalog/catversion.h | 4 +- src/include/catalog/dependency.h | 10 +- src/include/catalog/pg_am.h | 4 +- src/include/catalog/pg_amproc.h | 28 +- src/include/catalog/pg_attribute.h | 8 +- src/include/catalog/pg_cast.h | 18 +- src/include/catalog/pg_constraint.h | 13 +- src/include/catalog/pg_opclass.h | 6 +- src/include/catalog/pg_operator.h | 32 +- src/include/catalog/pg_proc.h | 114 +- src/include/catalog/pg_statistic.h | 8 +- src/include/catalog/pg_type.h | 32 +- src/include/commands/alter.h | 4 +- src/include/commands/dbcommands.h | 6 +- src/include/commands/explain.h | 4 +- src/include/commands/portalcmds.h | 6 +- src/include/commands/prepare.h | 18 +- src/include/commands/sequence.h | 4 +- src/include/commands/trigger.h | 28 +- src/include/commands/typecmds.h | 4 +- src/include/executor/execdesc.h | 8 +- src/include/executor/executor.h | 104 +- src/include/executor/hashjoin.h | 7 +- src/include/executor/nodeHash.h | 4 +- src/include/executor/nodeSeqscan.h | 12 +- src/include/executor/nodeSubplan.h | 16 +- src/include/executor/spi.h | 6 +- src/include/executor/spi_priv.h | 7 +- src/include/executor/tstoreReceiver.h | 6 +- src/include/getaddrinfo.h | 35 +- src/include/getopt_long.h | 24 +- src/include/lib/stringinfo.h | 7 +- src/include/libpq/crypt.h | 4 +- src/include/libpq/ip.h | 34 +- src/include/libpq/libpq-be.h | 13 +- src/include/libpq/libpq.h | 18 +- src/include/libpq/pqcomm.h | 38 +- src/include/libpq/pqformat.h | 4 +- src/include/mb/pg_wchar.h | 4 +- src/include/miscadmin.h | 12 +- src/include/nodes/bitmapset.h | 58 +- src/include/nodes/execnodes.h | 151 +- src/include/nodes/makefuncs.h | 10 +- src/include/nodes/nodes.h | 6 +- src/include/nodes/params.h | 8 +- src/include/nodes/parsenodes.h | 45 +- src/include/nodes/pg_list.h | 14 +- src/include/nodes/plannodes.h | 10 +- src/include/nodes/primnodes.h | 79 +- src/include/nodes/relation.h | 37 +- src/include/optimizer/clauses.h | 20 +- src/include/optimizer/cost.h | 38 +- src/include/optimizer/geqo_misc.h | 3 +- src/include/optimizer/joininfo.h | 10 +- src/include/optimizer/pathnode.h | 16 +- src/include/optimizer/paths.h | 12 +- src/include/optimizer/plancat.h | 8 +- src/include/optimizer/planmain.h | 32 +- src/include/optimizer/prep.h | 4 +- src/include/optimizer/restrictinfo.h | 12 +- src/include/optimizer/tlist.h | 4 +- src/include/parser/analyze.h | 4 +- src/include/parser/parse_agg.h | 14 +- src/include/parser/parse_clause.h | 10 +- src/include/parser/parse_coerce.h | 44 +- src/include/parser/parse_func.h | 32 +- src/include/parser/parse_node.h | 5 +- src/include/parser/parse_oper.h | 18 +- src/include/pg_config_manual.h | 38 +- src/include/pgstat.h | 4 +- src/include/port.h | 54 +- src/include/port/bsdi.h | 1 - src/include/port/cygwin.h | 3 +- src/include/port/freebsd.h | 1 + src/include/port/hpux.h | 1 + src/include/port/netbsd.h | 1 + src/include/port/openbsd.h | 1 + src/include/port/win32.h | 63 +- src/include/port/win32/dlfcn.h | 1 + src/include/port/win32/grp.h | 1 + src/include/port/win32/netdb.h | 1 + src/include/port/win32/netinet/in.h | 1 - src/include/port/win32/pwd.h | 1 + src/include/port/win32/sys/socket.h | 1 + src/include/port/win32/sys/wait.h | 1 + src/include/postgres.h | 3 +- src/include/regex/regcustom.h | 52 +- src/include/regex/regerrs.h | 91 +- src/include/regex/regex.h | 169 +- src/include/regex/regguts.h | 390 ++-- src/include/storage/bufmgr.h | 6 +- src/include/storage/freespace.h | 16 +- src/include/storage/lock.h | 13 +- src/include/tcop/dest.h | 22 +- src/include/tcop/pquery.h | 22 +- src/include/tcop/tcopprot.h | 5 +- src/include/utils/acl.h | 10 +- src/include/utils/array.h | 53 +- src/include/utils/builtins.h | 4 +- src/include/utils/datetime.h | 6 +- src/include/utils/elog.h | 50 +- src/include/utils/errcodes.h | 24 +- src/include/utils/guc.h | 8 +- src/include/utils/guc_tables.h | 24 +- src/include/utils/help_config.h | 6 +- src/include/utils/inet.h | 4 +- src/include/utils/lsyscache.h | 20 +- src/include/utils/memutils.h | 7 +- src/include/utils/palloc.h | 6 +- src/include/utils/portal.h | 63 +- src/include/utils/rel.h | 6 +- src/include/utils/selfuncs.h | 8 +- src/include/utils/tuplestore.h | 8 +- src/interfaces/ecpg/compatlib/informix.c | 632 +++--- src/interfaces/ecpg/ecpglib/connect.c | 110 +- src/interfaces/ecpg/ecpglib/data.c | 47 +- src/interfaces/ecpg/ecpglib/descriptor.c | 4 +- src/interfaces/ecpg/ecpglib/error.c | 13 +- src/interfaces/ecpg/ecpglib/execute.c | 161 +- src/interfaces/ecpg/ecpglib/extern.h | 12 +- src/interfaces/ecpg/ecpglib/misc.c | 99 +- src/interfaces/ecpg/ecpglib/prepare.c | 20 +- src/interfaces/ecpg/include/datetime.h | 18 +- src/interfaces/ecpg/include/decimal.h | 31 +- src/interfaces/ecpg/include/ecpg_informix.h | 36 +- src/interfaces/ecpg/include/ecpgerrno.h | 4 +- src/interfaces/ecpg/include/ecpglib.h | 9 +- src/interfaces/ecpg/include/ecpgtype.h | 18 +- src/interfaces/ecpg/include/pgtypes_date.h | 15 +- src/interfaces/ecpg/include/pgtypes_error.h | 5 +- .../ecpg/include/pgtypes_interval.h | 15 +- src/interfaces/ecpg/include/pgtypes_numeric.h | 88 +- .../ecpg/include/pgtypes_timestamp.h | 10 +- src/interfaces/ecpg/include/sqlca.h | 2 +- src/interfaces/ecpg/include/sqlda.h | 1 + src/interfaces/ecpg/include/sqltypes.h | 22 +- src/interfaces/ecpg/pgtypeslib/common.c | 90 +- src/interfaces/ecpg/pgtypeslib/datetime.c | 522 +++-- src/interfaces/ecpg/pgtypeslib/dt.h | 58 +- src/interfaces/ecpg/pgtypeslib/dt_common.c | 740 ++++--- src/interfaces/ecpg/pgtypeslib/extern.h | 38 +- src/interfaces/ecpg/pgtypeslib/interval.c | 17 +- src/interfaces/ecpg/pgtypeslib/numeric.c | 245 ++- src/interfaces/ecpg/pgtypeslib/timestamp.c | 315 +-- src/interfaces/ecpg/preproc/c_keywords.c | 10 +- src/interfaces/ecpg/preproc/ecpg.c | 40 +- src/interfaces/ecpg/preproc/extern.h | 8 +- src/interfaces/ecpg/preproc/type.c | 81 +- src/interfaces/ecpg/preproc/type.h | 41 +- src/interfaces/ecpg/preproc/variable.c | 158 +- src/interfaces/libpgtcl/pgtclCmds.c | 12 +- src/interfaces/libpgtcl/pgtclCmds.h | 40 +- src/interfaces/libpgtcl/pgtclId.c | 18 +- src/interfaces/libpgtcl/pgtclId.h | 6 +- src/interfaces/libpq/fe-auth.c | 28 +- src/interfaces/libpq/fe-connect.c | 240 ++- src/interfaces/libpq/fe-exec.c | 108 +- src/interfaces/libpq/fe-lobj.c | 12 +- src/interfaces/libpq/fe-misc.c | 101 +- src/interfaces/libpq/fe-protocol2.c | 103 +- src/interfaces/libpq/fe-protocol3.c | 174 +- src/interfaces/libpq/fe-secure.c | 141 +- src/interfaces/libpq/libpq-fe.h | 64 +- src/interfaces/libpq/libpq-int.h | 70 +- src/pl/plperl/plperl.c | 23 +- src/pl/plpgsql/src/pl_comp.c | 129 +- src/pl/plpgsql/src/pl_exec.c | 159 +- src/pl/plpgsql/src/pl_funcs.c | 8 +- src/pl/plpgsql/src/pl_handler.c | 8 +- src/pl/plpgsql/src/plpgsql.h | 23 +- src/pl/plpython/plpython.c | 58 +- src/pl/tcl/pltcl.c | 16 +- src/port/copydir.c | 29 +- src/port/crypt.c | 853 ++++---- src/port/dirmod.c | 22 +- src/port/fseeko.c | 9 +- src/port/getaddrinfo.c | 66 +- src/port/getopt.c | 2 +- src/port/getopt_long.c | 14 +- src/port/gettimeofday.c | 15 +- src/port/path.c | 24 +- src/port/threads.c | 4 +- src/test/examples/testlibpq.c | 8 +- src/test/examples/testlibpq2.c | 27 +- src/test/examples/testlibpq3.c | 12 +- src/test/regress/regress.c | 6 +- src/tutorial/complex.c | 2 +- 554 files changed, 24888 insertions(+), 21245 deletions(-) diff --git a/contrib/btree_gist/btree_common.c b/contrib/btree_gist/btree_common.c index 9873af911c..9306076e0a 100644 --- a/contrib/btree_gist/btree_common.c +++ b/contrib/btree_gist/btree_common.c @@ -1,7 +1,7 @@ #include "btree_gist.h" PG_FUNCTION_INFO_V1(btree_decompress); -Datum btree_decompress(PG_FUNCTION_ARGS); +Datum btree_decompress(PG_FUNCTION_ARGS); /* ** GiST DeCompress methods diff --git a/contrib/btree_gist/btree_gist.h b/contrib/btree_gist/btree_gist.h index ebcecf4cc5..ecbabc2dbb 100644 --- a/contrib/btree_gist/btree_gist.h +++ b/contrib/btree_gist/btree_gist.h @@ -23,4 +23,3 @@ typedef struct rix extern GIST_SPLITVEC *btree_picksplit(bytea *entryvec, GIST_SPLITVEC *v, BINARY_UNION bu, CMPFUNC cmp); - diff --git a/contrib/cube/cube.c b/contrib/cube/cube.c index 5d8bcf75b5..396253261d 100644 --- a/contrib/cube/cube.c +++ b/contrib/cube/cube.c @@ -28,11 +28,11 @@ extern int cube_yyparse(); NDBOX *cube_in(char *str); NDBOX *cube(text *str); char *cube_out(NDBOX * cube); -NDBOX *cube_f8(double *); -NDBOX *cube_f8_f8(double *, double *); -NDBOX *cube_c_f8(NDBOX *, double *); -NDBOX *cube_c_f8_f8(NDBOX *, double *, double *); -int4 cube_dim(NDBOX * a); +NDBOX *cube_f8(double *); +NDBOX *cube_f8_f8(double *, double *); +NDBOX *cube_c_f8(NDBOX *, double *); +NDBOX *cube_c_f8_f8(NDBOX *, double *, double *); +int4 cube_dim(NDBOX * a); double *cube_ll_coord(NDBOX * a, int4 n); double *cube_ur_coord(NDBOX * a, int4 n); @@ -123,7 +123,7 @@ cube_out(NDBOX * cube) bool equal = true; int dim = cube->dim; int i; - int ndig; + int ndig; initStringInfo(&buf); @@ -131,7 +131,8 @@ cube_out(NDBOX * cube) * Get the number of digits to display. */ ndig = DBL_DIG + extra_float_digits; - if (ndig < 1) ndig = 1; + if (ndig < 1) + ndig = 1; /* * while printing the first (LL) corner, check if it is equal to the @@ -1192,7 +1193,8 @@ cube_enlarge(NDBOX * a, double *r, int4 n) j, k; - if (n > CUBE_MAX_DIM) n = CUBE_MAX_DIM; + if (n > CUBE_MAX_DIM) + n = CUBE_MAX_DIM; if (*r > 0 && n > 0) dim = n; if (a->dim > dim) @@ -1234,14 +1236,15 @@ NDBOX * cube_f8(double *x1) { NDBOX *result; - int size; + int size; + size = offsetof(NDBOX, x[0]) + sizeof(double) * 2; result = (NDBOX *) palloc(size); memset(result, 0, size); result->size = size; result->dim = 1; - result->x[0] = *x1; - result->x[1] = *x1; + result->x[0] = *x1; + result->x[1] = *x1; return result; } @@ -1250,56 +1253,61 @@ NDBOX * cube_f8_f8(double *x1, double *x2) { NDBOX *result; - int size; + int size; + size = offsetof(NDBOX, x[0]) + sizeof(double) * 2; result = (NDBOX *) palloc(size); memset(result, 0, size); result->size = size; result->dim = 1; - result->x[0] = *x1; - result->x[1] = *x2; + result->x[0] = *x1; + result->x[1] = *x2; return result; } /* Add a dimension to an existing cube with the same values for the new coordinate */ NDBOX * -cube_c_f8(NDBOX *c, double *x1) +cube_c_f8(NDBOX * c, double *x1) { NDBOX *result; - int size; - int i; - size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) * 2; + int size; + int i; + + size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) *2; result = (NDBOX *) palloc(size); memset(result, 0, size); result->size = size; result->dim = c->dim + 1; - for (i = 0; i < c->dim; i++) { - result->x[i] = c->x[i]; - result->x[result->dim + i] = c->x[c->dim + i]; - } - result->x[result->dim - 1] = *x1; - result->x[2 * result->dim - 1] = *x1; + for (i = 0; i < c->dim; i++) + { + result->x[i] = c->x[i]; + result->x[result->dim + i] = c->x[c->dim + i]; + } + result->x[result->dim - 1] = *x1; + result->x[2 * result->dim - 1] = *x1; return result; } /* Add a dimension to an existing cube */ NDBOX * -cube_c_f8_f8(NDBOX *c, double *x1, double *x2) +cube_c_f8_f8(NDBOX * c, double *x1, double *x2) { NDBOX *result; - int size; - int i; - size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) * 2; + int size; + int i; + + size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) *2; result = (NDBOX *) palloc(size); memset(result, 0, size); result->size = size; result->dim = c->dim + 1; - for (i = 0; i < c->dim; i++) { - result->x[i] = c->x[i]; - result->x[result->dim + i] = c->x[c->dim + i]; - } - result->x[result->dim - 1] = *x1; - result->x[2 * result->dim - 1] = *x2; + for (i = 0; i < c->dim; i++) + { + result->x[i] = c->x[i]; + result->x[result->dim + i] = c->x[c->dim + i]; + } + result->x[result->dim - 1] = *x1; + result->x[2 * result->dim - 1] = *x2; return result; } diff --git a/contrib/dbase/dbf2pg.c b/contrib/dbase/dbf2pg.c index 0ae53cd126..d679eed1ad 100644 --- a/contrib/dbase/dbf2pg.c +++ b/contrib/dbase/dbf2pg.c @@ -443,17 +443,15 @@ do_inserts(PGconn *conn, char *table, dbhead * dbh) if (result == DBF_VALID) { query[0] = '\0'; - j = 0; /* counter for fields in the output */ + j = 0; /* counter for fields in the output */ for (h = 0; h < dbh->db_nfields; h++) { - if (!strlen(fields[h].db_name)) /* When the new fieldname is empty, the field is skipped */ - { + if (!strlen(fields[h].db_name)) /* When the new fieldname + * is empty, the field is + * skipped */ continue; - } else - { j++; - } if (j > 1) /* not for the first field! */ strcat(query, "\t"); /* COPY statement field diff --git a/contrib/dblink/dblink.c b/contrib/dblink/dblink.c index 158942a4c0..629f93f1c6 100644 --- a/contrib/dblink/dblink.c +++ b/contrib/dblink/dblink.c @@ -61,17 +61,17 @@ typedef struct remoteConn { - PGconn *con; /* Hold the remote connection */ - bool remoteTrFlag; /* Indicates whether or not a transaction - * on remote database is in progress*/ -} remoteConn; + PGconn *con; /* Hold the remote connection */ + bool remoteTrFlag; /* Indicates whether or not a transaction + * on remote database is in progress */ +} remoteConn; /* * Internal declarations */ static remoteConn *getConnectionByName(const char *name); static HTAB *createConnHash(void); -static void createNewConnection(const char *name,remoteConn *con); +static void createNewConnection(const char *name, remoteConn * con); static void deleteConnection(const char *name); static char **get_pkey_attnames(Oid relid, int16 *numatts); static char *get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals); @@ -86,15 +86,15 @@ static TupleDesc pgresultGetTupleDesc(PGresult *res); static char *generate_relation_name(Oid relid); /* Global */ -List *res_id = NIL; -int res_id_index = 0; -PGconn *persistent_conn = NULL; -static HTAB *remoteConnHash=NULL; +List *res_id = NIL; +int res_id_index = 0; +PGconn *persistent_conn = NULL; +static HTAB *remoteConnHash = NULL; -/* +/* Following is list that holds multiple remote connections. Calling convention of each dblink function changes to accept -connection name as the first parameter. The connection list is +connection name as the first parameter. The connection list is much like ecpg e.g. a mapping between a name and a PGconn object. */ @@ -102,7 +102,7 @@ typedef struct remoteConnHashEnt { char name[NAMEDATALEN]; remoteConn *rcon; -} remoteConnHashEnt; +} remoteConnHashEnt; /* initial number of connection hashes */ #define NUMCONN 16 @@ -186,18 +186,18 @@ dblink_connect(PG_FUNCTION_ARGS) PGconn *conn = NULL; remoteConn *rcon = NULL; - if(PG_NARGS()==2) + if (PG_NARGS() == 2) { connstr = GET_STR(PG_GETARG_TEXT_P(1)); connname = GET_STR(PG_GETARG_TEXT_P(0)); } - else if(PG_NARGS()==1) + else if (PG_NARGS() == 1) connstr = GET_STR(PG_GETARG_TEXT_P(0)); oldcontext = MemoryContextSwitchTo(TopMemoryContext); - if(connname) - rcon=(remoteConn *) palloc(sizeof(remoteConn)); + if (connname) + rcon = (remoteConn *) palloc(sizeof(remoteConn)); conn = PQconnectdb(connstr); MemoryContextSwitchTo(oldcontext); @@ -206,16 +206,16 @@ dblink_connect(PG_FUNCTION_ARGS) { msg = pstrdup(PQerrorMessage(conn)); PQfinish(conn); - if(rcon) + if (rcon) pfree(rcon); ereport(ERROR, - (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION), - errmsg("could not establish connection"), - errdetail("%s", msg))); + (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION), + errmsg("could not establish connection"), + errdetail("%s", msg))); } - if(connname) + if (connname) { rcon->con = conn; createNewConnection(connname, rcon); @@ -237,7 +237,7 @@ dblink_disconnect(PG_FUNCTION_ARGS) remoteConn *rcon = NULL; PGconn *conn = NULL; - if (PG_NARGS() ==1 ) + if (PG_NARGS() == 1) { conname = GET_STR(PG_GETARG_TEXT_P(0)); rcon = getConnectionByName(conname); @@ -276,13 +276,13 @@ dblink_open(PG_FUNCTION_ARGS) StringInfo str = makeStringInfo(); remoteConn *rcon = NULL; - if(PG_NARGS() == 2) + if (PG_NARGS() == 2) { curname = GET_STR(PG_GETARG_TEXT_P(0)); sql = GET_STR(PG_GETARG_TEXT_P(1)); conn = persistent_conn; } - else if(PG_NARGS() == 3) + else if (PG_NARGS() == 3) { conname = GET_STR(PG_GETARG_TEXT_P(0)); curname = GET_STR(PG_GETARG_TEXT_P(1)); @@ -333,12 +333,12 @@ dblink_close(PG_FUNCTION_ARGS) curname = GET_STR(PG_GETARG_TEXT_P(0)); conn = persistent_conn; } - else if (PG_NARGS()==2) + else if (PG_NARGS() == 2) { conname = GET_STR(PG_GETARG_TEXT_P(0)); curname = GET_STR(PG_GETARG_TEXT_P(1)); rcon = getConnectionByName(conname); - if(rcon) + if (rcon) conn = rcon->con; } @@ -381,7 +381,7 @@ dblink_fetch(PG_FUNCTION_ARGS) PGresult *res = NULL; MemoryContext oldcontext; char *conname = NULL; - remoteConn *rcon=NULL; + remoteConn *rcon = NULL; /* stuff done only on the first call of the function */ if (SRF_IS_FIRSTCALL()) @@ -401,7 +401,7 @@ dblink_fetch(PG_FUNCTION_ARGS) howmany = PG_GETARG_INT32(2); rcon = getConnectionByName(conname); - if(rcon) + if (rcon) conn = rcon->con; } else if (PG_NARGS() == 2) @@ -411,7 +411,7 @@ dblink_fetch(PG_FUNCTION_ARGS) conn = persistent_conn; } - if(!conn) + if (!conn) DBLINK_CONN_NOT_AVAIL; /* create a function context for cross-call persistence */ @@ -429,9 +429,7 @@ dblink_fetch(PG_FUNCTION_ARGS) if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK)) - { DBLINK_RES_ERROR("sql error"); - } else if (PQresultStatus(res) == PGRES_COMMAND_OK) { /* cursor does not exist - closed already or bad name */ @@ -549,7 +547,7 @@ dblink_record(PG_FUNCTION_ARGS) char *connstr = NULL; char *sql = NULL; char *conname = NULL; - remoteConn *rcon=NULL; + remoteConn *rcon = NULL; /* create a function context for cross-call persistence */ funcctx = SRF_FIRSTCALL_INIT(); @@ -574,7 +572,7 @@ dblink_record(PG_FUNCTION_ARGS) /* shouldn't happen */ elog(ERROR, "wrong number of arguments"); - if(!conn) + if (!conn) DBLINK_CONN_NOT_AVAIL; res = PQexec(conn, sql); @@ -591,8 +589,8 @@ dblink_record(PG_FUNCTION_ARGS) TEXTOID, -1, 0, false); /* - * and save a copy of the command status string to return - * as our result tuple + * and save a copy of the command status string to return as + * our result tuple */ sql_cmd_status = PQcmdStatus(res); funcctx->max_calls = 1; @@ -707,7 +705,7 @@ dblink_exec(PG_FUNCTION_ARGS) char *connstr = NULL; char *sql = NULL; char *conname = NULL; - remoteConn *rcon=NULL; + remoteConn *rcon = NULL; bool freeconn = true; if (PG_NARGS() == 2) @@ -724,7 +722,7 @@ dblink_exec(PG_FUNCTION_ARGS) /* shouldn't happen */ elog(ERROR, "wrong number of arguments"); - if(!conn) + if (!conn) DBLINK_CONN_NOT_AVAIL; res = PQexec(conn, sql); @@ -741,15 +739,15 @@ dblink_exec(PG_FUNCTION_ARGS) TEXTOID, -1, 0, false); /* - * and save a copy of the command status string to return as - * our result tuple + * and save a copy of the command status string to return as our + * result tuple */ sql_cmd_status = GET_TEXT(PQcmdStatus(res)); } else ereport(ERROR, - (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED), - errmsg("statement returning results not allowed"))); + (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED), + errmsg("statement returning results not allowed"))); PQclear(res); @@ -802,6 +800,7 @@ dblink_get_pkey(PG_FUNCTION_ARGS) (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation \"%s\" does not exist", GET_STR(PG_GETARG_TEXT_P(0))))); + /* * need a tuple descriptor representing one INT and one TEXT * column @@ -980,8 +979,8 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS) if (src_nitems != pknumatts) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("source key array length must match number of key " \ - "attributes"))); + errmsg("source key array length must match number of key " \ + "attributes"))); /* * get array of pointers to c-strings from the input source array @@ -1013,8 +1012,8 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS) if (tgt_nitems != pknumatts) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("target key array length must match number of key " \ - "attributes"))); + errmsg("target key array length must match number of key " \ + "attributes"))); /* * get array of pointers to c-strings from the input target array @@ -1126,8 +1125,8 @@ dblink_build_sql_delete(PG_FUNCTION_ARGS) if (tgt_nitems != pknumatts) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("target key array length must match number of key " \ - "attributes"))); + errmsg("target key array length must match number of key " \ + "attributes"))); /* * get array of pointers to c-strings from the input target array @@ -1249,8 +1248,8 @@ dblink_build_sql_update(PG_FUNCTION_ARGS) if (src_nitems != pknumatts) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("source key array length must match number of key " \ - "attributes"))); + errmsg("source key array length must match number of key " \ + "attributes"))); /* * get array of pointers to c-strings from the input source array @@ -1282,8 +1281,8 @@ dblink_build_sql_update(PG_FUNCTION_ARGS) if (tgt_nitems != pknumatts) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("target key array length must match number of key " \ - "attributes"))); + errmsg("target key array length must match number of key " \ + "attributes"))); /* * get array of pointers to c-strings from the input target array @@ -1839,10 +1838,10 @@ pgresultGetTupleDesc(PGresult *res) ereport(ERROR, (errcode(ERRCODE_MOST_SPECIFIC_TYPE_MISMATCH), errmsg("field size mismatch"), - errdetail("Size of remote field \"%s\" does not match " \ - "size of local type \"%s\".", attname, - format_type_with_typemod(atttypid, - atttypmod)))); + errdetail("Size of remote field \"%s\" does not match " \ + "size of local type \"%s\".", attname, + format_type_with_typemod(atttypid, + atttypmod)))); attdim = 0; attisset = false; @@ -1893,50 +1892,50 @@ generate_relation_name(Oid relid) static remoteConn * getConnectionByName(const char *name) { - remoteConnHashEnt *hentry; - char key[NAMEDATALEN]; + remoteConnHashEnt *hentry; + char key[NAMEDATALEN]; - if(!remoteConnHash) - remoteConnHash=createConnHash(); + if (!remoteConnHash) + remoteConnHash = createConnHash(); MemSet(key, 0, NAMEDATALEN); snprintf(key, NAMEDATALEN - 1, "%s", name); - hentry = (remoteConnHashEnt*) hash_search(remoteConnHash, - key, HASH_FIND, NULL); + hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, + key, HASH_FIND, NULL); - if(hentry) - return(hentry->rcon); + if (hentry) + return (hentry->rcon); - return(NULL); + return (NULL); } static HTAB * createConnHash(void) { - HASHCTL ctl; - HTAB *ptr; + HASHCTL ctl; + HTAB *ptr; ctl.keysize = NAMEDATALEN; ctl.entrysize = sizeof(remoteConnHashEnt); - ptr=hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM); + ptr = hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM); - if(!ptr) + if (!ptr) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - return(ptr); + return (ptr); } static void -createNewConnection(const char *name, remoteConn *con) +createNewConnection(const char *name, remoteConn * con) { - remoteConnHashEnt *hentry; - bool found; - char key[NAMEDATALEN]; + remoteConnHashEnt *hentry; + bool found; + char key[NAMEDATALEN]; - if(!remoteConnHash) + if (!remoteConnHash) remoteConnHash = createConnHash(); MemSet(key, 0, NAMEDATALEN); @@ -1944,12 +1943,12 @@ createNewConnection(const char *name, remoteConn *con) hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key, HASH_ENTER, &found); - if(!hentry) + if (!hentry) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - if(found) + if (found) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("duplicate connection name"))); @@ -1961,12 +1960,12 @@ createNewConnection(const char *name, remoteConn *con) static void deleteConnection(const char *name) { - remoteConnHashEnt *hentry; - bool found; - char key[NAMEDATALEN]; + remoteConnHashEnt *hentry; + bool found; + char key[NAMEDATALEN]; - if(!remoteConnHash) - remoteConnHash=createConnHash(); + if (!remoteConnHash) + remoteConnHash = createConnHash(); MemSet(key, 0, NAMEDATALEN); snprintf(key, NAMEDATALEN - 1, "%s", name); @@ -1974,7 +1973,7 @@ deleteConnection(const char *name) hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key, HASH_REMOVE, &found); - if(!hentry) + if (!hentry) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("undefined connection name"))); diff --git a/contrib/dbmirror/pending.c b/contrib/dbmirror/pending.c index 5eebd1a1ba..cf00276a8f 100644 --- a/contrib/dbmirror/pending.c +++ b/contrib/dbmirror/pending.c @@ -1,6 +1,6 @@ /**************************************************************************** * pending.c - * $Id: pending.c,v 1.12 2003/07/24 17:52:20 tgl Exp $ + * $Id: pending.c,v 1.13 2003/08/04 00:43:10 momjian Exp $ * * This file contains a trigger for Postgresql-7.x to record changes to tables * to a pending table for mirroring. @@ -8,7 +8,7 @@ * * Written by Steven Singer (ssinger@navtechinc.com) * (c) 2001-2002 Navtech Systems Support Inc. - * ALL RIGHTS RESERVED + * ALL RIGHTS RESERVED * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without a written agreement @@ -79,8 +79,9 @@ recordchange(PG_FUNCTION_ARGS) HeapTuple retTuple = NULL; char *tblname; char op = 0; - char *schemaname; + char *schemaname; char *fullyqualtblname; + if (fcinfo->context != NULL) { @@ -94,13 +95,13 @@ recordchange(PG_FUNCTION_ARGS) tblname = SPI_getrelname(trigdata->tg_relation); #ifndef NOSCHEMAS schemaname = get_namespace_name(RelationGetNamespace(trigdata->tg_relation)); - fullyqualtblname = SPI_palloc(strlen(tblname) + - strlen(schemaname) + 6); - sprintf(fullyqualtblname,"\"%s\".\"%s\"", - schemaname,tblname); + fullyqualtblname = SPI_palloc(strlen(tblname) + + strlen(schemaname) + 6); + sprintf(fullyqualtblname, "\"%s\".\"%s\"", + schemaname, tblname); #else fullyqualtblname = SPI_palloc(strlen(tblname) + 3); - sprintf(fullyqualtblname,"\"%s\"",tblname); + sprintf(fullyqualtblname, "\"%s\"", tblname); #endif tupdesc = trigdata->tg_relation->rd_att; if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) @@ -166,8 +167,8 @@ storePending(char *cpTableName, HeapTuple tBeforeTuple, int iResult = 0; HeapTuple tCurTuple; - //Points the current tuple(before or after) - Datum saPlanData[4]; + /* Points the current tuple(before or after) */ + Datum saPlanData[4]; Oid taPlanArgTypes[3] = {NAMEOID, CHAROID, INT4OID}; void *vpPlan; @@ -253,7 +254,7 @@ storeKeyInfo(char *cpTableName, HeapTuple tTupleData, if (cpKeyData == NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - /* cpTableName already contains quotes... */ + /* cpTableName already contains quotes... */ errmsg("there is no PRIMARY KEY for table %s", cpTableName))); @@ -460,7 +461,7 @@ packageData(HeapTuple tTupleData, TupleDesc tTupleDesc, } else { - sprintf(cpFormatedPtr," "); + sprintf(cpFormatedPtr, " "); iUsedDataBlock++; cpFormatedPtr++; continue; @@ -508,8 +509,8 @@ packageData(HeapTuple tTupleData, TupleDesc tTupleDesc, if (tpPKeys != NULL) SPI_pfree(tpPKeys); #if defined DEBUG_OUTPUT - elog(NOTICE, "returning DataBlockSize:%d iUsedDataBlock:%d",iDataBlockSize, - iUsedDataBlock); + elog(NOTICE, "returning DataBlockSize:%d iUsedDataBlock:%d", iDataBlockSize, + iUsedDataBlock); #endif memset(cpDataBlock + iUsedDataBlock, 0, iDataBlockSize - iUsedDataBlock); diff --git a/contrib/dbsize/dbsize.c b/contrib/dbsize/dbsize.c index c474930ca9..0037c14e70 100644 --- a/contrib/dbsize/dbsize.c +++ b/contrib/dbsize/dbsize.c @@ -54,7 +54,7 @@ database_size(PG_FUNCTION_ARGS) if (!OidIsValid(dbid)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_DATABASE), - errmsg("database \"%s\" does not exist", NameStr(*dbname)))); + errmsg("database \"%s\" does not exist", NameStr(*dbname)))); dbpath = GetDatabasePath(dbid); diff --git a/contrib/earthdistance/earthdistance.c b/contrib/earthdistance/earthdistance.c index 19c81a5783..28ce40378c 100644 --- a/contrib/earthdistance/earthdistance.c +++ b/contrib/earthdistance/earthdistance.c @@ -6,8 +6,8 @@ /* Earth's radius is in statute miles. */ -const double EARTH_RADIUS = 3958.747716; -const double TWO_PI = 2.0 * M_PI; +const double EARTH_RADIUS = 3958.747716; +const double TWO_PI = 2.0 * M_PI; double *geo_distance(Point *pt1, Point *pt2); @@ -66,10 +66,11 @@ geo_distance(Point *pt1, Point *pt2) if (longdiff > M_PI) longdiff = TWO_PI - longdiff; - sino = sqrt(sin(fabs(lat1-lat2)/2.)*sin(fabs(lat1-lat2)/2.) + - cos(lat1) * cos(lat2) * sin(longdiff/2.)*sin(longdiff/2.)); - if (sino > 1.) sino = 1.; - *resultp = 2. * EARTH_RADIUS * asin(sino); + sino = sqrt(sin(fabs(lat1 - lat2) / 2.) * sin(fabs(lat1 - lat2) / 2.) + + cos(lat1) * cos(lat2) * sin(longdiff / 2.) * sin(longdiff / 2.)); + if (sino > 1.) + sino = 1.; + *resultp = 2. * EARTH_RADIUS * asin(sino); return resultp; } diff --git a/contrib/findoidjoins/findoidjoins.c b/contrib/findoidjoins/findoidjoins.c index 8eb27e42a5..4843c1f3e5 100644 --- a/contrib/findoidjoins/findoidjoins.c +++ b/contrib/findoidjoins/findoidjoins.c @@ -3,7 +3,7 @@ * * Copyright 2002 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/contrib/findoidjoins/Attic/findoidjoins.c,v 1.20 2003/05/14 03:25:56 tgl Exp $ + * $Header: /cvsroot/pgsql/contrib/findoidjoins/Attic/findoidjoins.c,v 1.21 2003/08/04 00:43:10 momjian Exp $ */ #include "postgres_fe.h" @@ -14,23 +14,24 @@ int main(int argc, char **argv) { - PGconn *conn; - PQExpBufferData sql; - PGresult *res; - PGresult *pkrel_res; - PGresult *fkrel_res; - char *fk_relname; - char *fk_nspname; - char *fk_attname; - char *pk_relname; - char *pk_nspname; - int fk, pk; /* loop counters */ + PGconn *conn; + PQExpBufferData sql; + PGresult *res; + PGresult *pkrel_res; + PGresult *fkrel_res; + char *fk_relname; + char *fk_nspname; + char *fk_attname; + char *pk_relname; + char *pk_nspname; + int fk, + pk; /* loop counters */ if (argc != 2) { fprintf(stderr, "Usage: %s database\n", argv[0]); exit(EXIT_FAILURE); - } + } initPQExpBuffer(&sql); @@ -48,13 +49,13 @@ main(int argc, char **argv) resetPQExpBuffer(&sql); appendPQExpBuffer(&sql, "%s", - "SET search_path = public;" - "SELECT c.relname, (SELECT nspname FROM " - "pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname " - "FROM pg_catalog.pg_class c " - "WHERE c.relkind = 'r' " - "AND c.relhasoids " - "ORDER BY nspname, c.relname" + "SET search_path = public;" + "SELECT c.relname, (SELECT nspname FROM " + "pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname " + "FROM pg_catalog.pg_class c " + "WHERE c.relkind = 'r' " + "AND c.relhasoids " + "ORDER BY nspname, c.relname" ); res = PQexec(conn, sql.data); @@ -70,20 +71,20 @@ main(int argc, char **argv) resetPQExpBuffer(&sql); appendPQExpBuffer(&sql, "%s", - "SELECT c.relname, " - "(SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname, " - "a.attname " - "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a " - "WHERE a.attnum > 0 AND c.relkind = 'r' " - "AND a.attrelid = c.oid " - "AND a.atttypid IN ('pg_catalog.oid'::regtype, " - " 'pg_catalog.regclass'::regtype, " - " 'pg_catalog.regoper'::regtype, " - " 'pg_catalog.regoperator'::regtype, " - " 'pg_catalog.regproc'::regtype, " - " 'pg_catalog.regprocedure'::regtype, " - " 'pg_catalog.regtype'::regtype) " - "ORDER BY nspname, c.relname, a.attnum" + "SELECT c.relname, " + "(SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname, " + "a.attname " + "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a " + "WHERE a.attnum > 0 AND c.relkind = 'r' " + "AND a.attrelid = c.oid " + "AND a.atttypid IN ('pg_catalog.oid'::regtype, " + " 'pg_catalog.regclass'::regtype, " + " 'pg_catalog.regoper'::regtype, " + " 'pg_catalog.regoperator'::regtype, " + " 'pg_catalog.regproc'::regtype, " + " 'pg_catalog.regprocedure'::regtype, " + " 'pg_catalog.regtype'::regtype) " + "ORDER BY nspname, c.relname, a.attnum" ); res = PQexec(conn, sql.data); @@ -95,8 +96,8 @@ main(int argc, char **argv) fkrel_res = res; /* - * For each column and each relation-having-OIDs, look to see if - * the column contains any values matching entries in the relation. + * For each column and each relation-having-OIDs, look to see if the + * column contains any values matching entries in the relation. */ for (fk = 0; fk < PQntuples(fkrel_res); fk++) @@ -113,12 +114,12 @@ main(int argc, char **argv) resetPQExpBuffer(&sql); appendPQExpBuffer(&sql, - "SELECT 1 " - "FROM \"%s\".\"%s\" t1, " - "\"%s\".\"%s\" t2 " - "WHERE t1.\"%s\"::pg_catalog.oid = t2.oid " - "LIMIT 1", - fk_nspname, fk_relname, pk_nspname, pk_relname, fk_attname); + "SELECT 1 " + "FROM \"%s\".\"%s\" t1, " + "\"%s\".\"%s\" t2 " + "WHERE t1.\"%s\"::pg_catalog.oid = t2.oid " + "LIMIT 1", + fk_nspname, fk_relname, pk_nspname, pk_relname, fk_attname); res = PQexec(conn, sql.data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) diff --git a/contrib/fulltextindex/fti.c b/contrib/fulltextindex/fti.c index 38dba1ce30..e5095ff1a1 100644 --- a/contrib/fulltextindex/fti.c +++ b/contrib/fulltextindex/fti.c @@ -304,7 +304,7 @@ fti(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("column \"%s\" of \"%s\" does not exist", - args[i + 1], indexname))); + args[i + 1], indexname))); /* Get the char* representation of the column */ column = SPI_getvalue(rettuple, tupdesc, colnum); @@ -339,8 +339,8 @@ fti(PG_FUNCTION_ARGS) ret = SPI_execp(*(plan->splan), values, NULL, 0); if (ret != SPI_OK_INSERT) ereport(ERROR, - (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION), - errmsg("error executing insert"))); + (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION), + errmsg("error executing insert"))); } pfree(buff); pfree(data); diff --git a/contrib/fuzzystrmatch/fuzzystrmatch.c b/contrib/fuzzystrmatch/fuzzystrmatch.c index 3f869180b8..cc4be6af1d 100644 --- a/contrib/fuzzystrmatch/fuzzystrmatch.c +++ b/contrib/fuzzystrmatch/fuzzystrmatch.c @@ -87,7 +87,7 @@ levenshtein(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument exceeds max length: %d", - MAX_LEVENSHTEIN_STRLEN))); + MAX_LEVENSHTEIN_STRLEN))); /* * If either rows or cols is 0, the answer is the other value. This @@ -220,7 +220,7 @@ metaphone(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument exceeds max length: %d", - MAX_METAPHONE_STRLEN))); + MAX_METAPHONE_STRLEN))); if (!(str_i_len > 0)) ereport(ERROR, @@ -232,7 +232,7 @@ metaphone(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("output length exceeds max length: %d", - MAX_METAPHONE_STRLEN))); + MAX_METAPHONE_STRLEN))); if (!(reqlen > 0)) ereport(ERROR, diff --git a/contrib/intagg/int_aggregate.c b/contrib/intagg/int_aggregate.c index 4614b669a7..2bb06ff73a 100644 --- a/contrib/intagg/int_aggregate.c +++ b/contrib/intagg/int_aggregate.c @@ -132,9 +132,9 @@ ShrinkPGArray(PGARRAY * p) /* use current transaction context */ pnew = palloc(cb); + /* - * Fix up the fields in the new structure, so Postgres - * understands + * Fix up the fields in the new structure, so Postgres understands */ memcpy(pnew, p, cb); pnew->a.size = cb; @@ -194,7 +194,7 @@ int_enum(PG_FUNCTION_ARGS) if (!rsi || !IsA(rsi, ReturnSetInfo)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("int_enum called in context that cannot accept a set"))); + errmsg("int_enum called in context that cannot accept a set"))); if (!p) { diff --git a/contrib/intarray/_int.h b/contrib/intarray/_int.h index 5decd969e1..3e702ca1af 100644 --- a/contrib/intarray/_int.h +++ b/contrib/intarray/_int.h @@ -91,19 +91,19 @@ typedef char *BITVECP; */ typedef struct { - int4 len; - int4 flag; - char data[1]; -} GISTTYPE; + int4 len; + int4 flag; + char data[1]; +} GISTTYPE; -#define ALLISTRUE 0x04 +#define ALLISTRUE 0x04 -#define ISALLTRUE(x) ( ((GISTTYPE*)x)->flag & ALLISTRUE ) +#define ISALLTRUE(x) ( ((GISTTYPE*)x)->flag & ALLISTRUE ) -#define GTHDRSIZE ( sizeof(int4)*2 ) +#define GTHDRSIZE ( sizeof(int4)*2 ) #define CALCGTSIZE(flag) ( GTHDRSIZE+(((flag) & ALLISTRUE) ? 0 : SIGLEN) ) -#define GETSIGN(x) ( (BITVECP)( (char*)x+GTHDRSIZE ) ) +#define GETSIGN(x) ( (BITVECP)( (char*)x+GTHDRSIZE ) ) /* ** types for functions @@ -114,22 +114,22 @@ typedef void (*formfloat) (ArrayType *, float *); /* ** useful function */ -bool isort(int4 *a, const int len); -ArrayType *new_intArrayType(int num); -ArrayType *copy_intArrayType(ArrayType *a); -ArrayType *resize_intArrayType(ArrayType *a, int num); -int internal_size(int *a, int len); -ArrayType *_int_unique(ArrayType *a); -int32 intarray_match_first(ArrayType *a, int32 elem); -ArrayType *intarray_add_elem(ArrayType *a, int32 elem); -ArrayType *intarray_concat_arrays(ArrayType *a, ArrayType *b); -ArrayType *int_to_intset(int32 elem); -bool inner_int_overlap(ArrayType *a, ArrayType *b); -bool inner_int_contains(ArrayType *a, ArrayType *b); -ArrayType * inner_int_union(ArrayType *a, ArrayType *b); -ArrayType * inner_int_inter(ArrayType *a, ArrayType *b); -void rt__int_size(ArrayType *a, float *size); -void gensign(BITVEC sign, int *a, int len); +bool isort(int4 *a, const int len); +ArrayType *new_intArrayType(int num); +ArrayType *copy_intArrayType(ArrayType *a); +ArrayType *resize_intArrayType(ArrayType *a, int num); +int internal_size(int *a, int len); +ArrayType *_int_unique(ArrayType *a); +int32 intarray_match_first(ArrayType *a, int32 elem); +ArrayType *intarray_add_elem(ArrayType *a, int32 elem); +ArrayType *intarray_concat_arrays(ArrayType *a, ArrayType *b); +ArrayType *int_to_intset(int32 elem); +bool inner_int_overlap(ArrayType *a, ArrayType *b); +bool inner_int_contains(ArrayType *a, ArrayType *b); +ArrayType *inner_int_union(ArrayType *a, ArrayType *b); +ArrayType *inner_int_inter(ArrayType *a, ArrayType *b); +void rt__int_size(ArrayType *a, float *size); +void gensign(BITVEC sign, int *a, int len); /***************************************************************************** @@ -160,18 +160,16 @@ typedef struct #define COMPUTESIZE(size) ( HDRSIZEQT + size * sizeof(ITEM) ) #define GETQUERY(x) (ITEM*)( (char*)(x)+HDRSIZEQT ) -bool signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot); -bool execconsistent(QUERYTYPE * query, ArrayType *array, bool calcnot); +bool signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot); +bool execconsistent(QUERYTYPE * query, ArrayType *array, bool calcnot); -int compASC(const void *a, const void *b); - -int compDESC(const void *a, const void *b); - -#define QSORT(a, direction) \ -if (ARRNELEMS(a) > 1) \ - qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4), \ - (direction) ? compASC : compDESC ) +int compASC(const void *a, const void *b); +int compDESC(const void *a, const void *b); +#define QSORT(a, direction) \ +if (ARRNELEMS(a) > 1) \ + qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4), \ + (direction) ? compASC : compDESC ) diff --git a/contrib/intarray/_int_bool.c b/contrib/intarray/_int_bool.c index 35d6e6e2c0..d57a94e870 100644 --- a/contrib/intarray/_int_bool.c +++ b/contrib/intarray/_int_bool.c @@ -299,7 +299,7 @@ signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot) GETQUERY(query) + query->size - 1, (void *) sign, calcnot, checkcondition_bit - ); + ); } bool @@ -326,7 +326,7 @@ rboolop(PG_FUNCTION_ARGS) boolop, PG_GETARG_DATUM(1), PG_GETARG_DATUM(0) - ); + ); } Datum @@ -743,4 +743,3 @@ querytree(PG_FUNCTION_ARGS) PG_RETURN_POINTER(res); } - diff --git a/contrib/intarray/_int_gist.c b/contrib/intarray/_int_gist.c index fa6d502e89..39c9679add 100644 --- a/contrib/intarray/_int_gist.c +++ b/contrib/intarray/_int_gist.c @@ -85,27 +85,31 @@ g_int_consistent(PG_FUNCTION_ARGS) } Datum -g_int_union(PG_FUNCTION_ARGS) { - bytea *entryvec = (bytea *) PG_GETARG_POINTER(0); - int *size = (int *) PG_GETARG_POINTER(1); - int4 i,len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY); - ArrayType *res; - int totlen=0,*ptr; +g_int_union(PG_FUNCTION_ARGS) +{ + bytea *entryvec = (bytea *) PG_GETARG_POINTER(0); + int *size = (int *) PG_GETARG_POINTER(1); + int4 i, + len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY); + ArrayType *res; + int totlen = 0, + *ptr; for (i = 0; i < len; i++) - totlen+=ARRNELEMS( GETENTRY(entryvec,i) ); + totlen += ARRNELEMS(GETENTRY(entryvec, i)); - res=new_intArrayType(totlen); - ptr=ARRPTR(res); + res = new_intArrayType(totlen); + ptr = ARRPTR(res); - for (i = 0; i < len; i++) { - memcpy(ptr, ARRPTR( GETENTRY(entryvec,i) ), ARRNELEMS( GETENTRY(entryvec,i) )*sizeof(int4) ); - ptr+=ARRNELEMS( GETENTRY(entryvec,i) ); + for (i = 0; i < len; i++) + { + memcpy(ptr, ARRPTR(GETENTRY(entryvec, i)), ARRNELEMS(GETENTRY(entryvec, i)) * sizeof(int4)); + ptr += ARRNELEMS(GETENTRY(entryvec, i)); } - QSORT(res,1); - res=_int_unique(res); - *size = VARSIZE(res); + QSORT(res, 1); + res = _int_unique(res); + *size = VARSIZE(res); PG_RETURN_POINTER(res); } @@ -239,22 +243,23 @@ g_int_decompress(PG_FUNCTION_ARGS) ** The GiST Penalty method for _intments */ Datum -g_int_penalty(PG_FUNCTION_ARGS) { - GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0); - GISTENTRY *newentry = (GISTENTRY *) PG_GETARG_POINTER(1); - float *result = (float *) PG_GETARG_POINTER(2); +g_int_penalty(PG_FUNCTION_ARGS) +{ + GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0); + GISTENTRY *newentry = (GISTENTRY *) PG_GETARG_POINTER(1); + float *result = (float *) PG_GETARG_POINTER(2); ArrayType *ud; float tmp1, tmp2; ud = inner_int_union((ArrayType *) DatumGetPointer(origentry->key), - (ArrayType *) DatumGetPointer(newentry->key)); + (ArrayType *) DatumGetPointer(newentry->key)); rt__int_size(ud, &tmp1); rt__int_size((ArrayType *) DatumGetPointer(origentry->key), &tmp2); *result = tmp1 - tmp2; pfree(ud); - PG_RETURN_POINTER (result); + PG_RETURN_POINTER(result); } @@ -311,8 +316,9 @@ comparecost(const void *a, const void *b) ** We use Guttman's poly time split algorithm */ Datum -g_int_picksplit(PG_FUNCTION_ARGS) { - bytea *entryvec = (bytea *) PG_GETARG_POINTER(0); +g_int_picksplit(PG_FUNCTION_ARGS) +{ + bytea *entryvec = (bytea *) PG_GETARG_POINTER(0); GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1); OffsetNumber i, j; @@ -501,4 +507,3 @@ g_int_picksplit(PG_FUNCTION_ARGS) { PG_RETURN_POINTER(v); } - diff --git a/contrib/intarray/_int_tool.c b/contrib/intarray/_int_tool.c index 04ff5e436b..d5f169f7c8 100644 --- a/contrib/intarray/_int_tool.c +++ b/contrib/intarray/_int_tool.c @@ -270,7 +270,7 @@ _int_unique(ArrayType *r) *data; int num = ARRNELEMS(r); - if ( num<2 ) + if (num < 2) return r; data = tmp = dr = ARRPTR(r); @@ -367,4 +367,3 @@ compDESC(const void *a, const void *b) return 0; return (*(int4 *) a < *(int4 *) b) ? 1 : -1; } - diff --git a/contrib/ltree/_ltree_op.c b/contrib/ltree/_ltree_op.c index f55434d387..3890769ce1 100644 --- a/contrib/ltree/_ltree_op.c +++ b/contrib/ltree/_ltree_op.c @@ -45,8 +45,8 @@ array_iterator(ArrayType *la, PGCALL2 callback, void *param, ltree ** found) if (ARR_NDIM(la) != 1) ereport(ERROR, - (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("array must be one-dimensional"))); + (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), + errmsg("array must be one-dimensional"))); if (found) *found = NULL; @@ -133,38 +133,40 @@ _ltq_rregex(PG_FUNCTION_ARGS) Datum _lt_q_regex(PG_FUNCTION_ARGS) { - ArrayType *_tree = PG_GETARG_ARRAYTYPE_P(0); - ArrayType *_query = PG_GETARG_ARRAYTYPE_P(1); - lquery *query = (lquery *) ARR_DATA_PTR(_query); - bool res = false; - int num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query)); + ArrayType *_tree = PG_GETARG_ARRAYTYPE_P(0); + ArrayType *_query = PG_GETARG_ARRAYTYPE_P(1); + lquery *query = (lquery *) ARR_DATA_PTR(_query); + bool res = false; + int num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query)); - if (ARR_NDIM(_query) != 1) - ereport(ERROR, + if (ARR_NDIM(_query) != 1) + ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must be one-dimensional"))); - while (num > 0) { - if ( array_iterator(_tree, ltq_regex, (void*)query, NULL) ) { - res = true; - break; - } - num--; - query = (lquery*)NEXTVAL(query); - } + while (num > 0) + { + if (array_iterator(_tree, ltq_regex, (void *) query, NULL)) + { + res = true; + break; + } + num--; + query = (lquery *) NEXTVAL(query); + } - PG_FREE_IF_COPY(_tree, 0); - PG_FREE_IF_COPY(_query, 1); - PG_RETURN_BOOL(res); + PG_FREE_IF_COPY(_tree, 0); + PG_FREE_IF_COPY(_query, 1); + PG_RETURN_BOOL(res); } Datum _lt_q_rregex(PG_FUNCTION_ARGS) { - PG_RETURN_DATUM(DirectFunctionCall2(_lt_q_regex, - PG_GETARG_DATUM(1), - PG_GETARG_DATUM(0) - )); + PG_RETURN_DATUM(DirectFunctionCall2(_lt_q_regex, + PG_GETARG_DATUM(1), + PG_GETARG_DATUM(0) + )); } diff --git a/contrib/ltree/lquery_op.c b/contrib/ltree/lquery_op.c index 72fd968d59..2328fcd238 100644 --- a/contrib/ltree/lquery_op.c +++ b/contrib/ltree/lquery_op.c @@ -45,7 +45,7 @@ getlexem(char *start, char *end, int *len) } bool -compare_subnode(ltree_level * t, char *qn, int len, int (*cmpptr) (const char *, const char *, size_t), bool anyend) + compare_subnode(ltree_level * t, char *qn, int len, int (*cmpptr) (const char *, const char *, size_t), bool anyend) { char *endt = t->name + t->len; char *endq = qn + len; @@ -123,10 +123,15 @@ printFieldNot(FieldNot *fn ) { } */ -static struct { - bool muse; - uint32 high_pos; -} SomeStack = {false,0,}; +static struct +{ + bool muse; + uint32 high_pos; +} SomeStack = + +{ + false, 0, +}; static bool checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_numlevel, FieldNot * ptr) @@ -140,7 +145,8 @@ checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_ lquery_level *prevq = NULL; ltree_level *prevt = NULL; - if ( SomeStack.muse ) { + if (SomeStack.muse) + { high_pos = SomeStack.high_pos; qlen--; prevq = curq; @@ -200,13 +206,15 @@ checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_ curt = LEVEL_NEXT(curt); tlen--; cur_tpos++; - if ( isok && prevq && prevq->numvar==0 && tlen>0 && cur_tpos <= high_pos ) { - FieldNot tmpptr; - if ( ptr ) - memcpy(&tmpptr,ptr,sizeof(FieldNot)); - SomeStack.high_pos = high_pos-cur_tpos; + if (isok && prevq && prevq->numvar == 0 && tlen > 0 && cur_tpos <= high_pos) + { + FieldNot tmpptr; + + if (ptr) + memcpy(&tmpptr, ptr, sizeof(FieldNot)); + SomeStack.high_pos = high_pos - cur_tpos; SomeStack.muse = true; - if ( checkCond(prevq, qlen+1, curt, tlen, (ptr) ? &tmpptr : NULL) ) + if (checkCond(prevq, qlen + 1, curt, tlen, (ptr) ? &tmpptr : NULL)) return true; } if (!isok && ptr) @@ -311,19 +319,21 @@ Datum lt_q_regex(PG_FUNCTION_ARGS) { ltree *tree = PG_GETARG_LTREE(0); - ArrayType *_query = PG_GETARG_ARRAYTYPE_P(1); - lquery *query = (lquery *) ARR_DATA_PTR(_query); - bool res = false; - int num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query)); + ArrayType *_query = PG_GETARG_ARRAYTYPE_P(1); + lquery *query = (lquery *) ARR_DATA_PTR(_query); + bool res = false; + int num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query)); - if (ARR_NDIM(_query) != 1) - ereport(ERROR, + if (ARR_NDIM(_query) != 1) + ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must be one-dimensional"))); - while (num > 0) { + while (num > 0) + { if (DatumGetBool(DirectFunctionCall2(ltq_regex, - PointerGetDatum(tree), PointerGetDatum(query)))) { + PointerGetDatum(tree), PointerGetDatum(query)))) + { res = true; break; @@ -345,5 +355,3 @@ lt_q_rregex(PG_FUNCTION_ARGS) PG_GETARG_DATUM(0) )); } - - diff --git a/contrib/ltree/ltree_io.c b/contrib/ltree/ltree_io.c index 24116b0242..62c033cc5d 100644 --- a/contrib/ltree/ltree_io.c +++ b/contrib/ltree/ltree_io.c @@ -22,7 +22,7 @@ Datum lquery_out(PG_FUNCTION_ARGS); #define UNCHAR ereport(ERROR, \ (errcode(ERRCODE_SYNTAX_ERROR), \ - errmsg("syntax error at position %d near \"%c\"", \ + errmsg("syntax error at position %d near \"%c\"", \ (int)(ptr-buf), *ptr))); @@ -81,8 +81,8 @@ ltree_in(PG_FUNCTION_ARGS) (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("name length is %d, must " \ - "be < 256, in position %d", - lptr->len, (int) (lptr->start - buf)))); + "be < 256, in position %d", + lptr->len, (int) (lptr->start - buf)))); totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE); lptr++; @@ -105,8 +105,8 @@ ltree_in(PG_FUNCTION_ARGS) (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("name length is %d, must " \ - "be < 256, in position %d", - lptr->len, (int) (lptr->start - buf)))); + "be < 256, in position %d", + lptr->len, (int) (lptr->start - buf)))); totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE); lptr++; @@ -283,8 +283,8 @@ lquery_in(PG_FUNCTION_ARGS) (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("name length is %d, must " \ - "be < 256, in position %d", - lptr->len, (int) (lptr->start - buf)))); + "be < 256, in position %d", + lptr->len, (int) (lptr->start - buf)))); state = LQPRS_WAITVAR; } @@ -299,8 +299,8 @@ lquery_in(PG_FUNCTION_ARGS) (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("name length is %d, must " \ - "be < 256, in position %d", - lptr->len, (int) (lptr->start - buf)))); + "be < 256, in position %d", + lptr->len, (int) (lptr->start - buf)))); state = LQPRS_WAITLEVEL; curqlevel = NEXTLEV(curqlevel); @@ -412,8 +412,8 @@ lquery_in(PG_FUNCTION_ARGS) (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("name length is %d, must " \ - "be < 256, in position %d", - lptr->len, (int) (lptr->start - buf)))); + "be < 256, in position %d", + lptr->len, (int) (lptr->start - buf)))); } else if (state == LQPRS_WAITOPEN) curqlevel->high = 0xffff; @@ -442,7 +442,7 @@ lquery_in(PG_FUNCTION_ARGS) (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), errdetail("Low limit(%d) is greater than upper(%d).", - curqlevel->low, curqlevel->high))); + curqlevel->low, curqlevel->high))); curqlevel = NEXTLEV(curqlevel); } diff --git a/contrib/ltree/ltree_op.c b/contrib/ltree/ltree_op.c index 1b3c80b726..4dcb558fe4 100644 --- a/contrib/ltree/ltree_op.c +++ b/contrib/ltree/ltree_op.c @@ -83,49 +83,49 @@ Datum ltree_cmp(PG_FUNCTION_ARGS) { RUNCMP - PG_RETURN_INT32(res); + PG_RETURN_INT32(res); } Datum ltree_lt(PG_FUNCTION_ARGS) { RUNCMP - PG_RETURN_BOOL((res < 0) ? true : false); + PG_RETURN_BOOL((res < 0) ? true : false); } Datum ltree_le(PG_FUNCTION_ARGS) { RUNCMP - PG_RETURN_BOOL((res <= 0) ? true : false); + PG_RETURN_BOOL((res <= 0) ? true : false); } Datum ltree_eq(PG_FUNCTION_ARGS) { RUNCMP - PG_RETURN_BOOL((res == 0) ? true : false); + PG_RETURN_BOOL((res == 0) ? true : false); } Datum ltree_ge(PG_FUNCTION_ARGS) { RUNCMP - PG_RETURN_BOOL((res >= 0) ? true : false); + PG_RETURN_BOOL((res >= 0) ? true : false); } Datum ltree_gt(PG_FUNCTION_ARGS) { RUNCMP - PG_RETURN_BOOL((res > 0) ? true : false); + PG_RETURN_BOOL((res > 0) ? true : false); } Datum ltree_ne(PG_FUNCTION_ARGS) { RUNCMP - PG_RETURN_BOOL((res != 0) ? true : false); + PG_RETURN_BOOL((res != 0) ? true : false); } Datum @@ -331,46 +331,55 @@ ltree_index(PG_FUNCTION_ARGS) { ltree *a = PG_GETARG_LTREE(0); ltree *b = PG_GETARG_LTREE(1); - int start=(fcinfo->nargs == 3) ? PG_GETARG_INT32(2) : 0; - int i,j; - ltree_level *startptr, *aptr, *bptr; - bool found=false; + int start = (fcinfo->nargs == 3) ? PG_GETARG_INT32(2) : 0; + int i, + j; + ltree_level *startptr, + *aptr, + *bptr; + bool found = false; - if ( start < 0 ) { - if ( -start >= a->numlevel ) - start=0; - else - start = (int)(a->numlevel)+start; + if (start < 0) + { + if (-start >= a->numlevel) + start = 0; + else + start = (int) (a->numlevel) + start; } - if ( a->numlevel - start < b->numlevel || a->numlevel==0 || b->numlevel==0 ) { + if (a->numlevel - start < b->numlevel || a->numlevel == 0 || b->numlevel == 0) + { PG_FREE_IF_COPY(a, 0); PG_FREE_IF_COPY(b, 1); PG_RETURN_INT32(-1); } - startptr=LTREE_FIRST(a); - for(i=0; i<=a->numlevel-b->numlevel; i++) { - if ( i>=start ) { - aptr=startptr; - bptr=LTREE_FIRST(b); - for(j=0;jnumlevel;j++) { - if ( !(aptr->len==bptr->len && strncmp(aptr->name,bptr->name, aptr->len)==0) ) - break; - aptr=LEVEL_NEXT(aptr); - bptr=LEVEL_NEXT(bptr); + startptr = LTREE_FIRST(a); + for (i = 0; i <= a->numlevel - b->numlevel; i++) + { + if (i >= start) + { + aptr = startptr; + bptr = LTREE_FIRST(b); + for (j = 0; j < b->numlevel; j++) + { + if (!(aptr->len == bptr->len && strncmp(aptr->name, bptr->name, aptr->len) == 0)) + break; + aptr = LEVEL_NEXT(aptr); + bptr = LEVEL_NEXT(bptr); } - - if ( j==b->numlevel ) { - found=true; + + if (j == b->numlevel) + { + found = true; break; } } - startptr=LEVEL_NEXT(startptr); + startptr = LEVEL_NEXT(startptr); } - - if ( !found ) - i=-1; + + if (!found) + i = -1; PG_FREE_IF_COPY(a, 0); PG_FREE_IF_COPY(b, 1); @@ -496,18 +505,18 @@ Datum text2ltree(PG_FUNCTION_ARGS) { text *in = PG_GETARG_TEXT_P(0); - char *s = (char *) palloc(VARSIZE(in) - VARHDRSZ + 1); - ltree *out; + char *s = (char *) palloc(VARSIZE(in) - VARHDRSZ + 1); + ltree *out; memcpy(s, VARDATA(in), VARSIZE(in) - VARHDRSZ); s[VARSIZE(in) - VARHDRSZ] = '\0'; out = (ltree *) DatumGetPointer(DirectFunctionCall1( - ltree_in, - PointerGetDatum(s) - )); + ltree_in, + PointerGetDatum(s) + )); pfree(s); - PG_FREE_IF_COPY(in,0); + PG_FREE_IF_COPY(in, 0); PG_RETURN_POINTER(out); } @@ -516,16 +525,18 @@ Datum ltree2text(PG_FUNCTION_ARGS) { ltree *in = PG_GETARG_LTREE(0); - char *ptr; - int i; + char *ptr; + int i; ltree_level *curlevel; - text *out; - - out=(text*)palloc(in->len+VARHDRSZ); - ptr = VARDATA(out); + text *out; + + out = (text *) palloc(in->len + VARHDRSZ); + ptr = VARDATA(out); curlevel = LTREE_FIRST(in); - for (i = 0; i < in->numlevel; i++) { - if (i != 0) { + for (i = 0; i < in->numlevel; i++) + { + if (i != 0) + { *ptr = '.'; ptr++; } @@ -533,13 +544,9 @@ ltree2text(PG_FUNCTION_ARGS) ptr += curlevel->len; curlevel = LEVEL_NEXT(curlevel); } - - VARATT_SIZEP(out) = VARHDRSZ + (ptr-VARDATA(out)); + + VARATT_SIZEP(out) = VARHDRSZ + (ptr - VARDATA(out)); PG_FREE_IF_COPY(in, 0); - + PG_RETURN_POINTER(out); } - - - - diff --git a/contrib/oid2name/oid2name.c b/contrib/oid2name/oid2name.c index e2e2907267..76369fd13c 100644 --- a/contrib/oid2name/oid2name.c +++ b/contrib/oid2name/oid2name.c @@ -356,8 +356,8 @@ sql_exec_dumptable(PGconn *conn, int systables) snprintf(todo, 1024, "select relfilenode,relname from pg_class order by relname"); else snprintf(todo, 1024, "select relfilenode,relname from pg_class " - "where relkind not in ('v','s', 'c') and " - "relname not like 'pg_%%' order by relname"); + "where relkind not in ('v','s', 'c') and " + "relname not like 'pg_%%' order by relname"); sql_exec(conn, todo, 0); } diff --git a/contrib/pg_autovacuum/pg_autovacuum.c b/contrib/pg_autovacuum/pg_autovacuum.c index dce065d7b6..01d22dbc6b 100644 --- a/contrib/pg_autovacuum/pg_autovacuum.c +++ b/contrib/pg_autovacuum/pg_autovacuum.c @@ -6,324 +6,362 @@ #include "pg_autovacuum.h" #define TIMEBUFF 256 -FILE *LOGOUTPUT; -char timebuffer[TIMEBUFF]; -char logbuffer[4096]; +FILE *LOGOUTPUT; +char timebuffer[TIMEBUFF]; +char logbuffer[4096]; void -log_entry (const char *logentry) +log_entry(const char *logentry) { - time_t curtime; - struct tm *loctime; - curtime = time (NULL); - loctime = localtime (&curtime); - strftime (timebuffer, TIMEBUFF, "%Y-%m-%d %r", loctime); /* cbb - %F is not always available */ - fprintf (LOGOUTPUT, "[%s] %s\n", timebuffer, logentry); + time_t curtime; + struct tm *loctime; + + curtime = time(NULL); + loctime = localtime(&curtime); + strftime(timebuffer, TIMEBUFF, "%Y-%m-%d %r", loctime); /* cbb - %F is not + * always available */ + fprintf(LOGOUTPUT, "[%s] %s\n", timebuffer, logentry); } /* Function used to detatch the pg_autovacuum daemon from the tty and go into the background * -* This code is mostly ripped directly from pm_dameonize in postmaster.c * -* with unneeded code removed. */ -void daemonize () +* This code is mostly ripped directly from pm_dameonize in postmaster.c * +* with unneeded code removed. */ +void +daemonize() { - pid_t pid; + pid_t pid; - pid = fork(); - if (pid == (pid_t) -1) - { - log_entry("Error: cannot disassociate from controlling TTY"); - fflush(LOGOUTPUT); - _exit(1); - } - else if (pid) - { /* parent */ - /* Parent should just exit, without doing any atexit cleanup */ - _exit(0); - } + pid = fork(); + if (pid == (pid_t) -1) + { + log_entry("Error: cannot disassociate from controlling TTY"); + fflush(LOGOUTPUT); + _exit(1); + } + else if (pid) + { /* parent */ + /* Parent should just exit, without doing any atexit cleanup */ + _exit(0); + } /* GH: If there's no setsid(), we hopefully don't need silent mode. * Until there's a better solution. */ #ifdef HAVE_SETSID - if (setsid() < 0) - { - log_entry("Error: cannot disassociate from controlling TTY"); - fflush(LOGOUTPUT); - _exit(1); - } + if (setsid() < 0) + { + log_entry("Error: cannot disassociate from controlling TTY"); + fflush(LOGOUTPUT); + _exit(1); + } #endif } /* Create and return tbl_info struct with initialized to values from row or res */ tbl_info * -init_table_info (PGresult * res, int row, db_info *dbi) +init_table_info(PGresult *res, int row, db_info * dbi) { - tbl_info *new_tbl = (tbl_info *) malloc (sizeof (tbl_info)); + tbl_info *new_tbl = (tbl_info *) malloc(sizeof(tbl_info)); - if (!new_tbl) { - log_entry ("init_table_info: Cannot get memory"); - fflush (LOGOUTPUT); - return NULL; - } + if (!new_tbl) + { + log_entry("init_table_info: Cannot get memory"); + fflush(LOGOUTPUT); + return NULL; + } - if (NULL == res) - return NULL; + if (NULL == res) + return NULL; - new_tbl->dbi = dbi; /* set pointer to db */ + new_tbl->dbi = dbi; /* set pointer to db */ - new_tbl->schema_name = (char *) - malloc (strlen (PQgetvalue (res, row, PQfnumber (res, "schemaname"))) + 1); - if (!new_tbl->schema_name) { - log_entry ("init_table_info: malloc failed on new_tbl->schema_name"); - fflush (LOGOUTPUT); - return NULL; - } - strcpy (new_tbl->schema_name, - PQgetvalue (res, row, PQfnumber (res, "schemaname"))); + new_tbl->schema_name = (char *) + malloc(strlen(PQgetvalue(res, row, PQfnumber(res, "schemaname"))) + 1); + if (!new_tbl->schema_name) + { + log_entry("init_table_info: malloc failed on new_tbl->schema_name"); + fflush(LOGOUTPUT); + return NULL; + } + strcpy(new_tbl->schema_name, + PQgetvalue(res, row, PQfnumber(res, "schemaname"))); - new_tbl->table_name = (char *) - malloc (strlen (PQgetvalue (res, row, PQfnumber (res, "relname"))) + - strlen (new_tbl->schema_name) + 2); - if (!new_tbl->table_name) { - log_entry ("init_table_info: malloc failed on new_tbl->table_name"); - fflush (LOGOUTPUT); - return NULL; - } - strcpy (new_tbl->table_name, new_tbl->schema_name); - strcat (new_tbl->table_name, "."); - strcat (new_tbl->table_name, PQgetvalue (res, row, PQfnumber (res, "relname"))); + new_tbl->table_name = (char *) + malloc(strlen(PQgetvalue(res, row, PQfnumber(res, "relname"))) + + strlen(new_tbl->schema_name) + 2); + if (!new_tbl->table_name) + { + log_entry("init_table_info: malloc failed on new_tbl->table_name"); + fflush(LOGOUTPUT); + return NULL; + } + strcpy(new_tbl->table_name, new_tbl->schema_name); + strcat(new_tbl->table_name, "."); + strcat(new_tbl->table_name, PQgetvalue(res, row, PQfnumber(res, "relname"))); - new_tbl->CountAtLastAnalyze = - (atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_ins"))) + - atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_upd")))); - new_tbl->curr_analyze_count = new_tbl->CountAtLastAnalyze; + new_tbl->CountAtLastAnalyze = + (atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_ins"))) + + atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_upd")))); + new_tbl->curr_analyze_count = new_tbl->CountAtLastAnalyze; - new_tbl->CountAtLastVacuum = - (atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_del"))) + - atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_upd")))); - new_tbl->curr_vacuum_count = new_tbl->CountAtLastVacuum; + new_tbl->CountAtLastVacuum = + (atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_del"))) + + atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_upd")))); + new_tbl->curr_vacuum_count = new_tbl->CountAtLastVacuum; - new_tbl->relfilenode = atoi (PQgetvalue (res, row, PQfnumber (res, "relfilenode"))); - new_tbl->reltuples = atoi (PQgetvalue (res, row, PQfnumber (res, "reltuples"))); - new_tbl->relpages = atoi (PQgetvalue (res, row, PQfnumber (res, "relpages"))); + new_tbl->relfilenode = atoi(PQgetvalue(res, row, PQfnumber(res, "relfilenode"))); + new_tbl->reltuples = atoi(PQgetvalue(res, row, PQfnumber(res, "reltuples"))); + new_tbl->relpages = atoi(PQgetvalue(res, row, PQfnumber(res, "relpages"))); - new_tbl->analyze_threshold = - args->analyze_base_threshold + args->analyze_scaling_factor * new_tbl->reltuples; - new_tbl->vacuum_threshold = - args->vacuum_base_threshold + args->vacuum_scaling_factor * new_tbl->reltuples; + new_tbl->analyze_threshold = + args->analyze_base_threshold + args->analyze_scaling_factor * new_tbl->reltuples; + new_tbl->vacuum_threshold = + args->vacuum_base_threshold + args->vacuum_scaling_factor * new_tbl->reltuples; - if (args->debug >= 2) { - print_table_info (new_tbl); - } + if (args->debug >= 2) + print_table_info(new_tbl); - return new_tbl; + return new_tbl; } /* Set thresholds = base_value + scaling_factor * reltuples Should be called after a vacuum since vacuum updates values in pg_class */ void -update_table_thresholds (db_info * dbi, tbl_info * tbl,int vacuum_type) +update_table_thresholds(db_info * dbi, tbl_info * tbl, int vacuum_type) { - PGresult *res = NULL; - int disconnect = 0; - char query[128]; + PGresult *res = NULL; + int disconnect = 0; + char query[128]; - if (NULL == dbi->conn) { - dbi->conn = db_connect (dbi); - disconnect = 1; - } + if (NULL == dbi->conn) + { + dbi->conn = db_connect(dbi); + disconnect = 1; + } - if (NULL != dbi->conn) { - snprintf (query, sizeof (query), PAGES_QUERY, tbl->relfilenode); - res = send_query (query, dbi); - if (NULL != res) { - tbl->reltuples = - atoi (PQgetvalue (res, 0, PQfnumber (res, "reltuples"))); - tbl->relpages = atoi (PQgetvalue (res, 0, PQfnumber (res, "relpages"))); + if (NULL != dbi->conn) + { + snprintf(query, sizeof(query), PAGES_QUERY, tbl->relfilenode); + res = send_query(query, dbi); + if (NULL != res) + { + tbl->reltuples = + atoi(PQgetvalue(res, 0, PQfnumber(res, "reltuples"))); + tbl->relpages = atoi(PQgetvalue(res, 0, PQfnumber(res, "relpages"))); - /* update vacuum thresholds only of we just did a vacuum analyze */ - if(VACUUM_ANALYZE == vacuum_type) - { - tbl->vacuum_threshold = - (args->vacuum_base_threshold + args->vacuum_scaling_factor * tbl->reltuples); - tbl->CountAtLastVacuum = tbl->curr_vacuum_count; - } + /* + * update vacuum thresholds only of we just did a vacuum + * analyze + */ + if (VACUUM_ANALYZE == vacuum_type) + { + tbl->vacuum_threshold = + (args->vacuum_base_threshold + args->vacuum_scaling_factor * tbl->reltuples); + tbl->CountAtLastVacuum = tbl->curr_vacuum_count; + } - /* update analyze thresholds */ - tbl->analyze_threshold = - (args->analyze_base_threshold + args->analyze_scaling_factor * tbl->reltuples); - tbl->CountAtLastAnalyze = tbl->curr_analyze_count; + /* update analyze thresholds */ + tbl->analyze_threshold = + (args->analyze_base_threshold + args->analyze_scaling_factor * tbl->reltuples); + tbl->CountAtLastAnalyze = tbl->curr_analyze_count; - PQclear (res); + PQclear(res); - /* If the stats collector is reporting fewer updates then we have on record - then the stats were probably reset, so we need to reset also */ - if ((tbl->curr_analyze_count < tbl->CountAtLastAnalyze) || - (tbl->curr_vacuum_count < tbl->CountAtLastVacuum)) - { - tbl->CountAtLastAnalyze = tbl->curr_analyze_count; - tbl->CountAtLastVacuum = tbl->curr_vacuum_count; - } - } - } - if (disconnect) - db_disconnect (dbi); + /* + * If the stats collector is reporting fewer updates then we + * have on record then the stats were probably reset, so we + * need to reset also + */ + if ((tbl->curr_analyze_count < tbl->CountAtLastAnalyze) || + (tbl->curr_vacuum_count < tbl->CountAtLastVacuum)) + { + tbl->CountAtLastAnalyze = tbl->curr_analyze_count; + tbl->CountAtLastVacuum = tbl->curr_vacuum_count; + } + } + } + if (disconnect) + db_disconnect(dbi); } void -update_table_list (db_info * dbi) +update_table_list(db_info * dbi) { - int disconnect = 0; - PGresult *res = NULL; - tbl_info *tbl = NULL; - Dlelem *tbl_elem = DLGetHead (dbi->table_list); - int i = 0, t = 0, found_match = 0; + int disconnect = 0; + PGresult *res = NULL; + tbl_info *tbl = NULL; + Dlelem *tbl_elem = DLGetHead(dbi->table_list); + int i = 0, + t = 0, + found_match = 0; - if (NULL == dbi->conn) { - dbi->conn = db_connect (dbi); - disconnect = 1; - } + if (NULL == dbi->conn) + { + dbi->conn = db_connect(dbi); + disconnect = 1; + } - if (NULL != dbi->conn) { - /* Get a result set that has all the information - we will need to both remove tables from the list - that no longer exist and add tables to the list - that are new */ - res = send_query (query_table_stats (dbi), dbi); - t = PQntuples (res); + if (NULL != dbi->conn) + { + /* + * Get a result set that has all the information we will need to + * both remove tables from the list that no longer exist and add + * tables to the list that are new + */ + res = send_query(query_table_stats(dbi), dbi); + t = PQntuples(res); - /* First: use the tbl_list as the outer loop and - the result set as the inner loop, this will - determine what tables should be removed */ - while (NULL != tbl_elem) { - tbl = ((tbl_info *) DLE_VAL (tbl_elem)); - found_match = 0; + /* + * First: use the tbl_list as the outer loop and the result set as + * the inner loop, this will determine what tables should be + * removed + */ + while (NULL != tbl_elem) + { + tbl = ((tbl_info *) DLE_VAL(tbl_elem)); + found_match = 0; - for (i = 0; i < t; i++) { /* loop through result set looking for a match */ - if (tbl->relfilenode == atoi (PQgetvalue (res, i, PQfnumber (res, "relfilenode")))) { - found_match = 1; - break; - } - } - if (0 == found_match) { /* then we didn't find this tbl_elem in the result set */ - Dlelem *elem_to_remove = tbl_elem; - tbl_elem = DLGetSucc (tbl_elem); - remove_table_from_list (elem_to_remove); - } - else - tbl_elem = DLGetSucc (tbl_elem); - } /* Done removing dropped tables from the table_list */ + for (i = 0; i < t; i++) + { /* loop through result set looking for a + * match */ + if (tbl->relfilenode == atoi(PQgetvalue(res, i, PQfnumber(res, "relfilenode")))) + { + found_match = 1; + break; + } + } + if (0 == found_match) + { /* then we didn't find this tbl_elem in + * the result set */ + Dlelem *elem_to_remove = tbl_elem; - /* Then loop use result set as outer loop and - tbl_list as the inner loop to determine - what tables are new */ - for (i = 0; i < t; i++) - { - tbl_elem = DLGetHead (dbi->table_list); - found_match = 0; - while (NULL != tbl_elem) - { - tbl = ((tbl_info *) DLE_VAL (tbl_elem)); - if (tbl->relfilenode == atoi (PQgetvalue (res, i, PQfnumber (res, "relfilenode")))) - { - found_match = 1; - break; - } - tbl_elem = DLGetSucc (tbl_elem); - } - if (0 == found_match) /*then we didn't find this result now in the tbl_list */ - { - DLAddTail (dbi->table_list, DLNewElem (init_table_info (res, i, dbi))); - if (args->debug >= 1) - { - sprintf (logbuffer, "added table: %s.%s", dbi->dbname, - ((tbl_info *) DLE_VAL (DLGetTail (dbi->table_list)))->table_name); - log_entry (logbuffer); - } - } - } /* end of for loop that adds tables */ - fflush (LOGOUTPUT); - PQclear (res); - res = NULL; - if (args->debug >= 3) { - print_table_list (dbi->table_list); - } - if (disconnect) - db_disconnect (dbi); - } + tbl_elem = DLGetSucc(tbl_elem); + remove_table_from_list(elem_to_remove); + } + else + tbl_elem = DLGetSucc(tbl_elem); + } /* Done removing dropped tables from the + * table_list */ + + /* + * Then loop use result set as outer loop and tbl_list as the + * inner loop to determine what tables are new + */ + for (i = 0; i < t; i++) + { + tbl_elem = DLGetHead(dbi->table_list); + found_match = 0; + while (NULL != tbl_elem) + { + tbl = ((tbl_info *) DLE_VAL(tbl_elem)); + if (tbl->relfilenode == atoi(PQgetvalue(res, i, PQfnumber(res, "relfilenode")))) + { + found_match = 1; + break; + } + tbl_elem = DLGetSucc(tbl_elem); + } + if (0 == found_match) /* then we didn't find this result + * now in the tbl_list */ + { + DLAddTail(dbi->table_list, DLNewElem(init_table_info(res, i, dbi))); + if (args->debug >= 1) + { + sprintf(logbuffer, "added table: %s.%s", dbi->dbname, + ((tbl_info *) DLE_VAL(DLGetTail(dbi->table_list)))->table_name); + log_entry(logbuffer); + } + } + } /* end of for loop that adds tables */ + fflush(LOGOUTPUT); + PQclear(res); + res = NULL; + if (args->debug >= 3) + print_table_list(dbi->table_list); + if (disconnect) + db_disconnect(dbi); + } } /* Free memory, and remove the node from the list */ void -remove_table_from_list (Dlelem * tbl_to_remove) +remove_table_from_list(Dlelem *tbl_to_remove) { - tbl_info *tbl = ((tbl_info *) DLE_VAL (tbl_to_remove)); + tbl_info *tbl = ((tbl_info *) DLE_VAL(tbl_to_remove)); - if (args->debug >= 1) { - sprintf (logbuffer, "Removing table: %s from list.", tbl->table_name); - log_entry (logbuffer); - fflush (LOGOUTPUT); - } - DLRemove (tbl_to_remove); + if (args->debug >= 1) + { + sprintf(logbuffer, "Removing table: %s from list.", tbl->table_name); + log_entry(logbuffer); + fflush(LOGOUTPUT); + } + DLRemove(tbl_to_remove); - if (tbl->schema_name) { - free (tbl->schema_name); - tbl->schema_name = NULL; - } - if (tbl->table_name) { - free (tbl->table_name); - tbl->table_name = NULL; - } - if (tbl) { - free (tbl); - tbl = NULL; - } - DLFreeElem (tbl_to_remove); + if (tbl->schema_name) + { + free(tbl->schema_name); + tbl->schema_name = NULL; + } + if (tbl->table_name) + { + free(tbl->table_name); + tbl->table_name = NULL; + } + if (tbl) + { + free(tbl); + tbl = NULL; + } + DLFreeElem(tbl_to_remove); } /* Free the entire table list */ void -free_tbl_list (Dllist * tbl_list) +free_tbl_list(Dllist *tbl_list) { - Dlelem *tbl_elem = DLGetHead (tbl_list); - Dlelem *tbl_elem_to_remove = NULL; - while (NULL != tbl_elem) { - tbl_elem_to_remove = tbl_elem; - tbl_elem = DLGetSucc (tbl_elem); - remove_table_from_list (tbl_elem_to_remove); - } - DLFreeList (tbl_list); + Dlelem *tbl_elem = DLGetHead(tbl_list); + Dlelem *tbl_elem_to_remove = NULL; + + while (NULL != tbl_elem) + { + tbl_elem_to_remove = tbl_elem; + tbl_elem = DLGetSucc(tbl_elem); + remove_table_from_list(tbl_elem_to_remove); + } + DLFreeList(tbl_list); } void -print_table_list (Dllist * table_list) +print_table_list(Dllist *table_list) { - Dlelem *table_elem = DLGetHead (table_list); - while (NULL != table_elem) { - print_table_info (((tbl_info *) DLE_VAL (table_elem))); - table_elem = DLGetSucc (table_elem); - } + Dlelem *table_elem = DLGetHead(table_list); + + while (NULL != table_elem) + { + print_table_info(((tbl_info *) DLE_VAL(table_elem))); + table_elem = DLGetSucc(table_elem); + } } void -print_table_info (tbl_info * tbl) +print_table_info(tbl_info * tbl) { - sprintf (logbuffer, " table name: %s.%s", tbl->dbi->dbname, tbl->table_name); - log_entry (logbuffer); - sprintf (logbuffer, " relfilenode: %i",tbl->relfilenode); - log_entry (logbuffer); - sprintf (logbuffer, " reltuples: %i; relpages: %i", tbl->reltuples, tbl->relpages); - log_entry (logbuffer); - sprintf (logbuffer, " curr_analyze_count: %li; cur_delete_count: %li", - tbl->curr_analyze_count, tbl->curr_vacuum_count); - log_entry (logbuffer); - sprintf (logbuffer, " ins_at_last_analyze: %li; del_at_last_vacuum: %li", - tbl->CountAtLastAnalyze, tbl->CountAtLastVacuum); - log_entry (logbuffer); - sprintf (logbuffer, " insert_threshold: %li; delete_threshold %li", - tbl->analyze_threshold, tbl->vacuum_threshold); - log_entry (logbuffer); - fflush (LOGOUTPUT); + sprintf(logbuffer, " table name: %s.%s", tbl->dbi->dbname, tbl->table_name); + log_entry(logbuffer); + sprintf(logbuffer, " relfilenode: %i", tbl->relfilenode); + log_entry(logbuffer); + sprintf(logbuffer, " reltuples: %i; relpages: %i", tbl->reltuples, tbl->relpages); + log_entry(logbuffer); + sprintf(logbuffer, " curr_analyze_count: %li; cur_delete_count: %li", + tbl->curr_analyze_count, tbl->curr_vacuum_count); + log_entry(logbuffer); + sprintf(logbuffer, " ins_at_last_analyze: %li; del_at_last_vacuum: %li", + tbl->CountAtLastAnalyze, tbl->CountAtLastVacuum); + log_entry(logbuffer); + sprintf(logbuffer, " insert_threshold: %li; delete_threshold %li", + tbl->analyze_threshold, tbl->vacuum_threshold); + log_entry(logbuffer); + fflush(LOGOUTPUT); } /* End of table Management Functions */ @@ -332,161 +370,188 @@ print_table_info (tbl_info * tbl) /* init_db_list() creates the db_list and initalizes template1 */ Dllist * -init_db_list () +init_db_list() { - Dllist *db_list = DLNewList (); - db_info *dbs = NULL; - PGresult *res = NULL; + Dllist *db_list = DLNewList(); + db_info *dbs = NULL; + PGresult *res = NULL; - DLAddHead (db_list, DLNewElem (init_dbinfo ((char *) "template1", 0, 0))); - if (NULL == DLGetHead (db_list)) { /* Make sure init_dbinfo was successful */ - log_entry ("init_db_list(): Error creating db_list for db: template1."); - fflush (LOGOUTPUT); - return NULL; - } + DLAddHead(db_list, DLNewElem(init_dbinfo((char *) "template1", 0, 0))); + if (NULL == DLGetHead(db_list)) + { /* Make sure init_dbinfo was successful */ + log_entry("init_db_list(): Error creating db_list for db: template1."); + fflush(LOGOUTPUT); + return NULL; + } - /* We do this just so we can set the proper oid for the template1 database */ - dbs = ((db_info *) DLE_VAL (DLGetHead (db_list))); - dbs->conn = db_connect (dbs); + /* + * We do this just so we can set the proper oid for the template1 + * database + */ + dbs = ((db_info *) DLE_VAL(DLGetHead(db_list))); + dbs->conn = db_connect(dbs); - if (NULL != dbs->conn) { - res = send_query (FROZENOID_QUERY, dbs); - dbs->oid = atoi (PQgetvalue (res, 0, PQfnumber (res, "oid"))); - dbs->age = atoi (PQgetvalue (res, 0, PQfnumber (res, "age"))); - if (res) - PQclear (res); + if (NULL != dbs->conn) + { + res = send_query(FROZENOID_QUERY, dbs); + dbs->oid = atoi(PQgetvalue(res, 0, PQfnumber(res, "oid"))); + dbs->age = atoi(PQgetvalue(res, 0, PQfnumber(res, "age"))); + if (res) + PQclear(res); - if (args->debug >= 2) { - print_db_list (db_list, 0); - } - } - return db_list; + if (args->debug >= 2) + print_db_list(db_list, 0); + } + return db_list; } /* Simple function to create an instance of the dbinfo struct - Initalizes all the pointers and connects to the database */ + Initalizes all the pointers and connects to the database */ db_info * -init_dbinfo (char *dbname, int oid, int age) +init_dbinfo(char *dbname, int oid, int age) { - db_info *newdbinfo = (db_info *) malloc (sizeof (db_info)); - newdbinfo->analyze_threshold = args->vacuum_base_threshold; - newdbinfo->vacuum_threshold = args->analyze_base_threshold; - newdbinfo->dbname = (char *) malloc (strlen (dbname) + 1); - strcpy (newdbinfo->dbname, dbname); - newdbinfo->username = NULL; - if (NULL != args->user) { - newdbinfo->username = (char *) malloc (strlen (args->user) + 1); - strcpy (newdbinfo->username, args->user); - } - newdbinfo->password = NULL; - if (NULL != args->password) { - newdbinfo->password = (char *) malloc (strlen (args->password) + 1); - strcpy (newdbinfo->password, args->password); - } - newdbinfo->oid = oid; - newdbinfo->age = age; - newdbinfo->table_list = DLNewList (); - newdbinfo->conn = NULL; + db_info *newdbinfo = (db_info *) malloc(sizeof(db_info)); - if (args->debug >= 2) { - print_table_list (newdbinfo->table_list); - } + newdbinfo->analyze_threshold = args->vacuum_base_threshold; + newdbinfo->vacuum_threshold = args->analyze_base_threshold; + newdbinfo->dbname = (char *) malloc(strlen(dbname) + 1); + strcpy(newdbinfo->dbname, dbname); + newdbinfo->username = NULL; + if (NULL != args->user) + { + newdbinfo->username = (char *) malloc(strlen(args->user) + 1); + strcpy(newdbinfo->username, args->user); + } + newdbinfo->password = NULL; + if (NULL != args->password) + { + newdbinfo->password = (char *) malloc(strlen(args->password) + 1); + strcpy(newdbinfo->password, args->password); + } + newdbinfo->oid = oid; + newdbinfo->age = age; + newdbinfo->table_list = DLNewList(); + newdbinfo->conn = NULL; - return newdbinfo; + if (args->debug >= 2) + print_table_list(newdbinfo->table_list); + + return newdbinfo; } /* Function adds and removes databases from the db_list as appropriate */ void -update_db_list (Dllist * db_list) +update_db_list(Dllist *db_list) { - int disconnect = 0; - PGresult *res = NULL; - Dlelem *db_elem = DLGetHead (db_list); - db_info *dbi = NULL; - db_info *dbi_template1 = DLE_VAL (db_elem); - int i = 0, t = 0, found_match = 0; + int disconnect = 0; + PGresult *res = NULL; + Dlelem *db_elem = DLGetHead(db_list); + db_info *dbi = NULL; + db_info *dbi_template1 = DLE_VAL(db_elem); + int i = 0, + t = 0, + found_match = 0; - if (args->debug >= 2) { - log_entry ("updating the database list"); - fflush (LOGOUTPUT); - } + if (args->debug >= 2) + { + log_entry("updating the database list"); + fflush(LOGOUTPUT); + } - if (NULL == dbi_template1->conn) { - dbi_template1->conn = db_connect (dbi_template1); - disconnect = 1; - } + if (NULL == dbi_template1->conn) + { + dbi_template1->conn = db_connect(dbi_template1); + disconnect = 1; + } - if (NULL != dbi_template1->conn) { - /* Get a result set that has all the information - we will need to both remove databasews from the list - that no longer exist and add databases to the list - that are new */ - res = send_query (FROZENOID_QUERY2, dbi_template1); - t = PQntuples (res); + if (NULL != dbi_template1->conn) + { + /* + * Get a result set that has all the information we will need to + * both remove databasews from the list that no longer exist and + * add databases to the list that are new + */ + res = send_query(FROZENOID_QUERY2, dbi_template1); + t = PQntuples(res); - /* First: use the db_list as the outer loop and - the result set as the inner loop, this will - determine what databases should be removed */ - while (NULL != db_elem) { - dbi = ((db_info *) DLE_VAL (db_elem)); - found_match = 0; + /* + * First: use the db_list as the outer loop and the result set as + * the inner loop, this will determine what databases should be + * removed + */ + while (NULL != db_elem) + { + dbi = ((db_info *) DLE_VAL(db_elem)); + found_match = 0; - for (i = 0; i < t; i++) { /* loop through result set looking for a match */ - if (dbi->oid == atoi (PQgetvalue (res, i, PQfnumber (res, "oid")))) { - found_match = 1; - /* update the dbi->age so that we ensure xid_wraparound won't happen */ - dbi->age = atoi (PQgetvalue (res, i, PQfnumber (res, "age"))); - break; - } - } - if (0 == found_match) { /*then we didn't find this db_elem in the result set */ - Dlelem *elem_to_remove = db_elem; - db_elem = DLGetSucc (db_elem); - remove_db_from_list (elem_to_remove); - } - else - db_elem = DLGetSucc (db_elem); - } /* Done removing dropped databases from the table_list */ + for (i = 0; i < t; i++) + { /* loop through result set looking for a + * match */ + if (dbi->oid == atoi(PQgetvalue(res, i, PQfnumber(res, "oid")))) + { + found_match = 1; - /* Then loop use result set as outer loop and - db_list as the inner loop to determine - what databases are new */ - for (i = 0; i < t; i++) - { - db_elem = DLGetHead (db_list); - found_match = 0; - while (NULL != db_elem) - { - dbi = ((db_info *) DLE_VAL (db_elem)); - if (dbi->oid == atoi (PQgetvalue (res, i, PQfnumber (res, "oid")))) - { - found_match = 1; - break; - } - db_elem = DLGetSucc (db_elem); - } - if (0 == found_match) /*then we didn't find this result now in the tbl_list */ - { - DLAddTail (db_list, DLNewElem (init_dbinfo - (PQgetvalue(res, i, PQfnumber (res, "datname")), - atoi (PQgetvalue(res, i, PQfnumber (res, "oid"))), - atoi (PQgetvalue(res, i, PQfnumber (res, "age")))))); - if (args->debug >= 1) - { - sprintf (logbuffer, "added database: %s",((db_info *) DLE_VAL (DLGetTail (db_list)))->dbname); - log_entry (logbuffer); - } - } - } /* end of for loop that adds tables */ - fflush (LOGOUTPUT); - PQclear (res); - res = NULL; - if (args->debug >= 3) { - print_db_list (db_list, 0); - } - if (disconnect) - db_disconnect (dbi_template1); - } + /* + * update the dbi->age so that we ensure + * xid_wraparound won't happen + */ + dbi->age = atoi(PQgetvalue(res, i, PQfnumber(res, "age"))); + break; + } + } + if (0 == found_match) + { /* then we didn't find this db_elem in the + * result set */ + Dlelem *elem_to_remove = db_elem; + + db_elem = DLGetSucc(db_elem); + remove_db_from_list(elem_to_remove); + } + else + db_elem = DLGetSucc(db_elem); + } /* Done removing dropped databases from + * the table_list */ + + /* + * Then loop use result set as outer loop and db_list as the inner + * loop to determine what databases are new + */ + for (i = 0; i < t; i++) + { + db_elem = DLGetHead(db_list); + found_match = 0; + while (NULL != db_elem) + { + dbi = ((db_info *) DLE_VAL(db_elem)); + if (dbi->oid == atoi(PQgetvalue(res, i, PQfnumber(res, "oid")))) + { + found_match = 1; + break; + } + db_elem = DLGetSucc(db_elem); + } + if (0 == found_match) /* then we didn't find this result + * now in the tbl_list */ + { + DLAddTail(db_list, DLNewElem(init_dbinfo + (PQgetvalue(res, i, PQfnumber(res, "datname")), + atoi(PQgetvalue(res, i, PQfnumber(res, "oid"))), + atoi(PQgetvalue(res, i, PQfnumber(res, "age")))))); + if (args->debug >= 1) + { + sprintf(logbuffer, "added database: %s", ((db_info *) DLE_VAL(DLGetTail(db_list)))->dbname); + log_entry(logbuffer); + } + } + } /* end of for loop that adds tables */ + fflush(LOGOUTPUT); + PQclear(res); + res = NULL; + if (args->debug >= 3) + print_db_list(db_list, 0); + if (disconnect) + db_disconnect(dbi_template1); + } } /* xid_wraparound_check @@ -504,101 +569,116 @@ return 0 if nothing happened, return 1 if the database needed a database wide vacuum */ int -xid_wraparound_check (db_info * dbi) +xid_wraparound_check(db_info * dbi) { - /* FIXME: should probably do something better here so that we don't vacuum all the - databases on the server at the same time. We have 500million xacts to work with so - we should be able to spread the load of full database vacuums a bit */ - if (1500000000 < dbi->age) { - PGresult *res = NULL; - res = send_query ("vacuum", dbi); - /* FIXME: Perhaps should add a check for PQ_COMMAND_OK */ - PQclear (res); - return 1; - } - return 0; + /* + * FIXME: should probably do something better here so that we don't + * vacuum all the databases on the server at the same time. We have + * 500million xacts to work with so we should be able to spread the + * load of full database vacuums a bit + */ + if (1500000000 < dbi->age) + { + PGresult *res = NULL; + + res = send_query("vacuum", dbi); + /* FIXME: Perhaps should add a check for PQ_COMMAND_OK */ + PQclear(res); + return 1; + } + return 0; } /* Close DB connection, free memory, and remove the node from the list */ void -remove_db_from_list (Dlelem * db_to_remove) +remove_db_from_list(Dlelem *db_to_remove) { - db_info *dbi = ((db_info *) DLE_VAL (db_to_remove)); + db_info *dbi = ((db_info *) DLE_VAL(db_to_remove)); - if (args->debug >= 1) { - sprintf (logbuffer, "Removing db: %s from list.", dbi->dbname); - log_entry (logbuffer); - fflush (LOGOUTPUT); - } - DLRemove (db_to_remove); - if (dbi->conn) - db_disconnect (dbi); - if (dbi->dbname) { - free (dbi->dbname); - dbi->dbname = NULL; - } - if (dbi->username) { - free (dbi->username); - dbi->username = NULL; - } - if (dbi->password) { - free (dbi->password); - dbi->password = NULL; - } - if (dbi->table_list) { - free_tbl_list (dbi->table_list); - dbi->table_list = NULL; - } - if (dbi) { - free (dbi); - dbi = NULL; - } - DLFreeElem (db_to_remove); + if (args->debug >= 1) + { + sprintf(logbuffer, "Removing db: %s from list.", dbi->dbname); + log_entry(logbuffer); + fflush(LOGOUTPUT); + } + DLRemove(db_to_remove); + if (dbi->conn) + db_disconnect(dbi); + if (dbi->dbname) + { + free(dbi->dbname); + dbi->dbname = NULL; + } + if (dbi->username) + { + free(dbi->username); + dbi->username = NULL; + } + if (dbi->password) + { + free(dbi->password); + dbi->password = NULL; + } + if (dbi->table_list) + { + free_tbl_list(dbi->table_list); + dbi->table_list = NULL; + } + if (dbi) + { + free(dbi); + dbi = NULL; + } + DLFreeElem(db_to_remove); } /* Function is called before program exit to free all memory mostly it's just to keep valgrind happy */ void -free_db_list (Dllist * db_list) +free_db_list(Dllist *db_list) { - Dlelem *db_elem = DLGetHead (db_list); - Dlelem *db_elem_to_remove = NULL; - while (NULL != db_elem) { - db_elem_to_remove = db_elem; - db_elem = DLGetSucc (db_elem); - remove_db_from_list (db_elem_to_remove); - db_elem_to_remove = NULL; - } - DLFreeList (db_list); + Dlelem *db_elem = DLGetHead(db_list); + Dlelem *db_elem_to_remove = NULL; + + while (NULL != db_elem) + { + db_elem_to_remove = db_elem; + db_elem = DLGetSucc(db_elem); + remove_db_from_list(db_elem_to_remove); + db_elem_to_remove = NULL; + } + DLFreeList(db_list); } void -print_db_list (Dllist * db_list, int print_table_lists) +print_db_list(Dllist *db_list, int print_table_lists) { - Dlelem *db_elem = DLGetHead (db_list); - while (NULL != db_elem) { - print_db_info (((db_info *) DLE_VAL (db_elem)), print_table_lists); - db_elem = DLGetSucc (db_elem); - } + Dlelem *db_elem = DLGetHead(db_list); + + while (NULL != db_elem) + { + print_db_info(((db_info *) DLE_VAL(db_elem)), print_table_lists); + db_elem = DLGetSucc(db_elem); + } } void -print_db_info (db_info * dbi, int print_tbl_list) +print_db_info(db_info * dbi, int print_tbl_list) { - sprintf (logbuffer, "dbname: %s Username %s Passwd %s", dbi->dbname, - dbi->username, dbi->password); - log_entry (logbuffer); - sprintf (logbuffer, " oid %i InsertThresh: %i DeleteThresh: %i", dbi->oid, - dbi->analyze_threshold, dbi->vacuum_threshold); - log_entry (logbuffer); - if (NULL != dbi->conn) - log_entry (" conn is valid, we are connected"); - else - log_entry (" conn is null, we are not connected."); + sprintf(logbuffer, "dbname: %s Username %s Passwd %s", dbi->dbname, + dbi->username, dbi->password); + log_entry(logbuffer); + sprintf(logbuffer, " oid %i InsertThresh: %i DeleteThresh: %i", dbi->oid, + dbi->analyze_threshold, dbi->vacuum_threshold); + log_entry(logbuffer); + if (NULL != dbi->conn) + log_entry(" conn is valid, we are connected"); + else + log_entry(" conn is null, we are not connected."); - fflush (LOGOUTPUT); - if (0 < print_tbl_list) - print_table_list (dbi->table_list); + fflush(LOGOUTPUT); + if (0 < print_tbl_list) + print_table_list(dbi->table_list); } /* End of DB List Management Function */ @@ -607,406 +687,475 @@ print_db_info (db_info * dbi, int print_tbl_list) char * -query_table_stats (db_info * dbi) +query_table_stats(db_info * dbi) { - if (!strcmp (dbi->dbname, "template1")) /* Use template1 to monitor the system tables */ - return (char *) TABLE_STATS_ALL; - else - return (char *) TABLE_STATS_USER; + if (!strcmp(dbi->dbname, "template1")) /* Use template1 to + * monitor the system + * tables */ + return (char *) TABLE_STATS_ALL; + else + return (char *) TABLE_STATS_USER; } /* Perhaps add some test to this function to make sure that the stats we need are available */ PGconn * -db_connect (db_info * dbi) +db_connect(db_info * dbi) { - PGconn *db_conn = - PQsetdbLogin (args->host, args->port, NULL, NULL, dbi->dbname, - dbi->username, dbi->password); + PGconn *db_conn = + PQsetdbLogin(args->host, args->port, NULL, NULL, dbi->dbname, + dbi->username, dbi->password); - if (CONNECTION_OK != PQstatus (db_conn)) { - sprintf (logbuffer, "Failed connection to database %s with error: %s.", - dbi->dbname, PQerrorMessage (db_conn)); - log_entry (logbuffer); - fflush (LOGOUTPUT); - PQfinish (db_conn); - db_conn = NULL; - } - return db_conn; -} /* end of db_connect() */ + if (CONNECTION_OK != PQstatus(db_conn)) + { + sprintf(logbuffer, "Failed connection to database %s with error: %s.", + dbi->dbname, PQerrorMessage(db_conn)); + log_entry(logbuffer); + fflush(LOGOUTPUT); + PQfinish(db_conn); + db_conn = NULL; + } + return db_conn; +} /* end of db_connect() */ void -db_disconnect (db_info * dbi) +db_disconnect(db_info * dbi) { - if (NULL != dbi->conn) { - PQfinish (dbi->conn); - dbi->conn = NULL; - } + if (NULL != dbi->conn) + { + PQfinish(dbi->conn); + dbi->conn = NULL; + } } int -check_stats_enabled (db_info * dbi) +check_stats_enabled(db_info * dbi) { - PGresult *res = NULL; - int ret = 0; - res = send_query ("show stats_row_level", dbi); - ret = - strcmp ("on", PQgetvalue (res, 0, PQfnumber (res, "stats_row_level"))); - PQclear (res); - return ret; + PGresult *res = NULL; + int ret = 0; + + res = send_query("show stats_row_level", dbi); + ret = + strcmp("on", PQgetvalue(res, 0, PQfnumber(res, "stats_row_level"))); + PQclear(res); + return ret; } PGresult * -send_query (const char *query, db_info * dbi) +send_query(const char *query, db_info * dbi) { - PGresult *res; + PGresult *res; - if (NULL == dbi->conn) - return NULL; + if (NULL == dbi->conn) + return NULL; - res = PQexec (dbi->conn, query); + res = PQexec(dbi->conn, query); - if (!res) { - sprintf (logbuffer, - "Fatal error occured while sending query (%s) to database %s", - query, dbi->dbname); - log_entry (logbuffer); - sprintf (logbuffer, "The error is [%s]", PQresultErrorMessage (res)); - log_entry (logbuffer); - fflush (LOGOUTPUT); - return NULL; - } - if (PQresultStatus (res) != PGRES_TUPLES_OK - && PQresultStatus (res) != PGRES_COMMAND_OK) { - sprintf (logbuffer, - "Can not refresh statistics information from the database %s.", - dbi->dbname); - log_entry (logbuffer); - sprintf (logbuffer, "The error is [%s]", PQresultErrorMessage (res)); - log_entry (logbuffer); - fflush (LOGOUTPUT); - PQclear (res); - return NULL; - } - return res; -} /* End of send_query() */ + if (!res) + { + sprintf(logbuffer, + "Fatal error occured while sending query (%s) to database %s", + query, dbi->dbname); + log_entry(logbuffer); + sprintf(logbuffer, "The error is [%s]", PQresultErrorMessage(res)); + log_entry(logbuffer); + fflush(LOGOUTPUT); + return NULL; + } + if (PQresultStatus(res) != PGRES_TUPLES_OK + && PQresultStatus(res) != PGRES_COMMAND_OK) + { + sprintf(logbuffer, + "Can not refresh statistics information from the database %s.", + dbi->dbname); + log_entry(logbuffer); + sprintf(logbuffer, "The error is [%s]", PQresultErrorMessage(res)); + log_entry(logbuffer); + fflush(LOGOUTPUT); + PQclear(res); + return NULL; + } + return res; +} /* End of send_query() */ void -free_cmd_args () +free_cmd_args() { - if (NULL != args) { - if (NULL != args->user) - free (args->user); - if (NULL != args->user) - free (args->password); - free (args); - } + if (NULL != args) + { + if (NULL != args->user) + free(args->user); + if (NULL != args->user) + free(args->password); + free(args); + } } cmd_args * -get_cmd_args (int argc, char *argv[]) +get_cmd_args(int argc, char *argv[]) { - int c; - args = (cmd_args *) malloc (sizeof (cmd_args)); - args->sleep_base_value = SLEEPBASEVALUE; - args->sleep_scaling_factor = SLEEPSCALINGFACTOR; - args->vacuum_base_threshold = VACBASETHRESHOLD; - args->vacuum_scaling_factor = VACSCALINGFACTOR; - args->analyze_base_threshold = -1; - args->analyze_scaling_factor = -1; - args->debug = AUTOVACUUM_DEBUG; - args->daemonize = 0; + int c; - /* Fixme: Should add some sanity checking such as positive integer values etc */ - while (-1 != (c = getopt (argc, argv, "s:S:v:V:a:A:d:U:P:H:L:p:hD"))) { - switch (c) { - case 's': - args->sleep_base_value = atoi (optarg); - break; - case 'S': - args->sleep_scaling_factor = atof (optarg); - break; - case 'v': - args->vacuum_base_threshold = atoi (optarg); - break; - case 'V': - args->vacuum_scaling_factor = atof (optarg); - break; - case 'a': - args->analyze_base_threshold = atoi (optarg); - break; - case 'A': - args->analyze_scaling_factor = atof (optarg); - break; - case 'D': - args->daemonize++; - break; - case 'd': - args->debug = atoi (optarg); - break; - case 'U': - args->user = optarg; - break; - case 'P': - args->password = optarg; - break; - case 'H': - args->host = optarg; - break; - case 'L': - args->logfile = optarg; - break; - case 'p': - args->port = optarg; - break; - case 'h': - usage(); - exit (0); - default: - /* It's here that we know that things are invalid... - It is not forcibly an error to call usage */ - fprintf (stderr, "Error: Invalid Command Line Options.\n"); - usage(); - exit (1); - break; - } - /* if values for insert thresholds are not specified, - then they default to 1/2 of the delete values */ - if(-1 == args->analyze_base_threshold) - args->analyze_base_threshold = args->vacuum_base_threshold / 2; - if(-1 == args->analyze_scaling_factor) - args->analyze_scaling_factor = args->vacuum_scaling_factor / 2; - } - return args; -} + args = (cmd_args *) malloc(sizeof(cmd_args)); + args->sleep_base_value = SLEEPBASEVALUE; + args->sleep_scaling_factor = SLEEPSCALINGFACTOR; + args->vacuum_base_threshold = VACBASETHRESHOLD; + args->vacuum_scaling_factor = VACSCALINGFACTOR; + args->analyze_base_threshold = -1; + args->analyze_scaling_factor = -1; + args->debug = AUTOVACUUM_DEBUG; + args->daemonize = 0; -void usage() -{ - int i=0; - float f=0; - fprintf (stderr, "usage: pg_autovacuum \n"); - fprintf (stderr, " [-D] Daemonize (Detach from tty and run in the background)\n"); - i=AUTOVACUUM_DEBUG; - fprintf (stderr, " [-d] debug (debug level=0,1,2,3; default=%i)\n",i); + /* + * Fixme: Should add some sanity checking such as positive integer + * values etc + */ + while (-1 != (c = getopt(argc, argv, "s:S:v:V:a:A:d:U:P:H:L:p:hD"))) + { + switch (c) + { + case 's': + args->sleep_base_value = atoi(optarg); + break; + case 'S': + args->sleep_scaling_factor = atof(optarg); + break; + case 'v': + args->vacuum_base_threshold = atoi(optarg); + break; + case 'V': + args->vacuum_scaling_factor = atof(optarg); + break; + case 'a': + args->analyze_base_threshold = atoi(optarg); + break; + case 'A': + args->analyze_scaling_factor = atof(optarg); + break; + case 'D': + args->daemonize++; + break; + case 'd': + args->debug = atoi(optarg); + break; + case 'U': + args->user = optarg; + break; + case 'P': + args->password = optarg; + break; + case 'H': + args->host = optarg; + break; + case 'L': + args->logfile = optarg; + break; + case 'p': + args->port = optarg; + break; + case 'h': + usage(); + exit(0); + default: - i=SLEEPBASEVALUE; - fprintf (stderr, " [-s] sleep base value (default=%i)\n",i); - f=SLEEPSCALINGFACTOR; - fprintf (stderr, " [-S] sleep scaling factor (default=%f)\n",f); + /* + * It's here that we know that things are invalid... It is + * not forcibly an error to call usage + */ + fprintf(stderr, "Error: Invalid Command Line Options.\n"); + usage(); + exit(1); + break; + } - i=VACBASETHRESHOLD; - fprintf (stderr, " [-v] vacuum base threshold (default=%i)\n",i); - f=VACSCALINGFACTOR; - fprintf (stderr, " [-V] vacuum scaling factor (default=%f)\n",f); - i=i/2; - fprintf (stderr, " [-a] analyze base threshold (default=%i)\n",i); - f=f/2; - fprintf (stderr, " [-A] analyze scaling factor (default=%f)\n",f); - - fprintf (stderr, " [-L] logfile (default=none)\n"); - - fprintf (stderr, " [-U] username (libpq default)\n"); - fprintf (stderr, " [-P] password (libpq default)\n"); - fprintf (stderr, " [-H] host (libpq default)\n"); - fprintf (stderr, " [-p] port (libpq default)\n"); - - fprintf (stderr, " [-h] help (Show this output)\n"); + /* + * if values for insert thresholds are not specified, then they + * default to 1/2 of the delete values + */ + if (-1 == args->analyze_base_threshold) + args->analyze_base_threshold = args->vacuum_base_threshold / 2; + if (-1 == args->analyze_scaling_factor) + args->analyze_scaling_factor = args->vacuum_scaling_factor / 2; + } + return args; } void -print_cmd_args () +usage() { - sprintf (logbuffer, "Printing command_args"); - log_entry (logbuffer); - sprintf (logbuffer, " args->host=%s", (args->host) ? args->host : "(null)"); - log_entry (logbuffer); - sprintf (logbuffer, " args->port=%s", (args->port) ? args->port : "(null)"); - log_entry (logbuffer); - sprintf (logbuffer, " args->user=%s", (args->user) ? args->user : "(null)"); - log_entry (logbuffer); - sprintf (logbuffer, " args->password=%s",(args->password) ? args->password : "(null)"); - log_entry (logbuffer); - sprintf (logbuffer, " args->logfile=%s",(args->logfile) ? args->logfile : "(null)"); - log_entry (logbuffer); - sprintf (logbuffer, " args->daemonize=%i",args->daemonize); - log_entry (logbuffer); + int i = 0; + float f = 0; - sprintf (logbuffer, " args->sleep_base_value=%i", args->sleep_base_value); - log_entry (logbuffer); - sprintf (logbuffer, " args->sleep_scaling_factor=%f",args->sleep_scaling_factor); - log_entry (logbuffer); - sprintf (logbuffer, " args->vacuum_base_threshold=%i",args->vacuum_base_threshold); - log_entry (logbuffer); - sprintf (logbuffer, " args->vacuum_scaling_factor=%f",args->vacuum_scaling_factor); - log_entry (logbuffer); - sprintf (logbuffer, " args->analyze_base_threshold=%i",args->analyze_base_threshold); - log_entry (logbuffer); - sprintf (logbuffer, " args->analyze_scaling_factor=%f",args->analyze_scaling_factor); - log_entry (logbuffer); - sprintf (logbuffer, " args->debug=%i", args->debug); - log_entry (logbuffer); + fprintf(stderr, "usage: pg_autovacuum \n"); + fprintf(stderr, " [-D] Daemonize (Detach from tty and run in the background)\n"); + i = AUTOVACUUM_DEBUG; + fprintf(stderr, " [-d] debug (debug level=0,1,2,3; default=%i)\n", i); - fflush (LOGOUTPUT); + i = SLEEPBASEVALUE; + fprintf(stderr, " [-s] sleep base value (default=%i)\n", i); + f = SLEEPSCALINGFACTOR; + fprintf(stderr, " [-S] sleep scaling factor (default=%f)\n", f); + + i = VACBASETHRESHOLD; + fprintf(stderr, " [-v] vacuum base threshold (default=%i)\n", i); + f = VACSCALINGFACTOR; + fprintf(stderr, " [-V] vacuum scaling factor (default=%f)\n", f); + i = i / 2; + fprintf(stderr, " [-a] analyze base threshold (default=%i)\n", i); + f = f / 2; + fprintf(stderr, " [-A] analyze scaling factor (default=%f)\n", f); + + fprintf(stderr, " [-L] logfile (default=none)\n"); + + fprintf(stderr, " [-U] username (libpq default)\n"); + fprintf(stderr, " [-P] password (libpq default)\n"); + fprintf(stderr, " [-H] host (libpq default)\n"); + fprintf(stderr, " [-p] port (libpq default)\n"); + + fprintf(stderr, " [-h] help (Show this output)\n"); +} + +void +print_cmd_args() +{ + sprintf(logbuffer, "Printing command_args"); + log_entry(logbuffer); + sprintf(logbuffer, " args->host=%s", (args->host) ? args->host : "(null)"); + log_entry(logbuffer); + sprintf(logbuffer, " args->port=%s", (args->port) ? args->port : "(null)"); + log_entry(logbuffer); + sprintf(logbuffer, " args->user=%s", (args->user) ? args->user : "(null)"); + log_entry(logbuffer); + sprintf(logbuffer, " args->password=%s", (args->password) ? args->password : "(null)"); + log_entry(logbuffer); + sprintf(logbuffer, " args->logfile=%s", (args->logfile) ? args->logfile : "(null)"); + log_entry(logbuffer); + sprintf(logbuffer, " args->daemonize=%i", args->daemonize); + log_entry(logbuffer); + + sprintf(logbuffer, " args->sleep_base_value=%i", args->sleep_base_value); + log_entry(logbuffer); + sprintf(logbuffer, " args->sleep_scaling_factor=%f", args->sleep_scaling_factor); + log_entry(logbuffer); + sprintf(logbuffer, " args->vacuum_base_threshold=%i", args->vacuum_base_threshold); + log_entry(logbuffer); + sprintf(logbuffer, " args->vacuum_scaling_factor=%f", args->vacuum_scaling_factor); + log_entry(logbuffer); + sprintf(logbuffer, " args->analyze_base_threshold=%i", args->analyze_base_threshold); + log_entry(logbuffer); + sprintf(logbuffer, " args->analyze_scaling_factor=%f", args->analyze_scaling_factor); + log_entry(logbuffer); + sprintf(logbuffer, " args->debug=%i", args->debug); + log_entry(logbuffer); + + fflush(LOGOUTPUT); } /* Beginning of AutoVacuum Main Program */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - char buf[256]; - int j = 0, loops = 0; -/* int numInserts, numDeletes, */ - int sleep_secs; - Dllist *db_list; - Dlelem *db_elem, *tbl_elem; - db_info *dbs; - tbl_info *tbl; - PGresult *res=NULL; - long long diff = 0; - struct timeval now, then; + char buf[256]; + int j = 0, + loops = 0; - args = get_cmd_args (argc, argv); /* Get Command Line Args and put them in the args struct */ +/* int numInserts, numDeletes, */ + int sleep_secs; + Dllist *db_list; + Dlelem *db_elem, + *tbl_elem; + db_info *dbs; + tbl_info *tbl; + PGresult *res = NULL; + long long diff = 0; + struct timeval now, + then; - /* Dameonize if requested */ - if (1 == args->daemonize){ daemonize(); } + args = get_cmd_args(argc, argv); /* Get Command Line Args and put + * them in the args struct */ - if (args->logfile) { - LOGOUTPUT = fopen (args->logfile, "a"); - if (!LOGOUTPUT) { - fprintf (stderr, "Could not open log file - [%s]\n", args->logfile); - exit(-1); - } - } - else { - LOGOUTPUT = stderr; - } - if (args->debug >= 2) { - print_cmd_args (); - } + /* Dameonize if requested */ + if (1 == args->daemonize) + daemonize(); - /* Init the db list with template1 */ - db_list = init_db_list (); - if (NULL == db_list) - return 1; - - if (0 != check_stats_enabled (((db_info *) DLE_VAL (DLGetHead (db_list))))) { - log_entry ("Error: GUC variable stats_row_level must be enabled."); - log_entry (" Please fix the problems and try again."); - fflush (LOGOUTPUT); - - exit (1); - } - - gettimeofday (&then, 0); /* for use later to caluculate sleep time */ - - while (1) { /* Main Loop */ - db_elem = DLGetHead (db_list); /* Reset cur_db_node to the beginning of the db_list */ - - dbs = ((db_info *) DLE_VAL (db_elem)); /* get pointer to cur_db's db_info struct */ - if (NULL == dbs->conn) { - dbs->conn = db_connect (dbs); - if (NULL == dbs->conn) { /* Serious problem: We can't connect to template1 */ - log_entry ("Error: Cannot connect to template1, exiting."); - fflush (LOGOUTPUT); - fclose (LOGOUTPUT); - exit (1); - } - } - - if (0 == (loops % UPDATE_INTERVAL)) /* Update the list if it's time */ - update_db_list (db_list); /* Add and remove databases from the list */ - - while (NULL != db_elem) { /* Loop through databases in list */ - dbs = ((db_info *) DLE_VAL (db_elem)); /* get pointer to cur_db's db_info struct */ - if (NULL == dbs->conn) - dbs->conn = db_connect (dbs); - - if (NULL != dbs->conn) { - if (0 == (loops % UPDATE_INTERVAL)) /* Update the list if it's time */ - update_table_list (dbs); /* Add and remove tables from the list */ - - if (0 == xid_wraparound_check (dbs)); + if (args->logfile) { - res = send_query (query_table_stats (dbs), dbs); /* Get an updated snapshot of this dbs table stats */ - for (j = 0; j < PQntuples (res); j++) { /* loop through result set */ - tbl_elem = DLGetHead (dbs->table_list); /* Reset tbl_elem to top of dbs->table_list */ - while (NULL != tbl_elem) { /* Loop through tables in list */ - tbl = ((tbl_info *) DLE_VAL (tbl_elem)); /* set tbl_info = current_table */ - if (tbl->relfilenode == atoi (PQgetvalue(res, j, PQfnumber (res, "relfilenode")))) { - tbl->curr_analyze_count = - (atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_ins"))) + - atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_upd"))) + - atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_del")))); - tbl->curr_vacuum_count = - (atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_del"))) + - atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_upd")))); + LOGOUTPUT = fopen(args->logfile, "a"); + if (!LOGOUTPUT) + { + fprintf(stderr, "Could not open log file - [%s]\n", args->logfile); + exit(-1); + } + } + else + LOGOUTPUT = stderr; + if (args->debug >= 2) + print_cmd_args(); - /* Check numDeletes to see if we need to vacuum, if so: - Run vacuum analyze (adding analyze is small so we might as well) - Update table thresholds and related information - if numDeletes is not big enough for vacuum then check numInserts for analyze */ - if ((tbl->curr_vacuum_count - tbl->CountAtLastVacuum) >= tbl->vacuum_threshold) - { - snprintf (buf, sizeof (buf), "vacuum analyze %s", tbl->table_name); - if (args->debug >= 1) { - sprintf (logbuffer, "Performing: %s", buf); - log_entry (logbuffer); - fflush (LOGOUTPUT); - } - send_query (buf, dbs); - update_table_thresholds (dbs, tbl, VACUUM_ANALYZE); - if (args->debug >= 2) {print_table_info (tbl);} - } - else if ((tbl->curr_analyze_count - tbl->CountAtLastAnalyze) >= tbl->analyze_threshold) - { - snprintf (buf, sizeof (buf), "analyze %s", tbl->table_name); - if (args->debug >= 1) { - sprintf (logbuffer, "Performing: %s", buf); - log_entry (logbuffer); - fflush (LOGOUTPUT); - } - send_query (buf, dbs); - update_table_thresholds (dbs, tbl, ANALYZE_ONLY); - if (args->debug >= 2) { print_table_info (tbl); } - } - - break; /* once we have found a match, no need to keep checking. */ - } - /* Advance the table pointers for the next loop */ - tbl_elem = DLGetSucc (tbl_elem); + /* Init the db list with template1 */ + db_list = init_db_list(); + if (NULL == db_list) + return 1; - } /* end for table while loop */ - } /* end for j loop (tuples in PGresult) */ - } /* close of if(xid_wraparound_check()) */ - /* Done working on this db, Clean up, then advance cur_db */ - PQclear (res); - res = NULL; - db_disconnect (dbs); - } - db_elem = DLGetSucc (db_elem); /* move on to next DB regardless */ - } /* end of db_list while loop */ + if (0 != check_stats_enabled(((db_info *) DLE_VAL(DLGetHead(db_list))))) + { + log_entry("Error: GUC variable stats_row_level must be enabled."); + log_entry(" Please fix the problems and try again."); + fflush(LOGOUTPUT); - /* Figure out how long to sleep etc ... */ - gettimeofday (&now, 0); - diff = (now.tv_sec - then.tv_sec) * 1000000 + (now.tv_usec - then.tv_usec); + exit(1); + } - sleep_secs = args->sleep_base_value + args->sleep_scaling_factor * diff / 1000000; - loops++; - if (args->debug >= 2) { - sprintf (logbuffer, - "%i All DBs checked in: %lld usec, will sleep for %i secs.", - loops, diff, sleep_secs); - log_entry (logbuffer); - } + gettimeofday(&then, 0); /* for use later to caluculate sleep time */ - sleep (sleep_secs); /* Larger Pause between outer loops */ + while (1) + { /* Main Loop */ + db_elem = DLGetHead(db_list); /* Reset cur_db_node to the + * beginning of the db_list */ - gettimeofday (&then, 0); /* Reset time counter */ + dbs = ((db_info *) DLE_VAL(db_elem)); /* get pointer to cur_db's + * db_info struct */ + if (NULL == dbs->conn) + { + dbs->conn = db_connect(dbs); + if (NULL == dbs->conn) + { /* Serious problem: We can't connect to + * template1 */ + log_entry("Error: Cannot connect to template1, exiting."); + fflush(LOGOUTPUT); + fclose(LOGOUTPUT); + exit(1); + } + } - } /* end of while loop */ + if (0 == (loops % UPDATE_INTERVAL)) /* Update the list if it's + * time */ + update_db_list(db_list); /* Add and remove databases from + * the list */ - /* program is exiting, this should never run, but is here to make compiler / valgrind happy */ - free_db_list (db_list); - free_cmd_args (); - return EXIT_SUCCESS; + while (NULL != db_elem) + { /* Loop through databases in list */ + dbs = ((db_info *) DLE_VAL(db_elem)); /* get pointer to + * cur_db's db_info + * struct */ + if (NULL == dbs->conn) + dbs->conn = db_connect(dbs); + + if (NULL != dbs->conn) + { + if (0 == (loops % UPDATE_INTERVAL)) /* Update the list if + * it's time */ + update_table_list(dbs); /* Add and remove tables + * from the list */ + + if (0 == xid_wraparound_check(dbs)); + { + res = send_query(query_table_stats(dbs), dbs); /* Get an updated + * snapshot of this dbs + * table stats */ + for (j = 0; j < PQntuples(res); j++) + { /* loop through result set */ + tbl_elem = DLGetHead(dbs->table_list); /* Reset tbl_elem to top + * of dbs->table_list */ + while (NULL != tbl_elem) + { /* Loop through tables in list */ + tbl = ((tbl_info *) DLE_VAL(tbl_elem)); /* set tbl_info = + * current_table */ + if (tbl->relfilenode == atoi(PQgetvalue(res, j, PQfnumber(res, "relfilenode")))) + { + tbl->curr_analyze_count = + (atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_ins"))) + + atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_upd"))) + + atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_del")))); + tbl->curr_vacuum_count = + (atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_del"))) + + atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_upd")))); + + /* + * Check numDeletes to see if we need to + * vacuum, if so: Run vacuum analyze + * (adding analyze is small so we might as + * well) Update table thresholds and + * related information if numDeletes is + * not big enough for vacuum then check + * numInserts for analyze + */ + if ((tbl->curr_vacuum_count - tbl->CountAtLastVacuum) >= tbl->vacuum_threshold) + { + snprintf(buf, sizeof(buf), "vacuum analyze %s", tbl->table_name); + if (args->debug >= 1) + { + sprintf(logbuffer, "Performing: %s", buf); + log_entry(logbuffer); + fflush(LOGOUTPUT); + } + send_query(buf, dbs); + update_table_thresholds(dbs, tbl, VACUUM_ANALYZE); + if (args->debug >= 2) + print_table_info(tbl); + } + else if ((tbl->curr_analyze_count - tbl->CountAtLastAnalyze) >= tbl->analyze_threshold) + { + snprintf(buf, sizeof(buf), "analyze %s", tbl->table_name); + if (args->debug >= 1) + { + sprintf(logbuffer, "Performing: %s", buf); + log_entry(logbuffer); + fflush(LOGOUTPUT); + } + send_query(buf, dbs); + update_table_thresholds(dbs, tbl, ANALYZE_ONLY); + if (args->debug >= 2) + print_table_info(tbl); + } + + break; /* once we have found a match, no + * need to keep checking. */ + } + + /* + * Advance the table pointers for the next + * loop + */ + tbl_elem = DLGetSucc(tbl_elem); + + } /* end for table while loop */ + } /* end for j loop (tuples in PGresult) */ + } /* close of if(xid_wraparound_check()) */ + /* Done working on this db, Clean up, then advance cur_db */ + PQclear(res); + res = NULL; + db_disconnect(dbs); + } + db_elem = DLGetSucc(db_elem); /* move on to next DB + * regardless */ + } /* end of db_list while loop */ + + /* Figure out how long to sleep etc ... */ + gettimeofday(&now, 0); + diff = (now.tv_sec - then.tv_sec) * 1000000 + (now.tv_usec - then.tv_usec); + + sleep_secs = args->sleep_base_value + args->sleep_scaling_factor * diff / 1000000; + loops++; + if (args->debug >= 2) + { + sprintf(logbuffer, + "%i All DBs checked in: %lld usec, will sleep for %i secs.", + loops, diff, sleep_secs); + log_entry(logbuffer); + } + + sleep(sleep_secs); /* Larger Pause between outer loops */ + + gettimeofday(&then, 0); /* Reset time counter */ + + } /* end of while loop */ + + /* + * program is exiting, this should never run, but is here to make + * compiler / valgrind happy + */ + free_db_list(db_list); + free_cmd_args(); + return EXIT_SUCCESS; } diff --git a/contrib/pg_autovacuum/pg_autovacuum.h b/contrib/pg_autovacuum/pg_autovacuum.h index ac97f63bec..fbdaf69912 100644 --- a/contrib/pg_autovacuum/pg_autovacuum.h +++ b/contrib/pg_autovacuum/pg_autovacuum.h @@ -23,19 +23,19 @@ #include "/usr/include/pgsql/server/lib/dllist.h" */ -#define AUTOVACUUM_DEBUG 1 -#define VACBASETHRESHOLD 1000 -#define VACSCALINGFACTOR 2 -#define SLEEPBASEVALUE 300 -#define SLEEPSCALINGFACTOR 2 -#define UPDATE_INTERVAL 2 +#define AUTOVACUUM_DEBUG 1 +#define VACBASETHRESHOLD 1000 +#define VACSCALINGFACTOR 2 +#define SLEEPBASEVALUE 300 +#define SLEEPSCALINGFACTOR 2 +#define UPDATE_INTERVAL 2 /* these two constants are used to tell update_table_stats what operation we just perfomred */ -#define VACUUM_ANALYZE 0 -#define ANALYZE_ONLY 1 +#define VACUUM_ANALYZE 0 +#define ANALYZE_ONLY 1 -#define TABLE_STATS_ALL "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_all_tables b where a.relfilenode=b.relid" -#define TABLE_STATS_USER "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_user_tables b where a.relfilenode=b.relid" +#define TABLE_STATS_ALL "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_all_tables b where a.relfilenode=b.relid" +#define TABLE_STATS_USER "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_user_tables b where a.relfilenode=b.relid" #define FRONTEND #define PAGES_QUERY "select relfilenode,reltuples,relpages from pg_class where relfilenode=%i" #define FROZENOID_QUERY "select oid,age(datfrozenxid) from pg_database where datname = 'template1'" @@ -44,71 +44,96 @@ /* define cmd_args stucture */ struct cmdargs { - int vacuum_base_threshold, analyze_base_threshold, sleep_base_value, debug, daemonize; - float vacuum_scaling_factor, analyze_scaling_factor, sleep_scaling_factor; - char *user, *password, *host, *logfile, *port; + int vacuum_base_threshold, + analyze_base_threshold, + sleep_base_value, + debug, + daemonize; + float vacuum_scaling_factor, + analyze_scaling_factor, + sleep_scaling_factor; + char *user, + *password, + *host, + *logfile, + *port; }; typedef struct cmdargs cmd_args; /* define cmd_args as global so we can get to them everywhere */ -cmd_args *args; +cmd_args *args; /* Might need to add a time value for last time the whold database was vacuumed. - I think we need to guarantee this happens approx every 1Million TX's */ + I think we need to guarantee this happens approx every 1Million TX's */ struct dbinfo { - int oid, age; - int analyze_threshold, vacuum_threshold; /* Use these as defaults for table thresholds */ - PGconn *conn; - char *dbname, *username, *password; - Dllist *table_list; + int oid, + age; + int analyze_threshold, + vacuum_threshold; /* Use these as defaults for table + * thresholds */ + PGconn *conn; + char *dbname, + *username, + *password; + Dllist *table_list; }; typedef struct dbinfo db_info; struct tableinfo { - char *schema_name, *table_name; - int relfilenode, reltuples, relpages; - long analyze_threshold, vacuum_threshold; - long CountAtLastAnalyze; /* equal to: inserts + updates as of the last analyze or initial values at startup */ - long CountAtLastVacuum; /* equal to: deletes + updates as of the last vacuum or initial values at startup */ - long curr_analyze_count, curr_vacuum_count; /* Latest values from stats system */ - db_info *dbi; /* pointer to the database that this table belongs to */ + char *schema_name, + *table_name; + int relfilenode, + reltuples, + relpages; + long analyze_threshold, + vacuum_threshold; + long CountAtLastAnalyze; /* equal to: inserts + updates as + * of the last analyze or initial + * values at startup */ + long CountAtLastVacuum; /* equal to: deletes + updates as + * of the last vacuum or initial + * values at startup */ + long curr_analyze_count, + curr_vacuum_count; /* Latest values from stats system */ + db_info *dbi; /* pointer to the database that this table + * belongs to */ }; typedef struct tableinfo tbl_info; /* Functions for dealing with command line arguements */ -static cmd_args *get_cmd_args (int argc, char *argv[]); -static void print_cmd_args (void); -static void free_cmd_args (void); -static void usage (void); +static cmd_args *get_cmd_args(int argc, char *argv[]); +static void print_cmd_args(void); +static void free_cmd_args(void); +static void usage(void); /* Functions for managing database lists */ -static Dllist *init_db_list (void); -static db_info *init_dbinfo (char *dbname, int oid, int age); -static void update_db_list (Dllist * db_list); -static void remove_db_from_list (Dlelem * db_to_remove); -static void print_db_info (db_info * dbi, int print_table_list); -static void print_db_list (Dllist * db_list, int print_table_lists); -static int xid_wraparound_check (db_info * dbi); -static void free_db_list (Dllist * db_list); +static Dllist *init_db_list(void); +static db_info *init_dbinfo(char *dbname, int oid, int age); +static void update_db_list(Dllist *db_list); +static void remove_db_from_list(Dlelem *db_to_remove); +static void print_db_info(db_info * dbi, int print_table_list); +static void print_db_list(Dllist *db_list, int print_table_lists); +static int xid_wraparound_check(db_info * dbi); +static void free_db_list(Dllist *db_list); /* Functions for managing table lists */ -static tbl_info *init_table_info (PGresult * conn, int row, db_info *dbi); -static void update_table_list (db_info * dbi); -static void remove_table_from_list (Dlelem * tbl_to_remove); -static void print_table_list (Dllist * tbl_node); -static void print_table_info (tbl_info * tbl); -static void update_table_thresholds (db_info * dbi, tbl_info * tbl, int vacuum_type); -static void free_tbl_list (Dllist * tbl_list); +static tbl_info *init_table_info(PGresult *conn, int row, db_info * dbi); +static void update_table_list(db_info * dbi); +static void remove_table_from_list(Dlelem *tbl_to_remove); +static void print_table_list(Dllist *tbl_node); +static void print_table_info(tbl_info * tbl); +static void update_table_thresholds(db_info * dbi, tbl_info * tbl, int vacuum_type); +static void free_tbl_list(Dllist *tbl_list); /* A few database helper functions */ -static int check_stats_enabled (db_info * dbi); -static PGconn *db_connect (db_info * dbi); -static void db_disconnect (db_info * dbi); -static PGresult *send_query (const char *query, db_info * dbi); -static char *query_table_stats (db_info * dbi); +static int check_stats_enabled(db_info * dbi); +static PGconn *db_connect(db_info * dbi); +static void db_disconnect(db_info * dbi); +static PGresult *send_query(const char *query, db_info * dbi); +static char *query_table_stats(db_info * dbi); /* Other Generally needed Functions */ static void daemonize(void); -static void log_entry (const char *logentry); +static void log_entry(const char *logentry); diff --git a/contrib/pg_dumplo/main.c b/contrib/pg_dumplo/main.c index b6783c23ef..09a71a586d 100644 --- a/contrib/pg_dumplo/main.c +++ b/contrib/pg_dumplo/main.c @@ -1,7 +1,7 @@ /* ------------------------------------------------------------------------- * pg_dumplo * - * $Header: /cvsroot/pgsql/contrib/pg_dumplo/Attic/main.c,v 1.16 2003/05/14 03:25:56 tgl Exp $ + * $Header: /cvsroot/pgsql/contrib/pg_dumplo/Attic/main.c,v 1.17 2003/08/04 00:43:11 momjian Exp $ * * Karel Zak 1999-2000 * ------------------------------------------------------------------------- @@ -26,7 +26,7 @@ #ifndef HAVE_GETOPT_LONG #include "getopt_long.h" -int optreset; +int optreset; #endif char *progname = NULL; diff --git a/contrib/pgbench/pgbench.c b/contrib/pgbench/pgbench.c index 3253dab4b6..ede1b02f6f 100644 --- a/contrib/pgbench/pgbench.c +++ b/contrib/pgbench/pgbench.c @@ -1,5 +1,5 @@ /* - * $Header: /cvsroot/pgsql/contrib/pgbench/pgbench.c,v 1.25 2003/08/01 02:21:17 tgl Exp $ + * $Header: /cvsroot/pgsql/contrib/pgbench/pgbench.c,v 1.26 2003/08/04 00:43:11 momjian Exp $ * * pgbench: a simple TPC-B like benchmark program for PostgreSQL * written by Tatsuo Ishii @@ -122,7 +122,7 @@ doConnect() { PGconn *con; PGresult *res; - + con = PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName, login, pwd); if (con == NULL) diff --git a/contrib/pgcrypto/openssl.c b/contrib/pgcrypto/openssl.c index 3e7915d8bb..4b3dc593ce 100644 --- a/contrib/pgcrypto/openssl.c +++ b/contrib/pgcrypto/openssl.c @@ -26,7 +26,7 @@ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * - * $Id: openssl.c,v 1.11 2002/11/15 02:54:44 momjian Exp $ + * $Id: openssl.c,v 1.12 2003/08/04 00:43:11 momjian Exp $ */ #include @@ -130,18 +130,19 @@ px_find_digest(const char *name, PX_MD ** res) * of functions does not allow enough flexibility * and forces some of the parameters (keylen, * padding) to SSL defaults. - * + * * So need to manage ciphers ourselves. */ -struct ossl_cipher { - int (*init) (PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv); - int (*encrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res); - int (*decrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res); +struct ossl_cipher +{ + int (*init) (PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv); + int (*encrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res); + int (*decrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res); - int block_size; - int max_key_size; - int stream_cipher; + int block_size; + int max_key_size; + int stream_cipher; }; typedef struct @@ -224,7 +225,7 @@ static int bf_ecb_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res) { unsigned bs = gen_ossl_block_size(c); - unsigned i; + unsigned i; ossldata *od = c->ptr; for (i = 0; i < dlen / bs; i++) @@ -288,13 +289,13 @@ static int ossl_des_init(PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv) { ossldata *od = c->ptr; - des_cblock xkey; + des_cblock xkey; memset(&xkey, 0, sizeof(xkey)); memcpy(&xkey, key, klen > 8 ? 8 : klen); des_set_key(&xkey, od->u.des.key_schedule); memset(&xkey, 0, sizeof(xkey)); - + if (iv) memcpy(od->iv, iv, 8); else @@ -304,53 +305,53 @@ ossl_des_init(PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv) static int ossl_des_ecb_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, - uint8 *res) + uint8 *res) { unsigned bs = gen_ossl_block_size(c); - unsigned i; + unsigned i; ossldata *od = c->ptr; for (i = 0; i < dlen / bs; i++) - des_ecb_encrypt((des_cblock*)(data + i * bs), - (des_cblock*)(res + i * bs), - od->u.des.key_schedule, 1); + des_ecb_encrypt((des_cblock *) (data + i * bs), + (des_cblock *) (res + i * bs), + od->u.des.key_schedule, 1); return 0; } static int ossl_des_ecb_decrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, - uint8 *res) + uint8 *res) { unsigned bs = gen_ossl_block_size(c); - unsigned i; + unsigned i; ossldata *od = c->ptr; for (i = 0; i < dlen / bs; i++) - des_ecb_encrypt((des_cblock*)(data + i * bs), - (des_cblock*)(res + i * bs), - od->u.des.key_schedule, 0); + des_ecb_encrypt((des_cblock *) (data + i * bs), + (des_cblock *) (res + i * bs), + od->u.des.key_schedule, 0); return 0; } static int ossl_des_cbc_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, - uint8 *res) + uint8 *res) { ossldata *od = c->ptr; des_ncbc_encrypt(data, res, dlen, od->u.des.key_schedule, - (des_cblock*)od->iv, 1); + (des_cblock *) od->iv, 1); return 0; } static int ossl_des_cbc_decrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, - uint8 *res) + uint8 *res) { ossldata *od = c->ptr; des_ncbc_encrypt(data, res, dlen, od->u.des.key_schedule, - (des_cblock*)od->iv, 0); + (des_cblock *) od->iv, 0); return 0; } @@ -375,7 +376,7 @@ ossl_cast_ecb_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *re { unsigned bs = gen_ossl_block_size(c); ossldata *od = c->ptr; - const uint8 *end = data + dlen - bs; + const uint8 *end = data + dlen - bs; for (; data <= end; data += bs, res += bs) CAST_ecb_encrypt(data, res, &od->u.cast_key, CAST_ENCRYPT); @@ -387,7 +388,7 @@ ossl_cast_ecb_decrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *re { unsigned bs = gen_ossl_block_size(c); ossldata *od = c->ptr; - const uint8 *end = data + dlen - bs; + const uint8 *end = data + dlen - bs; for (; data <= end; data += bs, res += bs) CAST_ecb_encrypt(data, res, &od->u.cast_key, CAST_DECRYPT); @@ -429,37 +430,37 @@ static PX_Alias ossl_aliases[] = { static const struct ossl_cipher ossl_bf_cbc = { bf_init, bf_cbc_encrypt, bf_cbc_decrypt, - 64/8, 448/8, 0 + 64 / 8, 448 / 8, 0 }; static const struct ossl_cipher ossl_bf_ecb = { bf_init, bf_ecb_encrypt, bf_ecb_decrypt, - 64/8, 448/8, 0 + 64 / 8, 448 / 8, 0 }; static const struct ossl_cipher ossl_bf_cfb = { bf_init, bf_cfb64_encrypt, bf_cfb64_decrypt, - 64/8, 448/8, 1 + 64 / 8, 448 / 8, 1 }; static const struct ossl_cipher ossl_des_ecb = { ossl_des_init, ossl_des_ecb_encrypt, ossl_des_ecb_decrypt, - 64/8, 64/8, 0 + 64 / 8, 64 / 8, 0 }; static const struct ossl_cipher ossl_des_cbc = { ossl_des_init, ossl_des_cbc_encrypt, ossl_des_cbc_decrypt, - 64/8, 64/8, 0 + 64 / 8, 64 / 8, 0 }; static const struct ossl_cipher ossl_cast_ecb = { ossl_cast_init, ossl_cast_ecb_encrypt, ossl_cast_ecb_decrypt, - 64/8, 128/8, 0 + 64 / 8, 128 / 8, 0 }; static const struct ossl_cipher ossl_cast_cbc = { ossl_cast_init, ossl_cast_cbc_encrypt, ossl_cast_cbc_decrypt, - 64/8, 128/8, 0 + 64 / 8, 128 / 8, 0 }; /* @@ -467,7 +468,7 @@ static const struct ossl_cipher ossl_cast_cbc = { */ static const struct { - const char *name; + const char *name; const struct ossl_cipher *ciph; } ossl_cipher_types[] = @@ -510,8 +511,10 @@ px_find_cipher(const char *name, PX_Cipher ** res) const struct ossl_cipher *ossl_ciph = NULL; name = px_resolve_alias(ossl_aliases, name); - for (i = 0; ossl_cipher_types[i].name; i++) { - if (!strcmp(ossl_cipher_types[i].name, name)) { + for (i = 0; ossl_cipher_types[i].name; i++) + { + if (!strcmp(ossl_cipher_types[i].name, name)) + { ossl_ciph = ossl_cipher_types[i].ciph; break; } diff --git a/contrib/pgcrypto/pgcrypto.c b/contrib/pgcrypto/pgcrypto.c index de0d426f46..3abc6f12b1 100644 --- a/contrib/pgcrypto/pgcrypto.c +++ b/contrib/pgcrypto/pgcrypto.c @@ -26,7 +26,7 @@ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * - * $Id: pgcrypto.c,v 1.13 2003/07/24 17:52:33 tgl Exp $ + * $Id: pgcrypto.c,v 1.14 2003/08/04 00:43:11 momjian Exp $ */ #include @@ -241,7 +241,7 @@ pg_gen_salt_rounds(PG_FUNCTION_ARGS) if (len == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("no such crypt algorithm or bad number of rounds"))); + errmsg("no such crypt algorithm or bad number of rounds"))); res = (text *) palloc(len + VARHDRSZ); VARATT_SIZEP(res) = len + VARHDRSZ; diff --git a/contrib/pgstattuple/pgstattuple.c b/contrib/pgstattuple/pgstattuple.c index 110de6dff4..94160605dc 100644 --- a/contrib/pgstattuple/pgstattuple.c +++ b/contrib/pgstattuple/pgstattuple.c @@ -1,5 +1,5 @@ /* - * $Header: /cvsroot/pgsql/contrib/pgstattuple/pgstattuple.c,v 1.11 2003/08/01 02:21:17 tgl Exp $ + * $Header: /cvsroot/pgsql/contrib/pgstattuple/pgstattuple.c,v 1.12 2003/08/04 00:43:11 momjian Exp $ * * Copyright (c) 2001,2002 Tatsuo Ishii * @@ -221,5 +221,5 @@ pgstattuple_real(Relation rel) pfree(values[i]); pfree(values); - return(result); + return (result); } diff --git a/contrib/spi/autoinc.c b/contrib/spi/autoinc.c index 31bd21b04e..b6e0c64331 100644 --- a/contrib/spi/autoinc.c +++ b/contrib/spi/autoinc.c @@ -73,8 +73,8 @@ autoinc(PG_FUNCTION_ARGS) if (SPI_gettypeid(tupdesc, attnum) != INT4OID) ereport(ERROR, (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION), - errmsg("attribute \"%s\" of \"%s\" must be type INT4", - args[i], relname))); + errmsg("attribute \"%s\" of \"%s\" must be type INT4", + args[i], relname))); val = DatumGetInt32(SPI_getbinval(rettuple, tupdesc, attnum, &isnull)); diff --git a/contrib/spi/insert_username.c b/contrib/spi/insert_username.c index 6fa9c4c6f8..237b14d25c 100644 --- a/contrib/spi/insert_username.c +++ b/contrib/spi/insert_username.c @@ -65,17 +65,17 @@ insert_username(PG_FUNCTION_ARGS) if (attnum < 0) ereport(ERROR, (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION), - errmsg("\"%s\" has no attribute \"%s\"", relname, args[0]))); + errmsg("\"%s\" has no attribute \"%s\"", relname, args[0]))); if (SPI_gettypeid(tupdesc, attnum) != TEXTOID) ereport(ERROR, (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION), errmsg("attribute \"%s\" of \"%s\" must be type TEXT", - args[0], relname))); + args[0], relname))); /* create fields containing name */ newval = DirectFunctionCall1(textin, - CStringGetDatum(GetUserNameFromId(GetUserId()))); + CStringGetDatum(GetUserNameFromId(GetUserId()))); /* construct new tuple */ rettuple = SPI_modifytuple(rel, rettuple, 1, &attnum, &newval, NULL); diff --git a/contrib/spi/moddatetime.c b/contrib/spi/moddatetime.c index 6d80bab55e..f3a97e1c81 100644 --- a/contrib/spi/moddatetime.c +++ b/contrib/spi/moddatetime.c @@ -100,8 +100,8 @@ moddatetime(PG_FUNCTION_ARGS) if (SPI_gettypeid(tupdesc, attnum) != TIMESTAMPOID) ereport(ERROR, (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION), - errmsg("attribute \"%s\" of \"%s\" must be type TIMESTAMP", - args[0], relname))); + errmsg("attribute \"%s\" of \"%s\" must be type TIMESTAMP", + args[0], relname))); /* 1 is the number of items in the arrays attnum and newdt. attnum is the positional number of the field to be updated. diff --git a/contrib/spi/refint.c b/contrib/spi/refint.c index c9baa9c249..c409a269ca 100644 --- a/contrib/spi/refint.c +++ b/contrib/spi/refint.c @@ -134,8 +134,8 @@ check_primary_key(PG_FUNCTION_ARGS) if (fnumber < 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("there is no attribute \"%s\" in relation \"%s\"", - args[i], SPI_getrelname(rel)))); + errmsg("there is no attribute \"%s\" in relation \"%s\"", + args[i], SPI_getrelname(rel)))); /* Well, get binary (in internal format) value of column */ kvals[i] = SPI_getbinval(tuple, tupdesc, fnumber, &isnull); @@ -365,8 +365,8 @@ check_foreign_key(PG_FUNCTION_ARGS) if (fnumber < 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("there is no attribute \"%s\" in relation \"%s\"", - args[i], SPI_getrelname(rel)))); + errmsg("there is no attribute \"%s\" in relation \"%s\"", + args[i], SPI_getrelname(rel)))); /* Well, get binary (in internal format) value of column */ kvals[i] = SPI_getbinval(trigtuple, tupdesc, fnumber, &isnull); @@ -591,7 +591,7 @@ check_foreign_key(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION), errmsg("\"%s\": tuple is referenced in \"%s\"", - trigger->tgname, relname))); + trigger->tgname, relname))); } else { diff --git a/contrib/spi/timetravel.c b/contrib/spi/timetravel.c index aa8d0a47b4..8ffa56edc7 100644 --- a/contrib/spi/timetravel.c +++ b/contrib/spi/timetravel.c @@ -6,11 +6,11 @@ /* Modified by BÖJTHE Zoltán, Hungary, mailto:urdesobt@axelero.hu */ #include "executor/spi.h" /* this is what you need to work with SPI */ -#include "commands/trigger.h" /* -"- and triggers */ +#include "commands/trigger.h" /* -"- and triggers */ #include "miscadmin.h" /* for GetPgUserName() */ -#include /* tolower () */ +#include /* tolower () */ -#define ABSTIMEOID 702 /* it should be in pg_type.h */ +#define ABSTIMEOID 702 /* it should be in pg_type.h */ /* AbsoluteTime currabstime(void); */ Datum timetravel(PG_FUNCTION_ARGS); @@ -28,13 +28,13 @@ static int nPlans = 0; typedef struct _TTOffList { - struct _TTOffList *next; - char name[1]; -} TTOffList; + struct _TTOffList *next; + char name[1]; +} TTOffList; -static TTOffList TTOff = {NULL,{0}}; +static TTOffList TTOff = {NULL, {0}}; -static int findTTStatus(char *name); +static int findTTStatus(char *name); static EPlan *find_plan(char *ident, EPlan ** eplan, int *nplans); /* @@ -71,57 +71,57 @@ static EPlan *find_plan(char *ident, EPlan ** eplan, int *nplans); PG_FUNCTION_INFO_V1(timetravel); -Datum /* have to return HeapTuple to Executor */ +Datum /* have to return HeapTuple to Executor */ timetravel(PG_FUNCTION_ARGS) { - TriggerData *trigdata = (TriggerData *) fcinfo->context; - Trigger *trigger; /* to get trigger name */ - int argc; - char **args; /* arguments */ - int attnum[MaxAttrNum]; /* fnumbers of start/stop columns */ + TriggerData *trigdata = (TriggerData *) fcinfo->context; + Trigger *trigger; /* to get trigger name */ + int argc; + char **args; /* arguments */ + int attnum[MaxAttrNum]; /* fnumbers of start/stop columns */ Datum oldtimeon, - oldtimeoff; + oldtimeoff; Datum newtimeon, - newtimeoff, - newuser, - nulltext; - Datum *cvals; /* column values */ - char *cnulls; /* column nulls */ - char *relname; /* triggered relation name */ + newtimeoff, + newuser, + nulltext; + Datum *cvals; /* column values */ + char *cnulls; /* column nulls */ + char *relname; /* triggered relation name */ Relation rel; /* triggered relation */ HeapTuple trigtuple; HeapTuple newtuple = NULL; HeapTuple rettuple; TupleDesc tupdesc; /* tuple description */ - int natts; /* # of attributes */ - EPlan *plan; /* prepared plan */ + int natts; /* # of attributes */ + EPlan *plan; /* prepared plan */ char ident[2 * NAMEDATALEN]; bool isnull; /* to know is some column NULL or not */ bool isinsert = false; - int ret; - int i; + int ret; + int i; /* * Some checks first... */ /* Called by trigger manager ? */ - if(!CALLED_AS_TRIGGER(fcinfo)) + if (!CALLED_AS_TRIGGER(fcinfo)) elog(ERROR, "timetravel: not fired by trigger manager"); /* Should be called for ROW trigger */ - if(TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event)) + if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event)) elog(ERROR, "timetravel: can't process STATEMENT events"); /* Should be called BEFORE */ - if(TRIGGER_FIRED_AFTER(trigdata->tg_event)) + if (TRIGGER_FIRED_AFTER(trigdata->tg_event)) elog(ERROR, "timetravel: must be fired before event"); /* INSERT ? */ - if(TRIGGER_FIRED_BY_INSERT(trigdata->tg_event)) + if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event)) isinsert = true; - if(TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) + if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) newtuple = trigdata->tg_newtuple; trigtuple = trigdata->tg_trigtuple; @@ -130,7 +130,7 @@ timetravel(PG_FUNCTION_ARGS) relname = SPI_getrelname(rel); /* check if TT is OFF for this relation */ - if(0==findTTStatus(relname)) + if (0 == findTTStatus(relname)) { /* OFF - nothing to do */ pfree(relname); @@ -140,7 +140,7 @@ timetravel(PG_FUNCTION_ARGS) trigger = trigdata->tg_trigger; argc = trigger->tgnargs; - if(argc != MinAttrNum && argc != MaxAttrNum) + if (argc != MinAttrNum && argc != MaxAttrNum) elog(ERROR, "timetravel (%s): invalid (!= %d or %d) number of arguments %d", relname, MinAttrNum, MaxAttrNum, trigger->tgnargs); @@ -148,39 +148,39 @@ timetravel(PG_FUNCTION_ARGS) tupdesc = rel->rd_att; natts = tupdesc->natts; - for(i = 0 ; i < MinAttrNum ; i++) + for (i = 0; i < MinAttrNum; i++) { attnum[i] = SPI_fnumber(tupdesc, args[i]); - if(attnum[i] < 0) + if (attnum[i] < 0) elog(ERROR, "timetravel (%s): there is no attribute %s", relname, args[i]); - if(SPI_gettypeid(tupdesc, attnum[i]) != ABSTIMEOID) + if (SPI_gettypeid(tupdesc, attnum[i]) != ABSTIMEOID) elog(ERROR, "timetravel (%s): attribute %s must be of abstime type", relname, args[i]); } - for( ; i < argc ; i++) + for (; i < argc; i++) { attnum[i] = SPI_fnumber(tupdesc, args[i]); - if(attnum[i] < 0) + if (attnum[i] < 0) elog(ERROR, "timetravel (%s): there is no attribute %s", relname, args[i]); - if(SPI_gettypeid(tupdesc, attnum[i]) != TEXTOID) + if (SPI_gettypeid(tupdesc, attnum[i]) != TEXTOID) elog(ERROR, "timetravel (%s): attribute %s must be of text type", relname, args[i]); } /* create fields containing name */ - newuser = DirectFunctionCall1(textin, CStringGetDatum(GetUserNameFromId(GetUserId()))); + newuser = DirectFunctionCall1(textin, CStringGetDatum(GetUserNameFromId(GetUserId()))); - nulltext = (Datum)NULL; + nulltext = (Datum) NULL; - if(isinsert) - { /* INSERT */ - int chnattrs = 0; - int chattrs[MaxAttrNum]; - Datum newvals[MaxAttrNum]; - char newnulls[MaxAttrNum]; + if (isinsert) + { /* INSERT */ + int chnattrs = 0; + int chattrs[MaxAttrNum]; + Datum newvals[MaxAttrNum]; + char newnulls[MaxAttrNum]; oldtimeon = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_on], &isnull); - if(isnull) + if (isnull) { newvals[chnattrs] = GetCurrentAbsoluteTime(); newnulls[chnattrs] = ' '; @@ -189,10 +189,10 @@ timetravel(PG_FUNCTION_ARGS) } oldtimeoff = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_off], &isnull); - if(isnull) + if (isnull) { - if((chnattrs == 0 && DatumGetInt32(oldtimeon) >= NOEND_ABSTIME) || - (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) >= NOEND_ABSTIME)) + if ((chnattrs == 0 && DatumGetInt32(oldtimeon) >= NOEND_ABSTIME) || + (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) >= NOEND_ABSTIME)) elog(ERROR, "timetravel (%s): %s is infinity", relname, args[a_time_on]); newvals[chnattrs] = NOEND_ABSTIME; newnulls[chnattrs] = ' '; @@ -201,16 +201,16 @@ timetravel(PG_FUNCTION_ARGS) } else { - if((chnattrs == 0 && DatumGetInt32(oldtimeon) > DatumGetInt32(oldtimeoff)) || - (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) > DatumGetInt32(oldtimeoff))) + if ((chnattrs == 0 && DatumGetInt32(oldtimeon) > DatumGetInt32(oldtimeoff)) || + (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) > DatumGetInt32(oldtimeoff))) elog(ERROR, "timetravel (%s): %s gt %s", relname, args[a_time_on], args[a_time_off]); } pfree(relname); - if(chnattrs <= 0) + if (chnattrs <= 0) return PointerGetDatum(trigtuple); - if(argc == MaxAttrNum) + if (argc == MaxAttrNum) { /* clear update_user value */ newvals[chnattrs] = nulltext; @@ -235,33 +235,34 @@ timetravel(PG_FUNCTION_ARGS) /* UPDATE/DELETE: */ oldtimeon = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_on], &isnull); - if(isnull) + if (isnull) elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_on]); oldtimeoff = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_off], &isnull); - if(isnull) + if (isnull) elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_off]); /* * If DELETE/UPDATE of tuple with stop_date neq INFINITY then say * upper Executor to skip operation for this tuple */ - if(newtuple != NULL) - { /* UPDATE */ + if (newtuple != NULL) + { /* UPDATE */ newtimeon = SPI_getbinval(newtuple, tupdesc, attnum[a_time_on], &isnull); - if(isnull) + if (isnull) elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_on]); newtimeoff = SPI_getbinval(newtuple, tupdesc, attnum[a_time_off], &isnull); - if(isnull) + if (isnull) elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_off]); - if(oldtimeon != newtimeon || oldtimeoff != newtimeoff) + if (oldtimeon != newtimeon || oldtimeoff != newtimeoff) elog(ERROR, "timetravel (%s): you can't change %s and/or %s columns (use set_timetravel)", relname, args[a_time_on], args[a_time_off]); } - if(oldtimeoff != NOEND_ABSTIME) - { /* current record is a deleted/updated record */ + if (oldtimeoff != NOEND_ABSTIME) + { /* current record is a deleted/updated + * record */ pfree(relname); return PointerGetDatum(NULL); } @@ -269,27 +270,28 @@ timetravel(PG_FUNCTION_ARGS) newtimeoff = GetCurrentAbsoluteTime(); /* Connect to SPI manager */ - if((ret = SPI_connect()) < 0) + if ((ret = SPI_connect()) < 0) elog(ERROR, "timetravel (%s): SPI_connect returned %d", relname, ret); /* Fetch tuple values and nulls */ cvals = (Datum *) palloc(natts * sizeof(Datum)); cnulls = (char *) palloc(natts * sizeof(char)); - for(i = 0; i < natts; i++) + for (i = 0; i < natts; i++) { cvals[i] = SPI_getbinval(trigtuple, tupdesc, i + 1, &isnull); cnulls[i] = (isnull) ? 'n' : ' '; } /* change date column(s) */ - cvals[attnum[a_time_off] - 1] = newtimeoff; /* stop_date eq current date */ + cvals[attnum[a_time_off] - 1] = newtimeoff; /* stop_date eq current + * date */ cnulls[attnum[a_time_off] - 1] = ' '; - if(!newtuple) - { /* DELETE */ - if(argc == MaxAttrNum) + if (!newtuple) + { /* DELETE */ + if (argc == MaxAttrNum) { - cvals[attnum[a_del_user] - 1] = newuser; /* set delete user */ + cvals[attnum[a_del_user] - 1] = newuser; /* set delete user */ cnulls[attnum[a_del_user] - 1] = ' '; } } @@ -302,11 +304,11 @@ timetravel(PG_FUNCTION_ARGS) plan = find_plan(ident, &Plans, &nPlans); /* if there is no plan ... */ - if(plan->splan == NULL) + if (plan->splan == NULL) { - void *pplan; - Oid *ctypes; - char sql[8192]; + void *pplan; + Oid *ctypes; + char sql[8192]; /* allocate ctypes for preparation */ ctypes = (Oid *) palloc(natts * sizeof(Oid)); @@ -315,15 +317,15 @@ timetravel(PG_FUNCTION_ARGS) * Construct query: INSERT INTO _relation_ VALUES ($1, ...) */ snprintf(sql, sizeof(sql), "INSERT INTO %s VALUES (", relname); - for(i = 1; i <= natts; i++) + for (i = 1; i <= natts; i++) { ctypes[i - 1] = SPI_gettypeid(tupdesc, i); - if(!(tupdesc->attrs[i - 1]->attisdropped)) /* skip dropped columns */ - snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d%s", - i, (i < natts) ? ", " : ")" ); + if (!(tupdesc->attrs[i - 1]->attisdropped)) /* skip dropped columns */ + snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d%s", + i, (i < natts) ? ", " : ")"); #if 0 - snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d /* %d */ %s", - i, ctypes[i-1], (i < natts) ? ", " : ")" ); + snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d /* %d */ %s", + i, ctypes[i - 1], (i < natts) ? ", " : ")"); #endif } @@ -331,7 +333,7 @@ timetravel(PG_FUNCTION_ARGS) /* Prepare plan for query */ pplan = SPI_prepare(sql, natts, ctypes); - if(pplan == NULL) + if (pplan == NULL) elog(ERROR, "timetravel (%s): SPI_prepare returned %d", relname, SPI_result); /* @@ -340,7 +342,7 @@ timetravel(PG_FUNCTION_ARGS) * use. */ pplan = SPI_saveplan(pplan); - if(pplan == NULL) + if (pplan == NULL) elog(ERROR, "timetravel (%s): SPI_saveplan returned %d", relname, SPI_result); plan->splan = pplan; @@ -351,14 +353,14 @@ timetravel(PG_FUNCTION_ARGS) */ ret = SPI_execp(plan->splan, cvals, cnulls, 0); - if(ret < 0) + if (ret < 0) elog(ERROR, "timetravel (%s): SPI_execp returned %d", relname, ret); /* Tuple to return to upper Executor ... */ - if(newtuple) - { /* UPDATE */ - int chnattrs = 0; - int chattrs[MaxAttrNum]; + if (newtuple) + { /* UPDATE */ + int chnattrs = 0; + int chattrs[MaxAttrNum]; Datum newvals[MaxAttrNum]; char newnulls[MaxAttrNum]; @@ -372,7 +374,7 @@ timetravel(PG_FUNCTION_ARGS) chattrs[chnattrs] = attnum[a_time_off]; chnattrs++; - if(argc == MaxAttrNum) + if (argc == MaxAttrNum) { /* set update_user value */ newvals[chnattrs] = newuser; @@ -399,7 +401,8 @@ timetravel(PG_FUNCTION_ARGS) */ /* SPI_pfree(tmptuple); */ } - else /* DELETE case */ + else +/* DELETE case */ rettuple = trigtuple; SPI_finish(); /* don't forget say Bye to SPI mgr */ @@ -417,23 +420,24 @@ PG_FUNCTION_INFO_V1(set_timetravel); Datum set_timetravel(PG_FUNCTION_ARGS) { - Name relname = PG_GETARG_NAME(0); - int32 on = PG_GETARG_INT32(1); - char *rname; - char *d; - char *s; + Name relname = PG_GETARG_NAME(0); + int32 on = PG_GETARG_INT32(1); + char *rname; + char *d; + char *s; int32 ret; - TTOffList *p,*pp; + TTOffList *p, + *pp; - for(pp = (p = &TTOff)->next; pp; pp=(p=pp)->next) + for (pp = (p = &TTOff)->next; pp; pp = (p = pp)->next) { - if(namestrcmp(relname, pp->name) == 0) + if (namestrcmp(relname, pp->name) == 0) break; } - if(pp) + if (pp) { /* OFF currently */ - if(on != 0) + if (on != 0) { /* turn ON */ p->next = pp->next; @@ -444,20 +448,20 @@ set_timetravel(PG_FUNCTION_ARGS) else { /* ON currently */ - if(on == 0) + if (on == 0) { /* turn OFF */ s = rname = DatumGetCString(DirectFunctionCall1(nameout, NameGetDatum(relname))); - if(s) + if (s) { - pp = malloc(sizeof(TTOffList)+strlen(rname)); - if(pp) + pp = malloc(sizeof(TTOffList) + strlen(rname)); + if (pp) { pp->next = NULL; p->next = pp; d = pp->name; while (*s) - *d++ = tolower((unsigned char)*s++); + *d++ = tolower((unsigned char) *s++); *d = '\0'; } pfree(rname); @@ -470,7 +474,7 @@ set_timetravel(PG_FUNCTION_ARGS) /* * get_timetravel (relname) -- - * get timetravel status for specified relation (ON/OFF) + * get timetravel status for specified relation (ON/OFF) */ PG_FUNCTION_INFO_V1(get_timetravel); @@ -478,11 +482,11 @@ Datum get_timetravel(PG_FUNCTION_ARGS) { Name relname = PG_GETARG_NAME(0); - TTOffList *pp; + TTOffList *pp; - for(pp = TTOff.next; pp; pp = pp->next) + for (pp = TTOff.next; pp; pp = pp->next) { - if(namestrcmp(relname, pp->name) == 0) + if (namestrcmp(relname, pp->name) == 0) PG_RETURN_INT32(0); } PG_RETURN_INT32(1); @@ -491,9 +495,10 @@ get_timetravel(PG_FUNCTION_ARGS) static int findTTStatus(char *name) { - TTOffList* pp; - for(pp = TTOff.next; pp; pp = pp->next) - if(strcasecmp(name, pp->name) == 0) + TTOffList *pp; + + for (pp = TTOff.next; pp; pp = pp->next) + if (strcasecmp(name, pp->name) == 0) return 0; return 1; } @@ -509,17 +514,17 @@ currabstime() static EPlan * find_plan(char *ident, EPlan ** eplan, int *nplans) { - EPlan *newp; - int i; + EPlan *newp; + int i; - if(*nplans > 0) + if (*nplans > 0) { - for(i = 0; i < *nplans; i++) + for (i = 0; i < *nplans; i++) { - if(strcmp((*eplan)[i].ident, ident) == 0) + if (strcmp((*eplan)[i].ident, ident) == 0) break; } - if(i != *nplans) + if (i != *nplans) return (*eplan + i); *eplan = (EPlan *) realloc(*eplan, (i + 1) * sizeof(EPlan)); newp = *eplan + i; diff --git a/contrib/tablefunc/tablefunc.c b/contrib/tablefunc/tablefunc.c index d883793aac..17a3a6a857 100644 --- a/contrib/tablefunc/tablefunc.c +++ b/contrib/tablefunc/tablefunc.c @@ -42,11 +42,11 @@ #include "tablefunc.h" -static int load_categories_hash(char *cats_sql, MemoryContext per_query_ctx); +static int load_categories_hash(char *cats_sql, MemoryContext per_query_ctx); static Tuplestorestate *get_crosstab_tuplestore(char *sql, - int num_categories, - TupleDesc tupdesc, - MemoryContext per_query_ctx); + int num_categories, + TupleDesc tupdesc, + MemoryContext per_query_ctx); static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial); static bool compatCrosstabTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2); static bool compatConnectbyTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2); @@ -56,7 +56,7 @@ static TupleDesc make_crosstab_tupledesc(TupleDesc spi_tupdesc, static Tuplestorestate *connectby(char *relname, char *key_fld, char *parent_key_fld, - char *orderby_fld, + char *orderby_fld, char *branch_delim, char *start_with, int max_depth, @@ -115,7 +115,7 @@ static HTAB *crosstab_HashTable; typedef struct crosstab_cat_desc { char *catname; - int attidx; /* zero based */ + int attidx; /* zero based */ } crosstab_cat_desc; #define MAX_CATNAME_LEN NAMEDATALEN @@ -157,9 +157,9 @@ do { \ /* hash table */ typedef struct crosstab_hashent { - char internal_catname[MAX_CATNAME_LEN]; - crosstab_cat_desc *catdesc; -} crosstab_HashEnt; + char internal_catname[MAX_CATNAME_LEN]; + crosstab_cat_desc *catdesc; +} crosstab_HashEnt; /* * normal_rand - return requested number of random values @@ -414,7 +414,7 @@ crosstab(PG_FUNCTION_ARGS) (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid source data SQL statement"), errdetail("The provided SQL must return 3 " \ - " columns; rowid, category, and values."))); + " columns; rowid, category, and values."))); } else { @@ -667,10 +667,10 @@ crosstab(PG_FUNCTION_ARGS) } /* - * crosstab_hash - reimplement crosstab as materialized function and + * crosstab_hash - reimplement crosstab as materialized function and * properly deal with missing values (i.e. don't pack remaining * values to the left) - * + * * crosstab - create a crosstab of rowids and values columns from a * SQL statement returning one rowid column, one category column, * and one value column. @@ -705,13 +705,13 @@ PG_FUNCTION_INFO_V1(crosstab_hash); Datum crosstab_hash(PG_FUNCTION_ARGS) { - char *sql = GET_STR(PG_GETARG_TEXT_P(0)); - char *cats_sql = GET_STR(PG_GETARG_TEXT_P(1)); - ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; - TupleDesc tupdesc; - MemoryContext per_query_ctx; - MemoryContext oldcontext; - int num_categories; + char *sql = GET_STR(PG_GETARG_TEXT_P(0)); + char *cats_sql = GET_STR(PG_GETARG_TEXT_P(1)); + ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; + TupleDesc tupdesc; + MemoryContext per_query_ctx; + MemoryContext oldcontext; + int num_categories; /* check to see if caller supports us returning a tuplestore */ if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize)) @@ -729,9 +729,9 @@ crosstab_hash(PG_FUNCTION_ARGS) /* * Check to make sure we have a reasonable tuple descriptor * - * Note we will attempt to coerce the values into whatever - * the return attribute type is and depend on the "in" - * function to complain if needed. + * Note we will attempt to coerce the values into whatever the return + * attribute type is and depend on the "in" function to complain if + * needed. */ if (tupdesc->natts < 2) ereport(ERROR, @@ -770,19 +770,19 @@ crosstab_hash(PG_FUNCTION_ARGS) static int load_categories_hash(char *cats_sql, MemoryContext per_query_ctx) { - HASHCTL ctl; - int ret; - int proc; - MemoryContext SPIcontext; - int num_categories = 0; + HASHCTL ctl; + int ret; + int proc; + MemoryContext SPIcontext; + int num_categories = 0; /* initialize the category hash table */ ctl.keysize = MAX_CATNAME_LEN; ctl.entrysize = sizeof(crosstab_HashEnt); /* - * use INIT_CATS, defined above as a guess of how - * many hash table entries to create, initially + * use INIT_CATS, defined above as a guess of how many hash table + * entries to create, initially */ crosstab_HashTable = hash_create("crosstab hash", INIT_CATS, &ctl, HASH_ELEM); @@ -798,13 +798,13 @@ load_categories_hash(char *cats_sql, MemoryContext per_query_ctx) /* Check for qualifying tuples */ if ((ret == SPI_OK_SELECT) && (proc > 0)) { - SPITupleTable *spi_tuptable = SPI_tuptable; - TupleDesc spi_tupdesc = spi_tuptable->tupdesc; - int i; + SPITupleTable *spi_tuptable = SPI_tuptable; + TupleDesc spi_tupdesc = spi_tuptable->tupdesc; + int i; /* - * The provided categories SQL query must always return one column: - * category - the label or identifier for each column + * The provided categories SQL query must always return one + * column: category - the label or identifier for each column */ if (spi_tupdesc->natts != 1) ereport(ERROR, @@ -814,9 +814,9 @@ load_categories_hash(char *cats_sql, MemoryContext per_query_ctx) for (i = 0; i < proc; i++) { - crosstab_cat_desc *catdesc; - char *catname; - HeapTuple spi_tuple; + crosstab_cat_desc *catdesc; + char *catname; + HeapTuple spi_tuple; /* get the next sql result tuple */ spi_tuple = spi_tuptable->vals[i]; @@ -862,13 +862,13 @@ get_crosstab_tuplestore(char *sql, TupleDesc tupdesc, MemoryContext per_query_ctx) { - Tuplestorestate *tupstore; - AttInMetadata *attinmeta = TupleDescGetAttInMetadata(tupdesc); - char **values; - HeapTuple tuple; - int ret; - int proc; - MemoryContext SPIcontext; + Tuplestorestate *tupstore; + AttInMetadata *attinmeta = TupleDescGetAttInMetadata(tupdesc); + char **values; + HeapTuple tuple; + int ret; + int proc; + MemoryContext SPIcontext; /* initialize our tuplestore */ tupstore = tuplestore_begin_heap(true, false, SortMem); @@ -885,33 +885,36 @@ get_crosstab_tuplestore(char *sql, /* Check for qualifying tuples */ if ((ret == SPI_OK_SELECT) && (proc > 0)) { - SPITupleTable *spi_tuptable = SPI_tuptable; - TupleDesc spi_tupdesc = spi_tuptable->tupdesc; - int ncols = spi_tupdesc->natts; - char *rowid; - char *lastrowid = NULL; - int i, j; - int result_ncols; + SPITupleTable *spi_tuptable = SPI_tuptable; + TupleDesc spi_tupdesc = spi_tuptable->tupdesc; + int ncols = spi_tupdesc->natts; + char *rowid; + char *lastrowid = NULL; + int i, + j; + int result_ncols; /* - * The provided SQL query must always return at least three columns: + * The provided SQL query must always return at least three + * columns: * * 1. rowname the label for each row - column 1 in the final result - * 2. category the label for each value-column in the final result - * 3. value the values used to populate the value-columns - * + * 2. category the label for each value-column in the final + * result 3. value the values used to populate the + * value-columns + * * If there are more than three columns, the last two are taken as - * "category" and "values". The first column is taken as "rowname". - * Additional columns (2 thru N-2) are assumed the same for the same - * "rowname", and are copied into the result tuple from the first - * time we encounter a particular rowname. + * "category" and "values". The first column is taken as + * "rowname". Additional columns (2 thru N-2) are assumed the same + * for the same "rowname", and are copied into the result tuple + * from the first time we encounter a particular rowname. */ if (ncols < 3) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid source data SQL statement"), errdetail("The provided SQL must return 3 " \ - " columns; rowid, category, and values."))); + " columns; rowid, category, and values."))); result_ncols = (ncols - 2) + num_categories; @@ -922,7 +925,7 @@ get_crosstab_tuplestore(char *sql, errmsg("invalid return type"), errdetail("query-specified return " \ "tuple has %d columns but crosstab " \ - "returns %d", tupdesc->natts, result_ncols))); + "returns %d", tupdesc->natts, result_ncols))); /* allocate space */ values = (char **) palloc(result_ncols * sizeof(char *)); @@ -932,9 +935,9 @@ get_crosstab_tuplestore(char *sql, for (i = 0; i < proc; i++) { - HeapTuple spi_tuple; - crosstab_cat_desc *catdesc; - char *catname; + HeapTuple spi_tuple; + crosstab_cat_desc *catdesc; + char *catname; /* get the next sql result tuple */ spi_tuple = spi_tuptable->vals[i]; @@ -958,7 +961,10 @@ get_crosstab_tuplestore(char *sql, */ if (lastrowid != NULL) { - /* switch to appropriate context while storing the tuple */ + /* + * switch to appropriate context while storing the + * tuple + */ SPIcontext = MemoryContextSwitchTo(per_query_ctx); /* rowid changed, flush the previous output row */ @@ -984,7 +990,7 @@ get_crosstab_tuplestore(char *sql, crosstab_HashTableLookup(catname, catdesc); if (catdesc) - values[catdesc->attidx + ncols - 2] = + values[catdesc->attidx + ncols - 2] = SPI_getvalue(spi_tuple, spi_tupdesc, ncols); } @@ -1026,29 +1032,29 @@ get_crosstab_tuplestore(char *sql, * * keyid parent_keyid pos * ------+------------+-- - * row1 NULL 0 - * row2 row1 0 - * row3 row1 0 - * row4 row2 1 - * row5 row2 0 - * row6 row4 0 - * row7 row3 0 - * row8 row6 0 - * row9 row5 0 + * row1 NULL 0 + * row2 row1 0 + * row3 row1 0 + * row4 row2 1 + * row5 row2 0 + * row6 row4 0 + * row7 row3 0 + * row8 row6 0 + * row9 row5 0 * * * connectby(text relname, text keyid_fld, text parent_keyid_fld - * [, text orderby_fld], text start_with, int max_depth - * [, text branch_delim]) + * [, text orderby_fld], text start_with, int max_depth + * [, text branch_delim]) * connectby('foo', 'keyid', 'parent_keyid', 'pos', 'row2', 0, '~') returns: * - * keyid parent_id level branch serial + * keyid parent_id level branch serial * ------+-----------+--------+----------------------- - * row2 NULL 0 row2 1 - * row5 row2 1 row2~row5 2 - * row9 row5 2 row2~row5~row9 3 - * row4 row2 1 row2~row4 4 - * row6 row4 2 row2~row4~row6 5 + * row2 NULL 0 row2 1 + * row5 row2 1 row2~row5 2 + * row9 row5 2 row2~row5~row9 3 + * row4 row2 1 row2~row4 4 + * row6 row4 2 row2~row4~row6 5 * row8 row6 3 row2~row4~row6~row8 6 * */ @@ -1114,7 +1120,7 @@ connectby_text(PG_FUNCTION_ARGS) rsinfo->setResult = connectby(relname, key_fld, parent_key_fld, - NULL, + NULL, branch_delim, start_with, max_depth, @@ -1149,7 +1155,7 @@ connectby_text_serial(PG_FUNCTION_ARGS) char *branch_delim = NULL; bool show_branch = false; bool show_serial = true; - + ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; TupleDesc tupdesc; AttInMetadata *attinmeta; @@ -1192,7 +1198,7 @@ connectby_text_serial(PG_FUNCTION_ARGS) rsinfo->setResult = connectby(relname, key_fld, parent_key_fld, - orderby_fld, + orderby_fld, branch_delim, start_with, max_depth, @@ -1222,12 +1228,12 @@ static Tuplestorestate * connectby(char *relname, char *key_fld, char *parent_key_fld, - char *orderby_fld, + char *orderby_fld, char *branch_delim, char *start_with, int max_depth, bool show_branch, - bool show_serial, + bool show_serial, MemoryContext per_query_ctx, AttInMetadata *attinmeta) { @@ -1235,7 +1241,7 @@ connectby(char *relname, int ret; MemoryContext oldcontext; - int serial = 1; + int serial = 1; /* Connect to SPI manager */ if ((ret = SPI_connect()) < 0) @@ -1303,25 +1309,25 @@ build_tuplestore_recursively(char *key_fld, if (!show_serial) { appendStringInfo(sql, "SELECT %s, %s FROM %s WHERE %s = '%s' AND %s IS NOT NULL", - key_fld, - parent_key_fld, - relname, - parent_key_fld, - start_with, - key_fld); - serial_column=0; + key_fld, + parent_key_fld, + relname, + parent_key_fld, + start_with, + key_fld); + serial_column = 0; } else { appendStringInfo(sql, "SELECT %s, %s FROM %s WHERE %s = '%s' AND %s IS NOT NULL ORDER BY %s", - key_fld, - parent_key_fld, - relname, - parent_key_fld, - start_with, - key_fld, - orderby_fld); - serial_column=1; + key_fld, + parent_key_fld, + relname, + parent_key_fld, + start_with, + key_fld, + orderby_fld); + serial_column = 1; } /* Retrieve the desired rows */ @@ -1371,8 +1377,8 @@ build_tuplestore_recursively(char *key_fld, ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid return type"), - errdetail("Return and SQL tuple descriptions are " \ - "incompatible."))); + errdetail("Return and SQL tuple descriptions are " \ + "incompatible."))); /* root value is the one we initially start with */ values[0] = start_with; @@ -1395,7 +1401,7 @@ build_tuplestore_recursively(char *key_fld, if (show_branch) values[4] = serial_str; else - values[3] = serial_str; + values[3] = serial_str; } /* construct the tuple */ @@ -1508,11 +1514,11 @@ build_tuplestore_recursively(char *key_fld, static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial) { - int serial_column=0; + int serial_column = 0; if (show_serial) - serial_column=1; - + serial_column = 1; + /* are there the correct number of columns */ if (show_branch) { @@ -1546,7 +1552,7 @@ validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial (errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid return type"), errdetail("Third column must be type %s.", - format_type_be(INT4OID)))); + format_type_be(INT4OID)))); /* check that the type of the fourth column is TEXT if applicable */ if (show_branch && tupdesc->attrs[3]->atttypid != TEXTOID) @@ -1554,7 +1560,7 @@ validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial (errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid return type"), errdetail("Fourth column must be type %s.", - format_type_be(TEXTOID)))); + format_type_be(TEXTOID)))); /* check that the type of the fifth column is INT4 */ if (show_branch && show_serial && tupdesc->attrs[4]->atttypid != INT4OID) @@ -1565,7 +1571,7 @@ validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial if (!show_branch && show_serial && tupdesc->attrs[3]->atttypid != INT4OID) elog(ERROR, "Query-specified return tuple not valid for Connectby: " "fourth column must be type %s", format_type_be(INT4OID)); - + /* OK, the tupdesc is valid for our purposes */ } @@ -1596,7 +1602,7 @@ compatConnectbyTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc) (errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid return type"), errdetail("SQL parent key field datatype does " \ - "not match return parent key field datatype."))); + "not match return parent key field datatype."))); /* OK, the two tupdescs are compatible for our purposes */ return true; diff --git a/contrib/tsearch/morph.c b/contrib/tsearch/morph.c index 2455a72d8d..b827fd652d 100644 --- a/contrib/tsearch/morph.c +++ b/contrib/tsearch/morph.c @@ -51,7 +51,8 @@ DICT dicts[] = { #undef DICT_TABLE /* array for storing dictionary's objects (if needed) */ -void *dictobjs[lengthof(dicts)]; +void *dictobjs[ + lengthof(dicts)]; #define STOPLEXEM -2 #define BYLOCALE -1 @@ -175,7 +176,7 @@ lemmatize(char *word, int *len, int type) } else if (nd == BYLOCALE) { - continue; /* no dict for current locale */ + continue; /* no dict for current locale */ } else { diff --git a/contrib/tsearch2/common.c b/contrib/tsearch2/common.c index 917dced87f..3006218007 100644 --- a/contrib/tsearch2/common.c +++ b/contrib/tsearch2/common.c @@ -4,80 +4,99 @@ #include "ts_cfg.h" #include "dict.h" -text* -char2text(char* in) { +text * +char2text(char *in) +{ return charl2text(in, strlen(in)); } -text* charl2text(char* in, int len) { - text *out=(text*)palloc(len+VARHDRSZ); +text * +charl2text(char *in, int len) +{ + text *out = (text *) palloc(len + VARHDRSZ); + memcpy(VARDATA(out), in, len); - VARATT_SIZEP(out) = len+VARHDRSZ; + VARATT_SIZEP(out) = len + VARHDRSZ; return out; } -char -*text2char(text* in) { - char *out=palloc( VARSIZE(in) ); - memcpy(out, VARDATA(in), VARSIZE(in)-VARHDRSZ); - out[ VARSIZE(in)-VARHDRSZ ] ='\0'; +char + * +text2char(text *in) +{ + char *out = palloc(VARSIZE(in)); + + memcpy(out, VARDATA(in), VARSIZE(in) - VARHDRSZ); + out[VARSIZE(in) - VARHDRSZ] = '\0'; return out; } -char -*pnstrdup(char* in, int len) { - char *out=palloc( len+1 ); +char + * +pnstrdup(char *in, int len) +{ + char *out = palloc(len + 1); + memcpy(out, in, len); - out[len]='\0'; + out[len] = '\0'; return out; } -text -*ptextdup(text* in) { - text *out=(text*)palloc( VARSIZE(in) ); - memcpy(out,in,VARSIZE(in)); +text + * +ptextdup(text *in) +{ + text *out = (text *) palloc(VARSIZE(in)); + + memcpy(out, in, VARSIZE(in)); return out; } -text -*mtextdup(text* in) { - text *out=(text*)malloc( VARSIZE(in) ); - if ( !out ) +text + * +mtextdup(text *in) +{ + text *out = (text *) malloc(VARSIZE(in)); + + if (!out) ts_error(ERROR, "No memory"); - memcpy(out,in,VARSIZE(in)); + memcpy(out, in, VARSIZE(in)); return out; } -void -ts_error(int state, const char *format, ...) { - va_list args; - int tlen = 128, len=0; - char *buf; - +void +ts_error(int state, const char *format,...) +{ + va_list args; + int tlen = 128, + len = 0; + char *buf; + reset_cfg(); reset_dict(); reset_prs(); va_start(args, format); buf = palloc(tlen); - len = vsnprintf(buf, tlen-1, format, args); - if ( len >= tlen ) { - tlen=len+1; - buf = repalloc( buf, tlen ); - vsnprintf(buf, tlen-1, format, args); + len = vsnprintf(buf, tlen - 1, format, args); + if (len >= tlen) + { + tlen = len + 1; + buf = repalloc(buf, tlen); + vsnprintf(buf, tlen - 1, format, args); } va_end(args); - + /* ?? internal error ?? */ elog(state, "%s", buf); pfree(buf); } -int -text_cmp(text *a, text *b) { - if ( VARSIZE(a) == VARSIZE(b) ) - return strncmp( VARDATA(a), VARDATA(b), VARSIZE(a)-VARHDRSZ ); - return (int)VARSIZE(a) - (int)VARSIZE(b); +int +text_cmp(text *a, text *b) +{ + if (VARSIZE(a) == VARSIZE(b)) + return strncmp(VARDATA(a), VARDATA(b), VARSIZE(a) - VARHDRSZ); + return (int) VARSIZE(a) - (int) VARSIZE(b); } - diff --git a/contrib/tsearch2/common.h b/contrib/tsearch2/common.h index 70313fa4d2..481f00405b 100644 --- a/contrib/tsearch2/common.h +++ b/contrib/tsearch2/common.h @@ -7,18 +7,18 @@ #define PG_NARGS() (fcinfo->nargs) #endif -text* char2text(char* in); -text* charl2text(char* in, int len); -char *text2char(text* in); -char *pnstrdup(char* in, int len); -text *ptextdup(text* in); -text *mtextdup(text* in); +text *char2text(char *in); +text *charl2text(char *in, int len); +char *text2char(text *in); +char *pnstrdup(char *in, int len); +text *ptextdup(text *in); +text *mtextdup(text *in); -int text_cmp(text *a, text *b); +int text_cmp(text *a, text *b); #define NEXTVAL(x) ( (text*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) ) #define ARRNELEMS(x) ArrayGetNItems( ARR_NDIM(x), ARR_DIMS(x)) -void ts_error(int state, const char *format, ...); +void ts_error(int state, const char *format,...); #endif diff --git a/contrib/tsearch2/dict.c b/contrib/tsearch2/dict.c index 8f4cad5c41..9ceb78ffb8 100644 --- a/contrib/tsearch2/dict.c +++ b/contrib/tsearch2/dict.c @@ -1,5 +1,5 @@ -/* - * interface functions to dictionary +/* + * interface functions to dictionary * Teodor Sigaev */ #include @@ -19,260 +19,285 @@ /*********top interface**********/ -static void *plan_getdict=NULL; +static void *plan_getdict = NULL; void -init_dict(Oid id, DictInfo *dict) { - Oid arg[1]={ OIDOID }; - bool isnull; - Datum pars[1]={ ObjectIdGetDatum(id) }; - int stat; +init_dict(Oid id, DictInfo * dict) +{ + Oid arg[1] = {OIDOID}; + bool isnull; + Datum pars[1] = {ObjectIdGetDatum(id)}; + int stat; - memset(dict,0,sizeof(DictInfo)); + memset(dict, 0, sizeof(DictInfo)); SPI_connect(); - if ( !plan_getdict ) { - plan_getdict = SPI_saveplan( SPI_prepare( "select dict_init, dict_initoption, dict_lexize from pg_ts_dict where oid = $1" , 1, arg ) ); - if ( !plan_getdict ) + if (!plan_getdict) + { + plan_getdict = SPI_saveplan(SPI_prepare("select dict_init, dict_initoption, dict_lexize from pg_ts_dict where oid = $1", 1, arg)); + if (!plan_getdict) ts_error(ERROR, "SPI_prepare() failed"); } stat = SPI_execp(plan_getdict, pars, " ", 1); - if ( stat < 0 ) - ts_error (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed > 0 ) { - Datum opt; - Oid oid=InvalidOid; - oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) ); - if ( !(isnull || oid==InvalidOid) ) { - opt=SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); - dict->dictionary=(void*)DatumGetPointer(OidFunctionCall1(oid, opt)); + if (stat < 0) + ts_error(ERROR, "SPI_execp return %d", stat); + if (SPI_processed > 0) + { + Datum opt; + Oid oid = InvalidOid; + + oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); + if (!(isnull || oid == InvalidOid)) + { + opt = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); + dict->dictionary = (void *) DatumGetPointer(OidFunctionCall1(oid, opt)); } - oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull) ); - if ( isnull || oid==InvalidOid ) + oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull)); + if (isnull || oid == InvalidOid) ts_error(ERROR, "Null dict_lexize for dictonary %d", id); fmgr_info_cxt(oid, &(dict->lexize_info), TopMemoryContext); - dict->dict_id=id; - } else + dict->dict_id = id; + } + else ts_error(ERROR, "No dictionary with id %d", id); SPI_finish(); } -typedef struct { - DictInfo *last_dict; - int len; - int reallen; - DictInfo *list; +typedef struct +{ + DictInfo *last_dict; + int len; + int reallen; + DictInfo *list; SNMap name2id_map; -} DictList; +} DictList; -static DictList DList = {NULL,0,0,NULL,{0,0,NULL}}; +static DictList DList = {NULL, 0, 0, NULL, {0, 0, NULL}}; void -reset_dict(void) { - freeSNMap( &(DList.name2id_map) ); +reset_dict(void) +{ + freeSNMap(&(DList.name2id_map)); /* XXX need to free DList.list[*].dictionary */ - if ( DList.list ) + if (DList.list) free(DList.list); - memset(&DList,0,sizeof(DictList)); + memset(&DList, 0, sizeof(DictList)); } static int -comparedict(const void *a, const void *b) { - return ((DictInfo*)a)->dict_id - ((DictInfo*)b)->dict_id; +comparedict(const void *a, const void *b) +{ + return ((DictInfo *) a)->dict_id - ((DictInfo *) b)->dict_id; } DictInfo * -finddict(Oid id) { +finddict(Oid id) +{ /* last used dict */ - if ( DList.last_dict && DList.last_dict->dict_id==id ) + if (DList.last_dict && DList.last_dict->dict_id == id) return DList.last_dict; /* already used dict */ - if ( DList.len != 0 ) { - DictInfo key; - key.dict_id=id; + if (DList.len != 0) + { + DictInfo key; + + key.dict_id = id; DList.last_dict = bsearch(&key, DList.list, DList.len, sizeof(DictInfo), comparedict); - if ( DList.last_dict != NULL ) + if (DList.last_dict != NULL) return DList.last_dict; } /* last chance */ - if ( DList.len==DList.reallen ) { - DictInfo *tmp; - int reallen = ( DList.reallen ) ? 2*DList.reallen : 16; - tmp=(DictInfo*)realloc(DList.list,sizeof(DictInfo)*reallen); - if ( !tmp ) - ts_error(ERROR,"No memory"); - DList.reallen=reallen; - DList.list=tmp; + if (DList.len == DList.reallen) + { + DictInfo *tmp; + int reallen = (DList.reallen) ? 2 * DList.reallen : 16; + + tmp = (DictInfo *) realloc(DList.list, sizeof(DictInfo) * reallen); + if (!tmp) + ts_error(ERROR, "No memory"); + DList.reallen = reallen; + DList.list = tmp; } - DList.last_dict=&(DList.list[DList.len]); + DList.last_dict = &(DList.list[DList.len]); init_dict(id, DList.last_dict); DList.len++; qsort(DList.list, DList.len, sizeof(DictInfo), comparedict); - return finddict(id); /* qsort changed order!! */; + return finddict(id); /* qsort changed order!! */ ; } -static void *plan_name2id=NULL; +static void *plan_name2id = NULL; Oid -name2id_dict(text *name) { - Oid arg[1]={ TEXTOID }; - bool isnull; - Datum pars[1]={ PointerGetDatum(name) }; - int stat; - Oid id=findSNMap_t( &(DList.name2id_map), name ); +name2id_dict(text *name) +{ + Oid arg[1] = {TEXTOID}; + bool isnull; + Datum pars[1] = {PointerGetDatum(name)}; + int stat; + Oid id = findSNMap_t(&(DList.name2id_map), name); - if ( id ) + if (id) return id; - + SPI_connect(); - if ( !plan_name2id ) { - plan_name2id = SPI_saveplan( SPI_prepare( "select oid from pg_ts_dict where dict_name = $1" , 1, arg ) ); - if ( !plan_name2id ) + if (!plan_name2id) + { + plan_name2id = SPI_saveplan(SPI_prepare("select oid from pg_ts_dict where dict_name = $1", 1, arg)); + if (!plan_name2id) ts_error(ERROR, "SPI_prepare() failed"); } stat = SPI_execp(plan_name2id, pars, " ", 1); - if ( stat < 0 ) - ts_error (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed > 0 ) - id=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) ); - else + if (stat < 0) + ts_error(ERROR, "SPI_execp return %d", stat); + if (SPI_processed > 0) + id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); + else ts_error(ERROR, "No dictionary with name '%s'", text2char(name)); SPI_finish(); - addSNMap_t( &(DList.name2id_map), name, id ); + addSNMap_t(&(DList.name2id_map), name, id); return id; } /******sql-level interface******/ PG_FUNCTION_INFO_V1(lexize); -Datum lexize(PG_FUNCTION_ARGS); +Datum lexize(PG_FUNCTION_ARGS); Datum -lexize(PG_FUNCTION_ARGS) { - text *in=PG_GETARG_TEXT_P(1); - DictInfo *dict = finddict( PG_GETARG_OID(0) ); - char **res, **ptr; - Datum *da; - ArrayType *a; +lexize(PG_FUNCTION_ARGS) +{ + text *in = PG_GETARG_TEXT_P(1); + DictInfo *dict = finddict(PG_GETARG_OID(0)); + char **res, + **ptr; + Datum *da; + ArrayType *a; - ptr = res = (char**)DatumGetPointer( - FunctionCall3(&(dict->lexize_info), - PointerGetDatum(dict->dictionary), - PointerGetDatum(VARDATA(in)), - Int32GetDatum(VARSIZE(in)-VARHDRSZ) - ) - ); + ptr = res = (char **) DatumGetPointer( + FunctionCall3(&(dict->lexize_info), + PointerGetDatum(dict->dictionary), + PointerGetDatum(VARDATA(in)), + Int32GetDatum(VARSIZE(in) - VARHDRSZ) + ) + ); PG_FREE_IF_COPY(in, 1); - if ( !res ) { - if (PG_NARGS() > 2) + if (!res) + { + if (PG_NARGS() > 2) PG_RETURN_POINTER(NULL); else PG_RETURN_NULL(); } - while(*ptr) ptr++; - da = (Datum*)palloc(sizeof(Datum)*(ptr-res+1)); - ptr=res; - while(*ptr) { - da[ ptr-res ] = PointerGetDatum( char2text(*ptr) ); + while (*ptr) + ptr++; + da = (Datum *) palloc(sizeof(Datum) * (ptr - res + 1)); + ptr = res; + while (*ptr) + { + da[ptr - res] = PointerGetDatum(char2text(*ptr)); ptr++; } a = construct_array( - da, - ptr-res, - TEXTOID, - -1, - false, - 'i' - ); + da, + ptr - res, + TEXTOID, + -1, + false, + 'i' + ); - ptr=res; - while(*ptr) { - pfree( DatumGetPointer(da[ ptr-res ]) ); - pfree( *ptr ); + ptr = res; + while (*ptr) + { + pfree(DatumGetPointer(da[ptr - res])); + pfree(*ptr); ptr++; } pfree(res); pfree(da); - - PG_RETURN_POINTER(a); + + PG_RETURN_POINTER(a); } PG_FUNCTION_INFO_V1(lexize_byname); -Datum lexize_byname(PG_FUNCTION_ARGS); -Datum -lexize_byname(PG_FUNCTION_ARGS) { - text *dictname=PG_GETARG_TEXT_P(0); - Datum res; +Datum lexize_byname(PG_FUNCTION_ARGS); +Datum +lexize_byname(PG_FUNCTION_ARGS) +{ + text *dictname = PG_GETARG_TEXT_P(0); + Datum res; strdup("simple"); - res=DirectFunctionCall3( - lexize, - ObjectIdGetDatum(name2id_dict(dictname)), - PG_GETARG_DATUM(1), - (Datum)0 - ); + res = DirectFunctionCall3( + lexize, + ObjectIdGetDatum(name2id_dict(dictname)), + PG_GETARG_DATUM(1), + (Datum) 0 + ); PG_FREE_IF_COPY(dictname, 0); - if (res) - PG_RETURN_DATUM(res); - else + if (res) + PG_RETURN_DATUM(res); + else PG_RETURN_NULL(); } -static Oid currect_dictionary_id=0; +static Oid currect_dictionary_id = 0; PG_FUNCTION_INFO_V1(set_curdict); -Datum set_curdict(PG_FUNCTION_ARGS); +Datum set_curdict(PG_FUNCTION_ARGS); Datum -set_curdict(PG_FUNCTION_ARGS) { +set_curdict(PG_FUNCTION_ARGS) +{ finddict(PG_GETARG_OID(0)); - currect_dictionary_id=PG_GETARG_OID(0); + currect_dictionary_id = PG_GETARG_OID(0); PG_RETURN_VOID(); } PG_FUNCTION_INFO_V1(set_curdict_byname); -Datum set_curdict_byname(PG_FUNCTION_ARGS); +Datum set_curdict_byname(PG_FUNCTION_ARGS); Datum -set_curdict_byname(PG_FUNCTION_ARGS) { - text *dictname=PG_GETARG_TEXT_P(0); +set_curdict_byname(PG_FUNCTION_ARGS) +{ + text *dictname = PG_GETARG_TEXT_P(0); DirectFunctionCall1( - set_curdict, - ObjectIdGetDatum( name2id_dict(dictname) ) - ); + set_curdict, + ObjectIdGetDatum(name2id_dict(dictname)) + ); PG_FREE_IF_COPY(dictname, 0); PG_RETURN_VOID(); } PG_FUNCTION_INFO_V1(lexize_bycurrent); -Datum lexize_bycurrent(PG_FUNCTION_ARGS); -Datum -lexize_bycurrent(PG_FUNCTION_ARGS) { - Datum res; - if ( currect_dictionary_id == 0 ) +Datum lexize_bycurrent(PG_FUNCTION_ARGS); +Datum +lexize_bycurrent(PG_FUNCTION_ARGS) +{ + Datum res; + + if (currect_dictionary_id == 0) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("no currect dictionary"), errhint("Execute select set_curdict()."))); res = DirectFunctionCall3( - lexize, - ObjectIdGetDatum(currect_dictionary_id), - PG_GETARG_DATUM(0), - (Datum)0 - ); - if (res) + lexize, + ObjectIdGetDatum(currect_dictionary_id), + PG_GETARG_DATUM(0), + (Datum) 0 + ); + if (res) PG_RETURN_DATUM(res); - else + else PG_RETURN_NULL(); } - - diff --git a/contrib/tsearch2/dict.h b/contrib/tsearch2/dict.h index bbbbfc47a5..86ea42263e 100644 --- a/contrib/tsearch2/dict.h +++ b/contrib/tsearch2/dict.h @@ -3,36 +3,39 @@ #include "postgres.h" #include "fmgr.h" -typedef struct { - int len; - char **stop; - char* (*wordop)(char*); -} StopList; +typedef struct +{ + int len; + char **stop; + char *(*wordop) (char *); +} StopList; -void sortstoplist(StopList *s); -void freestoplist(StopList *s); -void readstoplist(text *in, StopList *s); -bool searchstoplist(StopList *s, char *key); -char* lowerstr(char *str); +void sortstoplist(StopList * s); +void freestoplist(StopList * s); +void readstoplist(text *in, StopList * s); +bool searchstoplist(StopList * s, char *key); +char *lowerstr(char *str); -typedef struct { - Oid dict_id; - FmgrInfo lexize_info; - void *dictionary; -} DictInfo; +typedef struct +{ + Oid dict_id; + FmgrInfo lexize_info; + void *dictionary; +} DictInfo; -void init_dict(Oid id, DictInfo *dict); -DictInfo* finddict(Oid id); -Oid name2id_dict(text *name); -void reset_dict(void); +void init_dict(Oid id, DictInfo * dict); +DictInfo *finddict(Oid id); +Oid name2id_dict(text *name); +void reset_dict(void); /* simple parser of cfg string */ -typedef struct { - char *key; - char *value; -} Map; +typedef struct +{ + char *key; + char *value; +} Map; -void parse_cfgdict(text *in, Map **m); +void parse_cfgdict(text *in, Map ** m); #endif diff --git a/contrib/tsearch2/dict_ex.c b/contrib/tsearch2/dict_ex.c index ead9610687..a8fb20453b 100644 --- a/contrib/tsearch2/dict_ex.c +++ b/contrib/tsearch2/dict_ex.c @@ -1,5 +1,5 @@ -/* - * example of dictionary +/* + * example of dictionary * Teodor Sigaev */ #include @@ -11,30 +11,35 @@ #include "dict.h" #include "common.h" -typedef struct { +typedef struct +{ StopList stoplist; -} DictExample; +} DictExample; PG_FUNCTION_INFO_V1(dex_init); -Datum dex_init(PG_FUNCTION_ARGS); +Datum dex_init(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(dex_lexize); -Datum dex_lexize(PG_FUNCTION_ARGS); +Datum dex_lexize(PG_FUNCTION_ARGS); -Datum -dex_init(PG_FUNCTION_ARGS) { - DictExample *d = (DictExample*)malloc( sizeof(DictExample) ); +Datum +dex_init(PG_FUNCTION_ARGS) +{ + DictExample *d = (DictExample *) malloc(sizeof(DictExample)); - if ( !d ) + if (!d) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - memset(d,0,sizeof(DictExample)); + memset(d, 0, sizeof(DictExample)); + + d->stoplist.wordop = lowerstr; + + if (!PG_ARGISNULL(0) && PG_GETARG_POINTER(0) != NULL) + { + text *in = PG_GETARG_TEXT_P(0); - d->stoplist.wordop=lowerstr; - - if ( !PG_ARGISNULL(0) && PG_GETARG_POINTER(0)!=NULL ) { - text *in = PG_GETARG_TEXT_P(0); readstoplist(in, &(d->stoplist)); sortstoplist(&(d->stoplist)); PG_FREE_IF_COPY(in, 0); @@ -44,18 +49,21 @@ dex_init(PG_FUNCTION_ARGS) { } Datum -dex_lexize(PG_FUNCTION_ARGS) { - DictExample *d = (DictExample*)PG_GETARG_POINTER(0); - char *in = (char*)PG_GETARG_POINTER(1); - char *txt = pnstrdup(in, PG_GETARG_INT32(2)); - char **res=palloc(sizeof(char*)*2); +dex_lexize(PG_FUNCTION_ARGS) +{ + DictExample *d = (DictExample *) PG_GETARG_POINTER(0); + char *in = (char *) PG_GETARG_POINTER(1); + char *txt = pnstrdup(in, PG_GETARG_INT32(2)); + char **res = palloc(sizeof(char *) * 2); - if ( *txt=='\0' || searchstoplist(&(d->stoplist),txt) ) { + if (*txt == '\0' || searchstoplist(&(d->stoplist), txt)) + { pfree(txt); - res[0]=NULL; - } else - res[0]=txt; - res[1]=NULL; + res[0] = NULL; + } + else + res[0] = txt; + res[1] = NULL; PG_RETURN_POINTER(res); } diff --git a/contrib/tsearch2/dict_ispell.c b/contrib/tsearch2/dict_ispell.c index c053adfad0..e3a100fa01 100644 --- a/contrib/tsearch2/dict_ispell.c +++ b/contrib/tsearch2/dict_ispell.c @@ -1,4 +1,4 @@ -/* +/* * ISpell interface * Teodor Sigaev */ @@ -12,96 +12,117 @@ #include "common.h" #include "ispell/spell.h" -typedef struct { +typedef struct +{ StopList stoplist; IspellDict obj; -} DictISpell; +} DictISpell; PG_FUNCTION_INFO_V1(spell_init); -Datum spell_init(PG_FUNCTION_ARGS); +Datum spell_init(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(spell_lexize); -Datum spell_lexize(PG_FUNCTION_ARGS); +Datum spell_lexize(PG_FUNCTION_ARGS); static void -freeDictISpell(DictISpell *d) { +freeDictISpell(DictISpell * d) +{ FreeIspell(&(d->obj)); freestoplist(&(d->stoplist)); free(d); } -Datum -spell_init(PG_FUNCTION_ARGS) { - DictISpell *d; - Map *cfg, *pcfg; - text *in; - bool affloaded=false, dictloaded=false, stoploaded=false; +Datum +spell_init(PG_FUNCTION_ARGS) +{ + DictISpell *d; + Map *cfg, + *pcfg; + text *in; + bool affloaded = false, + dictloaded = false, + stoploaded = false; - if ( PG_ARGISNULL(0) || PG_GETARG_POINTER(0)==NULL ) + if (PG_ARGISNULL(0) || PG_GETARG_POINTER(0) == NULL) ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("ISpell confguration error"))); - - d = (DictISpell*)malloc( sizeof(DictISpell) ); - if ( !d ) + + d = (DictISpell *) malloc(sizeof(DictISpell)); + if (!d) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - memset(d,0,sizeof(DictISpell)); - d->stoplist.wordop=lowerstr; + memset(d, 0, sizeof(DictISpell)); + d->stoplist.wordop = lowerstr; in = PG_GETARG_TEXT_P(0); - parse_cfgdict(in,&cfg); + parse_cfgdict(in, &cfg); PG_FREE_IF_COPY(in, 0); - pcfg=cfg; - while(pcfg->key) { - if ( strcasecmp("DictFile", pcfg->key) == 0 ) { - if ( dictloaded ) { + pcfg = cfg; + while (pcfg->key) + { + if (strcasecmp("DictFile", pcfg->key) == 0) + { + if (dictloaded) + { freeDictISpell(d); ereport(ERROR, - (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("dictionary already loaded"))); + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("dictionary already loaded"))); } - if ( ImportDictionary(&(d->obj), pcfg->value) ) { + if (ImportDictionary(&(d->obj), pcfg->value)) + { freeDictISpell(d); ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("could not load dictionary file \"%s\"", pcfg->value))); } - dictloaded=true; - } else if ( strcasecmp("AffFile", pcfg->key) == 0 ) { - if ( affloaded ) { + dictloaded = true; + } + else if (strcasecmp("AffFile", pcfg->key) == 0) + { + if (affloaded) + { freeDictISpell(d); ereport(ERROR, - (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("affixes already loaded"))); + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("affixes already loaded"))); } - if ( ImportAffixes(&(d->obj), pcfg->value) ) { + if (ImportAffixes(&(d->obj), pcfg->value)) + { freeDictISpell(d); ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("could not load affix file \"%s\"", pcfg->value))); } - affloaded=true; - } else if ( strcasecmp("StopFile", pcfg->key) == 0 ) { - text *tmp=char2text(pcfg->value); - if ( stoploaded ) { + affloaded = true; + } + else if (strcasecmp("StopFile", pcfg->key) == 0) + { + text *tmp = char2text(pcfg->value); + + if (stoploaded) + { freeDictISpell(d); ereport(ERROR, - (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("stop words already loaded"))); + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("stop words already loaded"))); } readstoplist(tmp, &(d->stoplist)); sortstoplist(&(d->stoplist)); pfree(tmp); - stoploaded=true; - } else { + stoploaded = true; + } + else + { freeDictISpell(d); ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("unrecognized option: %s => %s", - pcfg->key, pcfg->value))); + pcfg->key, pcfg->value))); } pfree(pcfg->key); pfree(pcfg->value); @@ -109,15 +130,20 @@ spell_init(PG_FUNCTION_ARGS) { } pfree(cfg); - if ( affloaded && dictloaded ) { + if (affloaded && dictloaded) + { SortDictionary(&(d->obj)); SortAffixes(&(d->obj)); - } else if ( !affloaded ) { + } + else if (!affloaded) + { freeDictISpell(d); ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("no affixes"))); - } else { + } + else + { freeDictISpell(d); ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), @@ -128,37 +154,43 @@ spell_init(PG_FUNCTION_ARGS) { } Datum -spell_lexize(PG_FUNCTION_ARGS) { - DictISpell *d = (DictISpell*)PG_GETARG_POINTER(0); - char *in = (char*)PG_GETARG_POINTER(1); - char *txt; - char **res; - char **ptr, **cptr; +spell_lexize(PG_FUNCTION_ARGS) +{ + DictISpell *d = (DictISpell *) PG_GETARG_POINTER(0); + char *in = (char *) PG_GETARG_POINTER(1); + char *txt; + char **res; + char **ptr, + **cptr; - if ( !PG_GETARG_INT32(2) ) + if (!PG_GETARG_INT32(2)) PG_RETURN_POINTER(NULL); - res=palloc(sizeof(char*)*2); + res = palloc(sizeof(char *) * 2); txt = pnstrdup(in, PG_GETARG_INT32(2)); - res=NormalizeWord(&(d->obj), txt); + res = NormalizeWord(&(d->obj), txt); pfree(txt); - if ( res==NULL ) + if (res == NULL) PG_RETURN_POINTER(NULL); - ptr=cptr=res; - while(*ptr) { - if ( searchstoplist(&(d->stoplist),*ptr) ) { + ptr = cptr = res; + while (*ptr) + { + if (searchstoplist(&(d->stoplist), *ptr)) + { pfree(*ptr); - *ptr=NULL; + *ptr = NULL; + ptr++; + } + else + { + *cptr = *ptr; + cptr++; ptr++; - } else { - *cptr=*ptr; - cptr++; ptr++; } } - *cptr=NULL; + *cptr = NULL; PG_RETURN_POINTER(res); } - diff --git a/contrib/tsearch2/dict_snowball.c b/contrib/tsearch2/dict_snowball.c index 103d87d7f9..51dba04449 100644 --- a/contrib/tsearch2/dict_snowball.c +++ b/contrib/tsearch2/dict_snowball.c @@ -1,6 +1,6 @@ -/* +/* * example of Snowball dictionary - * http://snowball.tartarus.org/ + * http://snowball.tartarus.org/ * Teodor Sigaev */ #include @@ -14,103 +14,118 @@ #include "snowball/english_stem.h" #include "snowball/russian_stem.h" -typedef struct { +typedef struct +{ struct SN_env *z; StopList stoplist; - int (*stem)(struct SN_env * z); -} DictSnowball; + int (*stem) (struct SN_env * z); +} DictSnowball; PG_FUNCTION_INFO_V1(snb_en_init); -Datum snb_en_init(PG_FUNCTION_ARGS); +Datum snb_en_init(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(snb_ru_init); -Datum snb_ru_init(PG_FUNCTION_ARGS); +Datum snb_ru_init(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(snb_lexize); -Datum snb_lexize(PG_FUNCTION_ARGS); +Datum snb_lexize(PG_FUNCTION_ARGS); -Datum -snb_en_init(PG_FUNCTION_ARGS) { - DictSnowball *d = (DictSnowball*)malloc( sizeof(DictSnowball) ); +Datum +snb_en_init(PG_FUNCTION_ARGS) +{ + DictSnowball *d = (DictSnowball *) malloc(sizeof(DictSnowball)); - if ( !d ) + if (!d) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - memset(d,0,sizeof(DictSnowball)); - d->stoplist.wordop=lowerstr; - - if ( !PG_ARGISNULL(0) && PG_GETARG_POINTER(0)!=NULL ) { - text *in = PG_GETARG_TEXT_P(0); + memset(d, 0, sizeof(DictSnowball)); + d->stoplist.wordop = lowerstr; + + if (!PG_ARGISNULL(0) && PG_GETARG_POINTER(0) != NULL) + { + text *in = PG_GETARG_TEXT_P(0); + readstoplist(in, &(d->stoplist)); sortstoplist(&(d->stoplist)); PG_FREE_IF_COPY(in, 0); } d->z = english_create_env(); - if (!d->z) { + if (!d->z) + { freestoplist(&(d->stoplist)); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - d->stem=english_stem; + d->stem = english_stem; PG_RETURN_POINTER(d); } -Datum -snb_ru_init(PG_FUNCTION_ARGS) { - DictSnowball *d = (DictSnowball*)malloc( sizeof(DictSnowball) ); +Datum +snb_ru_init(PG_FUNCTION_ARGS) +{ + DictSnowball *d = (DictSnowball *) malloc(sizeof(DictSnowball)); - if ( !d ) + if (!d) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - memset(d,0,sizeof(DictSnowball)); - d->stoplist.wordop=lowerstr; - - if ( !PG_ARGISNULL(0) && PG_GETARG_POINTER(0)!=NULL ) { - text *in = PG_GETARG_TEXT_P(0); + memset(d, 0, sizeof(DictSnowball)); + d->stoplist.wordop = lowerstr; + + if (!PG_ARGISNULL(0) && PG_GETARG_POINTER(0) != NULL) + { + text *in = PG_GETARG_TEXT_P(0); + readstoplist(in, &(d->stoplist)); sortstoplist(&(d->stoplist)); PG_FREE_IF_COPY(in, 0); } d->z = russian_create_env(); - if (!d->z) { + if (!d->z) + { freestoplist(&(d->stoplist)); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - d->stem=russian_stem; + d->stem = russian_stem; PG_RETURN_POINTER(d); } Datum -snb_lexize(PG_FUNCTION_ARGS) { - DictSnowball *d = (DictSnowball*)PG_GETARG_POINTER(0); - char *in = (char*)PG_GETARG_POINTER(1); - char *txt = pnstrdup(in, PG_GETARG_INT32(2)); - char **res=palloc(sizeof(char*)*2); +snb_lexize(PG_FUNCTION_ARGS) +{ + DictSnowball *d = (DictSnowball *) PG_GETARG_POINTER(0); + char *in = (char *) PG_GETARG_POINTER(1); + char *txt = pnstrdup(in, PG_GETARG_INT32(2)); + char **res = palloc(sizeof(char *) * 2); - if ( *txt=='\0' || searchstoplist(&(d->stoplist),txt) ) { + if (*txt == '\0' || searchstoplist(&(d->stoplist), txt)) + { pfree(txt); - res[0]=NULL; - } else { - SN_set_current(d->z, strlen(txt), txt); - (d->stem)(d->z); - if ( d->z->p && d->z->l ) { - txt=repalloc(txt, d->z->l+1); - memcpy( txt, d->z->p, d->z->l); - txt[d->z->l]='\0'; - } - res[0]=txt; + res[0] = NULL; } - res[1]=NULL; + else + { + SN_set_current(d->z, strlen(txt), txt); + (d->stem) (d->z); + if (d->z->p && d->z->l) + { + txt = repalloc(txt, d->z->l + 1); + memcpy(txt, d->z->p, d->z->l); + txt[d->z->l] = '\0'; + } + res[0] = txt; + } + res[1] = NULL; PG_RETURN_POINTER(res); } - diff --git a/contrib/tsearch2/dict_syn.c b/contrib/tsearch2/dict_syn.c index 34f74cf0ff..8364223be4 100644 --- a/contrib/tsearch2/dict_syn.c +++ b/contrib/tsearch2/dict_syn.c @@ -1,4 +1,4 @@ -/* +/* * ISpell interface * Teodor Sigaev */ @@ -13,93 +13,106 @@ #include "common.h" #define SYNBUFLEN 4096 -typedef struct { - char *in; - char *out; -} Syn; +typedef struct +{ + char *in; + char *out; +} Syn; -typedef struct { - int len; - Syn *syn; -} DictSyn; +typedef struct +{ + int len; + Syn *syn; +} DictSyn; PG_FUNCTION_INFO_V1(syn_init); -Datum syn_init(PG_FUNCTION_ARGS); +Datum syn_init(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(syn_lexize); -Datum syn_lexize(PG_FUNCTION_ARGS); +Datum syn_lexize(PG_FUNCTION_ARGS); static char * -findwrd(char *in, char **end) { - char *start; +findwrd(char *in, char **end) +{ + char *start; - *end=NULL; - while(*in && isspace(*in)) + *end = NULL; + while (*in && isspace(*in)) in++; - if ( !in ) + if (!in) return NULL; - start=in; + start = in; - while(*in && !isspace(*in)) + while (*in && !isspace(*in)) in++; - *end=in; + *end = in; return start; } static int -compareSyn(const void *a, const void *b) { - return strcmp( ((Syn*)a)->in, ((Syn*)b)->in ); +compareSyn(const void *a, const void *b) +{ + return strcmp(((Syn *) a)->in, ((Syn *) b)->in); } -Datum -syn_init(PG_FUNCTION_ARGS) { - text *in; - DictSyn *d; - int cur=0; - FILE *fin; - char *filename; - char buf[SYNBUFLEN]; - char *starti,*starto,*end=NULL; - int slen; +Datum +syn_init(PG_FUNCTION_ARGS) +{ + text *in; + DictSyn *d; + int cur = 0; + FILE *fin; + char *filename; + char buf[SYNBUFLEN]; + char *starti, + *starto, + *end = NULL; + int slen; - if ( PG_ARGISNULL(0) || PG_GETARG_POINTER(0)==NULL ) + if (PG_ARGISNULL(0) || PG_GETARG_POINTER(0) == NULL) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("NULL config"))); in = PG_GETARG_TEXT_P(0); - if ( VARSIZE(in) - VARHDRSZ == 0 ) + if (VARSIZE(in) - VARHDRSZ == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("VOID config"))); - filename=text2char(in); + filename = text2char(in); PG_FREE_IF_COPY(in, 0); - if ( (fin=fopen(filename,"r")) == NULL ) + if ((fin = fopen(filename, "r")) == NULL) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open file \"%s\": %m", - filename))); + filename))); - d = (DictSyn*)malloc( sizeof(DictSyn) ); - if ( !d ) { + d = (DictSyn *) malloc(sizeof(DictSyn)); + if (!d) + { fclose(fin); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - memset(d,0,sizeof(DictSyn)); + memset(d, 0, sizeof(DictSyn)); - while( fgets(buf,SYNBUFLEN,fin) ) { - slen = strlen(buf)-1; + while (fgets(buf, SYNBUFLEN, fin)) + { + slen = strlen(buf) - 1; buf[slen] = '\0'; - if ( *buf=='\0' ) continue; - if (cur==d->len) { - d->len = (d->len) ? 2*d->len : 16; - d->syn=(Syn*)realloc( d->syn, sizeof(Syn)*d->len ); - if ( !d->syn ) { + if (*buf == '\0') + continue; + if (cur == d->len) + { + d->len = (d->len) ? 2 * d->len : 16; + d->syn = (Syn *) realloc(d->syn, sizeof(Syn) * d->len); + if (!d->syn) + { fclose(fin); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), @@ -107,64 +120,66 @@ syn_init(PG_FUNCTION_ARGS) { } } - starti=findwrd(buf,&end); - if ( !starti ) + starti = findwrd(buf, &end); + if (!starti) continue; - *end='\0'; - if ( end >= buf+slen ) + *end = '\0'; + if (end >= buf + slen) continue; - starto= findwrd(end+1, &end); - if ( !starto ) + starto = findwrd(end + 1, &end); + if (!starto) continue; - *end='\0'; + *end = '\0'; - d->syn[cur].in=strdup(lowerstr(starti)); - d->syn[cur].out=strdup(lowerstr(starto)); - if ( !(d->syn[cur].in && d->syn[cur].out) ) { + d->syn[cur].in = strdup(lowerstr(starti)); + d->syn[cur].out = strdup(lowerstr(starto)); + if (!(d->syn[cur].in && d->syn[cur].out)) + { fclose(fin); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - cur++; + cur++; } - - fclose(fin); - - d->len=cur; - if ( cur>1 ) - qsort(d->syn, d->len, sizeof(Syn), compareSyn); + + fclose(fin); + + d->len = cur; + if (cur > 1) + qsort(d->syn, d->len, sizeof(Syn), compareSyn); pfree(filename); - PG_RETURN_POINTER(d); + PG_RETURN_POINTER(d); } Datum -syn_lexize(PG_FUNCTION_ARGS) { - DictSyn *d = (DictSyn*)PG_GETARG_POINTER(0); - char *in = (char*)PG_GETARG_POINTER(1); - Syn key,*found; - char **res=NULL; +syn_lexize(PG_FUNCTION_ARGS) +{ + DictSyn *d = (DictSyn *) PG_GETARG_POINTER(0); + char *in = (char *) PG_GETARG_POINTER(1); + Syn key, + *found; + char **res = NULL; - if ( !PG_GETARG_INT32(2) ) + if (!PG_GETARG_INT32(2)) PG_RETURN_POINTER(NULL); - key.out=NULL; - key.in=lowerstr(pnstrdup(in, PG_GETARG_INT32(2))); + key.out = NULL; + key.in = lowerstr(pnstrdup(in, PG_GETARG_INT32(2))); - found=(Syn*)bsearch(&key, d->syn, d->len, sizeof(Syn), compareSyn); + found = (Syn *) bsearch(&key, d->syn, d->len, sizeof(Syn), compareSyn); pfree(key.in); - if ( !found ) + if (!found) PG_RETURN_POINTER(NULL); - res=palloc(sizeof(char*)*2); + res = palloc(sizeof(char *) * 2); - res[0]=pstrdup(found->out); - res[1]=NULL; + res[0] = pstrdup(found->out); + res[1] = NULL; - PG_RETURN_POINTER(res); + PG_RETURN_POINTER(res); } - diff --git a/contrib/tsearch2/ispell/spell.c b/contrib/tsearch2/ispell/spell.c index c5ab260149..45786cca65 100644 --- a/contrib/tsearch2/ispell/spell.c +++ b/contrib/tsearch2/ispell/spell.c @@ -9,518 +9,648 @@ #define MAXNORMLEN 56 -#define STRNCASECMP(x,y) (strncasecmp(x,y,strlen(y))) +#define STRNCASECMP(x,y) (strncasecmp(x,y,strlen(y))) -static int cmpspell(const void *s1,const void *s2){ - return(strcmp(((const SPELL*)s1)->word,((const SPELL*)s2)->word)); +static int +cmpspell(const void *s1, const void *s2) +{ + return (strcmp(((const SPELL *) s1)->word, ((const SPELL *) s2)->word)); } -static void -strlower( char * str ) { - unsigned char *ptr = (unsigned char *)str; - while ( *ptr ) { - *ptr = tolower( *ptr ); +static void +strlower(char *str) +{ + unsigned char *ptr = (unsigned char *) str; + + while (*ptr) + { + *ptr = tolower(*ptr); ptr++; } } /* backward string compaire for suffix tree operations */ -static int -strbcmp(const char *s1, const char *s2) { - int l1 = strlen(s1)-1, l2 = strlen(s2)-1; - while (l1 >= 0 && l2 >= 0) { - if (s1[l1] < s2[l2]) return -1; - if (s1[l1] > s2[l2]) return 1; - l1--; l2--; +static int +strbcmp(const char *s1, const char *s2) +{ + int l1 = strlen(s1) - 1, + l2 = strlen(s2) - 1; + + while (l1 >= 0 && l2 >= 0) + { + if (s1[l1] < s2[l2]) + return -1; + if (s1[l1] > s2[l2]) + return 1; + l1--; + l2--; } - if (l1 < l2) return -1; - if (l1 > l2) return 1; + if (l1 < l2) + return -1; + if (l1 > l2) + return 1; return 0; } -static int -strbncmp(const char *s1, const char *s2, size_t count) { - int l1 = strlen(s1) - 1, l2 = strlen(s2) - 1, l = count; - while (l1 >= 0 && l2 >= 0 && l > 0) { - if (s1[l1] < s2[l2]) return -1; - if (s1[l1] > s2[l2]) return 1; +static int +strbncmp(const char *s1, const char *s2, size_t count) +{ + int l1 = strlen(s1) - 1, + l2 = strlen(s2) - 1, + l = count; + + while (l1 >= 0 && l2 >= 0 && l > 0) + { + if (s1[l1] < s2[l2]) + return -1; + if (s1[l1] > s2[l2]) + return 1; l1--; l2--; l--; } - if (l == 0) return 0; - if (l1 < l2) return -1; - if (l1 > l2) return 1; + if (l == 0) + return 0; + if (l1 < l2) + return -1; + if (l1 > l2) + return 1; return 0; } -static int -cmpaffix(const void *s1,const void *s2){ - if (((const AFFIX*)s1)->type < ((const AFFIX*)s2)->type) return -1; - if (((const AFFIX*)s1)->type > ((const AFFIX*)s2)->type) return 1; - if (((const AFFIX*)s1)->type == 'p') - return(strcmp(((const AFFIX*)s1)->repl,((const AFFIX*)s2)->repl)); - else - return(strbcmp(((const AFFIX*)s1)->repl,((const AFFIX*)s2)->repl)); +static int +cmpaffix(const void *s1, const void *s2) +{ + if (((const AFFIX *) s1)->type < ((const AFFIX *) s2)->type) + return -1; + if (((const AFFIX *) s1)->type > ((const AFFIX *) s2)->type) + return 1; + if (((const AFFIX *) s1)->type == 'p') + return (strcmp(((const AFFIX *) s1)->repl, ((const AFFIX *) s2)->repl)); + else + return (strbcmp(((const AFFIX *) s1)->repl, ((const AFFIX *) s2)->repl)); } -int -AddSpell(IspellDict * Conf,const char * word,const char *flag){ - if(Conf->nspell>=Conf->mspell){ - if(Conf->mspell){ - Conf->mspell+=1024*20; - Conf->Spell=(SPELL *)realloc(Conf->Spell,Conf->mspell*sizeof(SPELL)); - }else{ - Conf->mspell=1024*20; - Conf->Spell=(SPELL *)malloc(Conf->mspell*sizeof(SPELL)); +int +AddSpell(IspellDict * Conf, const char *word, const char *flag) +{ + if (Conf->nspell >= Conf->mspell) + { + if (Conf->mspell) + { + Conf->mspell += 1024 * 20; + Conf->Spell = (SPELL *) realloc(Conf->Spell, Conf->mspell * sizeof(SPELL)); } - if ( Conf->Spell == NULL ) + else + { + Conf->mspell = 1024 * 20; + Conf->Spell = (SPELL *) malloc(Conf->mspell * sizeof(SPELL)); + } + if (Conf->Spell == NULL) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - Conf->Spell[Conf->nspell].word=strdup(word); - if ( !Conf->Spell[Conf->nspell].word ) + Conf->Spell[Conf->nspell].word = strdup(word); + if (!Conf->Spell[Conf->nspell].word) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - strncpy(Conf->Spell[Conf->nspell].flag,flag,10); + strncpy(Conf->Spell[Conf->nspell].flag, flag, 10); Conf->nspell++; - return(0); + return (0); } -int -ImportDictionary(IspellDict * Conf,const char *filename){ - unsigned char str[BUFSIZ]; - FILE *dict; +int +ImportDictionary(IspellDict * Conf, const char *filename) +{ + unsigned char str[BUFSIZ]; + FILE *dict; - if(!(dict=fopen(filename,"r")))return(1); - while(fgets(str,sizeof(str),dict)){ + if (!(dict = fopen(filename, "r"))) + return (1); + while (fgets(str, sizeof(str), dict)) + { unsigned char *s; const unsigned char *flag; - flag = NULL; - if((s=strchr(str,'/'))){ - *s=0; - s++;flag=s; - while(*s){ - if (((*s>='A')&&(*s<='Z'))||((*s>='a')&&(*s<='z'))) + flag = NULL; + if ((s = strchr(str, '/'))) + { + *s = 0; + s++; + flag = s; + while (*s) + { + if (((*s >= 'A') && (*s <= 'Z')) || ((*s >= 'a') && (*s <= 'z'))) s++; - else { - *s=0; + else + { + *s = 0; break; } } - }else{ - flag=""; } + else + flag = ""; strlower(str); /* Dont load words if first letter is not required */ /* It allows to optimize loading at search time */ - s=str; - while(*s){ - if(*s=='\r')*s=0; - if(*s=='\n')*s=0; + s = str; + while (*s) + { + if (*s == '\r') + *s = 0; + if (*s == '\n') + *s = 0; s++; } - AddSpell(Conf,str,flag); + AddSpell(Conf, str, flag); } fclose(dict); - return(0); + return (0); } -static SPELL * -FindWord(IspellDict * Conf, const char *word, int affixflag) { - int l,c,r,resc,resl,resr, i; +static SPELL * +FindWord(IspellDict * Conf, const char *word, int affixflag) +{ + int l, + c, + r, + resc, + resl, + resr, + i; - i = (int)(*word) & 255; + i = (int) (*word) & 255; l = Conf->SpellTree.Left[i]; r = Conf->SpellTree.Right[i]; - if (l == -1) return (NULL); - while(l<=r){ + if (l == -1) + return (NULL); + while (l <= r) + { c = (l + r) >> 1; resc = strcmp(Conf->Spell[c].word, word); - if( (resc == 0) && - ((affixflag == 0) || (strchr(Conf->Spell[c].flag, affixflag) != NULL)) ) { - return(&Conf->Spell[c]); - } + if ((resc == 0) && + ((affixflag == 0) || (strchr(Conf->Spell[c].flag, affixflag) != NULL))) + return (&Conf->Spell[c]); resl = strcmp(Conf->Spell[l].word, word); - if( (resl == 0) && - ((affixflag == 0) || (strchr(Conf->Spell[l].flag, affixflag) != NULL)) ) { - return(&Conf->Spell[l]); - } + if ((resl == 0) && + ((affixflag == 0) || (strchr(Conf->Spell[l].flag, affixflag) != NULL))) + return (&Conf->Spell[l]); resr = strcmp(Conf->Spell[r].word, word); - if( (resr == 0) && - ((affixflag == 0) || (strchr(Conf->Spell[r].flag, affixflag) != NULL)) ) { - return(&Conf->Spell[r]); - } - if(resc < 0){ + if ((resr == 0) && + ((affixflag == 0) || (strchr(Conf->Spell[r].flag, affixflag) != NULL))) + return (&Conf->Spell[r]); + if (resc < 0) + { l = c + 1; r--; - } else if(resc > 0){ + } + else if (resc > 0) + { r = c - 1; l++; - } else { + } + else + { l++; r--; } } - return(NULL); + return (NULL); } -int -AddAffix(IspellDict * Conf,int flag,const char *mask,const char *find,const char *repl,int type) { - if(Conf->naffixes>=Conf->maffixes){ - if(Conf->maffixes){ - Conf->maffixes+=16; - Conf->Affix = (AFFIX*)realloc((void*)Conf->Affix,Conf->maffixes*sizeof(AFFIX)); - }else{ - Conf->maffixes=16; - Conf->Affix = (AFFIX*)malloc(Conf->maffixes * sizeof(AFFIX)); +int +AddAffix(IspellDict * Conf, int flag, const char *mask, const char *find, const char *repl, int type) +{ + if (Conf->naffixes >= Conf->maffixes) + { + if (Conf->maffixes) + { + Conf->maffixes += 16; + Conf->Affix = (AFFIX *) realloc((void *) Conf->Affix, Conf->maffixes * sizeof(AFFIX)); } - if ( Conf->Affix == NULL ) + else + { + Conf->maffixes = 16; + Conf->Affix = (AFFIX *) malloc(Conf->maffixes * sizeof(AFFIX)); + } + if (Conf->Affix == NULL) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - if (type=='s') { - sprintf(Conf->Affix[Conf->naffixes].mask,"%s$",mask); - } else { - sprintf(Conf->Affix[Conf->naffixes].mask,"^%s",mask); - } + if (type == 's') + sprintf(Conf->Affix[Conf->naffixes].mask, "%s$", mask); + else + sprintf(Conf->Affix[Conf->naffixes].mask, "^%s", mask); Conf->Affix[Conf->naffixes].compile = 1; - Conf->Affix[Conf->naffixes].flag=flag; - Conf->Affix[Conf->naffixes].type=type; - - strcpy(Conf->Affix[Conf->naffixes].find,find); - strcpy(Conf->Affix[Conf->naffixes].repl,repl); - Conf->Affix[Conf->naffixes].replen=strlen(repl); + Conf->Affix[Conf->naffixes].flag = flag; + Conf->Affix[Conf->naffixes].type = type; + + strcpy(Conf->Affix[Conf->naffixes].find, find); + strcpy(Conf->Affix[Conf->naffixes].repl, repl); + Conf->Affix[Conf->naffixes].replen = strlen(repl); Conf->naffixes++; - return(0); + return (0); } -static char * -remove_spaces(char *dist,char *src){ -char *d,*s; - d=dist; - s=src; - while(*s){ - if(*s!=' '&&*s!='-'&&*s!='\t'){ - *d=*s; +static char * +remove_spaces(char *dist, char *src) +{ + char *d, + *s; + + d = dist; + s = src; + while (*s) + { + if (*s != ' ' && *s != '-' && *s != '\t') + { + *d = *s; d++; } s++; } - *d=0; - return(dist); + *d = 0; + return (dist); } -int -ImportAffixes(IspellDict * Conf,const char *filename){ +int +ImportAffixes(IspellDict * Conf, const char *filename) +{ unsigned char str[BUFSIZ]; - unsigned char flag=0; - unsigned char mask[BUFSIZ]=""; - unsigned char find[BUFSIZ]=""; - unsigned char repl[BUFSIZ]=""; + unsigned char flag = 0; + unsigned char mask[BUFSIZ] = ""; + unsigned char find[BUFSIZ] = ""; + unsigned char repl[BUFSIZ] = ""; unsigned char *s; - int i; - int suffixes=0; - int prefixes=0; - FILE *affix; + int i; + int suffixes = 0; + int prefixes = 0; + FILE *affix; - if(!(affix=fopen(filename,"r"))) - return(1); + if (!(affix = fopen(filename, "r"))) + return (1); - while(fgets(str,sizeof(str),affix)){ - if(!STRNCASECMP(str,"suffixes")){ - suffixes=1; - prefixes=0; + while (fgets(str, sizeof(str), affix)) + { + if (!STRNCASECMP(str, "suffixes")) + { + suffixes = 1; + prefixes = 0; continue; } - if(!STRNCASECMP(str,"prefixes")){ - suffixes=0; - prefixes=1; + if (!STRNCASECMP(str, "prefixes")) + { + suffixes = 0; + prefixes = 1; continue; } - if(!STRNCASECMP(str,"flag ")){ - s=str+5; - while(strchr("* ",*s)) + if (!STRNCASECMP(str, "flag ")) + { + s = str + 5; + while (strchr("* ", *s)) s++; - flag=*s; + flag = *s; continue; } - if((!suffixes)&&(!prefixes))continue; - if((s=strchr(str,'#')))*s=0; - if(!*str)continue; + if ((!suffixes) && (!prefixes)) + continue; + if ((s = strchr(str, '#'))) + *s = 0; + if (!*str) + continue; strlower(str); - strcpy(mask,""); - strcpy(find,""); - strcpy(repl,""); - i=sscanf(str,"%[^>\n]>%[^,\n],%[^\n]",mask,find,repl); - remove_spaces(str,repl);strcpy(repl,str); - remove_spaces(str,find);strcpy(find,str); - remove_spaces(str,mask);strcpy(mask,str); - switch(i){ + strcpy(mask, ""); + strcpy(find, ""); + strcpy(repl, ""); + i = sscanf(str, "%[^>\n]>%[^,\n],%[^\n]", mask, find, repl); + remove_spaces(str, repl); + strcpy(repl, str); + remove_spaces(str, find); + strcpy(find, str); + remove_spaces(str, mask); + strcpy(mask, str); + switch (i) + { case 3: break; case 2: - if(*find != '\0'){ - strcpy(repl,find); - strcpy(find,""); + if (*find != '\0') + { + strcpy(repl, find); + strcpy(find, ""); } break; default: continue; } - - AddAffix(Conf,(int)flag,mask,find,repl,suffixes?'s':'p'); - + + AddAffix(Conf, (int) flag, mask, find, repl, suffixes ? 's' : 'p'); + } fclose(affix); - - return(0); + + return (0); } -void -SortDictionary(IspellDict * Conf){ - int CurLet = -1, Let;size_t i; +void +SortDictionary(IspellDict * Conf) +{ + int CurLet = -1, + Let; + size_t i; - qsort((void*)Conf->Spell,Conf->nspell,sizeof(SPELL),cmpspell); + qsort((void *) Conf->Spell, Conf->nspell, sizeof(SPELL), cmpspell); - for(i = 0; i < 256 ; i++ ) + for (i = 0; i < 256; i++) Conf->SpellTree.Left[i] = -1; - for(i = 0; i < Conf->nspell; i++) { - Let = (int)(*(Conf->Spell[i].word)) & 255; - if (CurLet != Let) { - Conf->SpellTree.Left[Let] = i; - CurLet = Let; - } - Conf->SpellTree.Right[Let] = i; + for (i = 0; i < Conf->nspell; i++) + { + Let = (int) (*(Conf->Spell[i].word)) & 255; + if (CurLet != Let) + { + Conf->SpellTree.Left[Let] = i; + CurLet = Let; + } + Conf->SpellTree.Right[Let] = i; } } -void -SortAffixes(IspellDict * Conf) { - int CurLetP = -1, CurLetS = -1, Let; - AFFIX *Affix; size_t i; - - if (Conf->naffixes > 1) - qsort((void*)Conf->Affix,Conf->naffixes,sizeof(AFFIX),cmpaffix); - for(i = 0; i < 256; i++) { - Conf->PrefixTree.Left[i] = Conf->PrefixTree.Right[i] = -1; - Conf->SuffixTree.Left[i] = Conf->SuffixTree.Right[i] = -1; - } +void +SortAffixes(IspellDict * Conf) +{ + int CurLetP = -1, + CurLetS = -1, + Let; + AFFIX *Affix; + size_t i; - for(i = 0; i < Conf->naffixes; i++) { - Affix = &(((AFFIX*)Conf->Affix)[i]); - if(Affix->type == 'p') { - Let = (int)(*(Affix->repl)) & 255; - if (CurLetP != Let) { - Conf->PrefixTree.Left[Let] = i; - CurLetP = Let; - } - Conf->PrefixTree.Right[Let] = i; - } else { - Let = (Affix->replen) ? (int)(Affix->repl[Affix->replen-1]) & 255 : 0; - if (CurLetS != Let) { - Conf->SuffixTree.Left[Let] = i; - CurLetS = Let; - } - Conf->SuffixTree.Right[Let] = i; - } - } + if (Conf->naffixes > 1) + qsort((void *) Conf->Affix, Conf->naffixes, sizeof(AFFIX), cmpaffix); + for (i = 0; i < 256; i++) + { + Conf->PrefixTree.Left[i] = Conf->PrefixTree.Right[i] = -1; + Conf->SuffixTree.Left[i] = Conf->SuffixTree.Right[i] = -1; + } + + for (i = 0; i < Conf->naffixes; i++) + { + Affix = &(((AFFIX *) Conf->Affix)[i]); + if (Affix->type == 'p') + { + Let = (int) (*(Affix->repl)) & 255; + if (CurLetP != Let) + { + Conf->PrefixTree.Left[Let] = i; + CurLetP = Let; + } + Conf->PrefixTree.Right[Let] = i; + } + else + { + Let = (Affix->replen) ? (int) (Affix->repl[Affix->replen - 1]) & 255 : 0; + if (CurLetS != Let) + { + Conf->SuffixTree.Left[Let] = i; + CurLetS = Let; + } + Conf->SuffixTree.Right[Let] = i; + } + } } -static char * -CheckSuffix(const char *word, size_t len, AFFIX *Affix, int *res, IspellDict *Conf) { - regmatch_t subs[2]; /* workaround for apache&linux */ - char newword[2*MAXNORMLEN] = ""; - int err; - - *res = strbncmp(word, Affix->repl, Affix->replen); - if (*res < 0) { - return NULL; - } - if (*res > 0) { - return NULL; - } - strcpy(newword, word); - strcpy(newword+len-Affix->replen, Affix->find); +static char * +CheckSuffix(const char *word, size_t len, AFFIX * Affix, int *res, IspellDict * Conf) +{ + regmatch_t subs[2]; /* workaround for apache&linux */ + char newword[2 * MAXNORMLEN] = ""; + int err; - if (Affix->compile) { - err = regcomp(&(Affix->reg),Affix->mask,REG_EXTENDED|REG_ICASE|REG_NOSUB); - if(err){ - /*regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE);*/ - regfree(&(Affix->reg)); - return(NULL); - } - Affix->compile = 0; - } - if(!(err=regexec(&(Affix->reg),newword,1,subs,0))){ - if(FindWord(Conf, newword, Affix->flag)) - return pstrdup(newword); - } - return NULL; + *res = strbncmp(word, Affix->repl, Affix->replen); + if (*res < 0) + return NULL; + if (*res > 0) + return NULL; + strcpy(newword, word); + strcpy(newword + len - Affix->replen, Affix->find); + + if (Affix->compile) + { + err = regcomp(&(Affix->reg), Affix->mask, REG_EXTENDED | REG_ICASE | REG_NOSUB); + if (err) + { + /* regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE); */ + regfree(&(Affix->reg)); + return (NULL); + } + Affix->compile = 0; + } + if (!(err = regexec(&(Affix->reg), newword, 1, subs, 0))) + { + if (FindWord(Conf, newword, Affix->flag)) + return pstrdup(newword); + } + return NULL; } #define NS 1 #define MAX_NORM 512 -static int -CheckPrefix(const char *word, size_t len, AFFIX *Affix, IspellDict *Conf, int pi, - char **forms, char ***cur ) { - regmatch_t subs[NS*2]; - char newword[2*MAXNORMLEN] = ""; - int err, ls, res, lres; - size_t newlen; - AFFIX *CAffix = Conf->Affix; - - res = strncmp(word, Affix->repl, Affix->replen); - if (res != 0) { - return res; - } - strcpy(newword, Affix->find); - strcat(newword, word+Affix->replen); +static int +CheckPrefix(const char *word, size_t len, AFFIX * Affix, IspellDict * Conf, int pi, + char **forms, char ***cur) +{ + regmatch_t subs[NS * 2]; + char newword[2 * MAXNORMLEN] = ""; + int err, + ls, + res, + lres; + size_t newlen; + AFFIX *CAffix = Conf->Affix; - if (Affix->compile) { - err = regcomp(&(Affix->reg),Affix->mask,REG_EXTENDED|REG_ICASE|REG_NOSUB); - if(err){ - /*regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE);*/ - regfree(&(Affix->reg)); - return (0); - } - Affix->compile = 0; - } - if(!(err=regexec(&(Affix->reg),newword,1,subs,0))){ - SPELL * curspell; + res = strncmp(word, Affix->repl, Affix->replen); + if (res != 0) + return res; + strcpy(newword, Affix->find); + strcat(newword, word + Affix->replen); - if((curspell=FindWord(Conf, newword, Affix->flag))){ - if ((*cur - forms) < (MAX_NORM-1)) { - **cur = pstrdup(newword); - (*cur)++; **cur = NULL; - } - } - newlen = strlen(newword); - ls = Conf->SuffixTree.Left[pi]; - if ( ls>=0 && ((*cur - forms) < (MAX_NORM-1)) ) { - **cur = CheckSuffix(newword, newlen, &CAffix[ls], &lres, Conf); - if (**cur) { - (*cur)++; **cur = NULL; + if (Affix->compile) + { + err = regcomp(&(Affix->reg), Affix->mask, REG_EXTENDED | REG_ICASE | REG_NOSUB); + if (err) + { + /* regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE); */ + regfree(&(Affix->reg)); + return (0); + } + Affix->compile = 0; } - } - } - return 0; + if (!(err = regexec(&(Affix->reg), newword, 1, subs, 0))) + { + SPELL *curspell; + + if ((curspell = FindWord(Conf, newword, Affix->flag))) + { + if ((*cur - forms) < (MAX_NORM - 1)) + { + **cur = pstrdup(newword); + (*cur)++; + **cur = NULL; + } + } + newlen = strlen(newword); + ls = Conf->SuffixTree.Left[pi]; + if (ls >= 0 && ((*cur - forms) < (MAX_NORM - 1))) + { + **cur = CheckSuffix(newword, newlen, &CAffix[ls], &lres, Conf); + if (**cur) + { + (*cur)++; + **cur = NULL; + } + } + } + return 0; } -char ** -NormalizeWord(IspellDict * Conf,char *word){ +char ** +NormalizeWord(IspellDict * Conf, char *word) +{ /*regmatch_t subs[NS];*/ -size_t len; -char ** forms; -char **cur; -AFFIX * Affix; -int ri, pi, ipi, lp, rp, cp, ls, rs; -int lres, rres, cres = 0; - SPELL *spell; + size_t len; + char **forms; + char **cur; + AFFIX *Affix; + int ri, + pi, + ipi, + lp, + rp, + cp, + ls, + rs; + int lres, + rres, + cres = 0; + SPELL *spell; - len=strlen(word); + len = strlen(word); if (len > MAXNORMLEN) - return(NULL); + return (NULL); strlower(word); - forms=(char **) palloc(MAX_NORM*sizeof(char **)); - cur=forms;*cur=NULL; + forms = (char **) palloc(MAX_NORM * sizeof(char **)); + cur = forms; + *cur = NULL; - ri = (int)(*word) & 255; - pi = (int)(word[strlen(word)-1]) & 255; - Affix=(AFFIX*)Conf->Affix; + ri = (int) (*word) & 255; + pi = (int) (word[strlen(word) - 1]) & 255; + Affix = (AFFIX *) Conf->Affix; /* Check that the word itself is normal form */ - if((spell = FindWord(Conf, word, 0))){ - *cur=pstrdup(word); - cur++;*cur=NULL; + if ((spell = FindWord(Conf, word, 0))) + { + *cur = pstrdup(word); + cur++; + *cur = NULL; } /* Find all other NORMAL forms of the 'word' */ - for (ipi = 0; ipi <= pi; ipi += pi) { + for (ipi = 0; ipi <= pi; ipi += pi) + { - /* check prefix */ - lp = Conf->PrefixTree.Left[ri]; - rp = Conf->PrefixTree.Right[ri]; - while (lp >= 0 && lp <= rp) { - cp = (lp + rp) >> 1; - cres = 0; - if ((cur - forms) < (MAX_NORM-1)) { - cres = CheckPrefix(word, len, &Affix[cp], Conf, ipi, forms, &cur); - } - if ((lp < cp) && ((cur - forms) < (MAX_NORM-1)) ) { - lres = CheckPrefix(word, len, &Affix[lp], Conf, ipi, forms, &cur); - } - if ( (rp > cp) && ((cur - forms) < (MAX_NORM-1)) ) { - rres = CheckPrefix(word, len, &Affix[rp], Conf, ipi, forms, &cur); - } - if (cres < 0) { - rp = cp - 1; - lp++; - } else if (cres > 0) { - lp = cp + 1; - rp--; - } else { - lp++; - rp--; - } - } - - /* check suffix */ - ls = Conf->SuffixTree.Left[ipi]; - rs = Conf->SuffixTree.Right[ipi]; - while (ls >= 0 && ls <= rs) { - if ( ((cur - forms) < (MAX_NORM-1)) ) { - *cur = CheckSuffix(word, len, &Affix[ls], &lres, Conf); - if (*cur) { - cur++; *cur = NULL; + /* check prefix */ + lp = Conf->PrefixTree.Left[ri]; + rp = Conf->PrefixTree.Right[ri]; + while (lp >= 0 && lp <= rp) + { + cp = (lp + rp) >> 1; + cres = 0; + if ((cur - forms) < (MAX_NORM - 1)) + cres = CheckPrefix(word, len, &Affix[cp], Conf, ipi, forms, &cur); + if ((lp < cp) && ((cur - forms) < (MAX_NORM - 1))) + lres = CheckPrefix(word, len, &Affix[lp], Conf, ipi, forms, &cur); + if ((rp > cp) && ((cur - forms) < (MAX_NORM - 1))) + rres = CheckPrefix(word, len, &Affix[rp], Conf, ipi, forms, &cur); + if (cres < 0) + { + rp = cp - 1; + lp++; + } + else if (cres > 0) + { + lp = cp + 1; + rp--; + } + else + { + lp++; + rp--; + } } - } - if ( (rs > ls) && ((cur - forms) < (MAX_NORM-1)) ) { - *cur = CheckSuffix(word, len, &Affix[rs], &rres, Conf); - if (*cur) { - cur++; *cur = NULL; - } - } - ls++; - rs--; - } /* end while */ - - } /* for ipi */ - if(cur==forms){ + /* check suffix */ + ls = Conf->SuffixTree.Left[ipi]; + rs = Conf->SuffixTree.Right[ipi]; + while (ls >= 0 && ls <= rs) + { + if (((cur - forms) < (MAX_NORM - 1))) + { + *cur = CheckSuffix(word, len, &Affix[ls], &lres, Conf); + if (*cur) + { + cur++; + *cur = NULL; + } + } + if ((rs > ls) && ((cur - forms) < (MAX_NORM - 1))) + { + *cur = CheckSuffix(word, len, &Affix[rs], &rres, Conf); + if (*cur) + { + cur++; + *cur = NULL; + } + } + ls++; + rs--; + } /* end while */ + + } /* for ipi */ + + if (cur == forms) + { pfree(forms); - return(NULL); + return (NULL); } - return(forms); + return (forms); } -void -FreeIspell (IspellDict *Conf) { - int i; - AFFIX *Affix = (AFFIX *)Conf->Affix; +void +FreeIspell(IspellDict * Conf) +{ + int i; + AFFIX *Affix = (AFFIX *) Conf->Affix; - for (i = 0; i < Conf->naffixes; i++) { - if (Affix[i].compile == 0) { - regfree(&(Affix[i].reg)); - } - } - for (i = 0; i < Conf->naffixes; i++) { - free( Conf->Spell[i].word ); - } - free(Conf->Affix); - free(Conf->Spell); - memset( (void*)Conf, 0, sizeof(IspellDict) ); - return; + for (i = 0; i < Conf->naffixes; i++) + { + if (Affix[i].compile == 0) + regfree(&(Affix[i].reg)); + } + for (i = 0; i < Conf->naffixes; i++) + free(Conf->Spell[i].word); + free(Conf->Affix); + free(Conf->Spell); + memset((void *) Conf, 0, sizeof(IspellDict)); + return; } diff --git a/contrib/tsearch2/ispell/spell.h b/contrib/tsearch2/ispell/spell.h index 3034ca6709..baf5052f02 100644 --- a/contrib/tsearch2/ispell/spell.h +++ b/contrib/tsearch2/ispell/spell.h @@ -4,48 +4,53 @@ #include #include -typedef struct spell_struct { - char * word; - char flag[10]; -} SPELL; +typedef struct spell_struct +{ + char *word; + char flag[10]; +} SPELL; -typedef struct aff_struct { - char flag; - char type; - char mask[33]; - char find[16]; - char repl[16]; - regex_t reg; - size_t replen; - char compile; -} AFFIX; +typedef struct aff_struct +{ + char flag; + char type; + char mask[33]; + char find[16]; + char repl[16]; + regex_t reg; + size_t replen; + char compile; +} AFFIX; -typedef struct Tree_struct { - int Left[256], Right[256]; -} Tree_struct; +typedef struct Tree_struct +{ + int Left[256], + Right[256]; +} Tree_struct; -typedef struct { - int maffixes; - int naffixes; - AFFIX * Affix; +typedef struct +{ + int maffixes; + int naffixes; + AFFIX *Affix; - int nspell; - int mspell; - SPELL *Spell; - Tree_struct SpellTree; - Tree_struct PrefixTree; - Tree_struct SuffixTree; + int nspell; + int mspell; + SPELL *Spell; + Tree_struct SpellTree; + Tree_struct PrefixTree; + Tree_struct SuffixTree; -} IspellDict; +} IspellDict; -char ** NormalizeWord(IspellDict * Conf,char *word); -int ImportAffixes(IspellDict * Conf, const char *filename); -int ImportDictionary(IspellDict * Conf,const char *filename); +char **NormalizeWord(IspellDict * Conf, char *word); +int ImportAffixes(IspellDict * Conf, const char *filename); +int ImportDictionary(IspellDict * Conf, const char *filename); -int AddSpell(IspellDict * Conf,const char * word,const char *flag); -int AddAffix(IspellDict * Conf,int flag,const char *mask,const char *find,const char *repl,int type); -void SortDictionary(IspellDict * Conf); -void SortAffixes(IspellDict * Conf); -void FreeIspell (IspellDict *Conf); +int AddSpell(IspellDict * Conf, const char *word, const char *flag); +int AddAffix(IspellDict * Conf, int flag, const char *mask, const char *find, const char *repl, int type); +void SortDictionary(IspellDict * Conf); +void SortAffixes(IspellDict * Conf); +void FreeIspell(IspellDict * Conf); #endif diff --git a/contrib/tsearch2/prs_dcfg.c b/contrib/tsearch2/prs_dcfg.c index 783cf43ceb..6b553e4525 100644 --- a/contrib/tsearch2/prs_dcfg.c +++ b/contrib/tsearch2/prs_dcfg.c @@ -1,5 +1,5 @@ -/* - * Simple config parser +/* + * Simple config parser * Teodor Sigaev */ #include @@ -16,126 +16,164 @@ #define CS_WAITEQ 2 #define CS_WAITVALUE 3 #define CS_INVALUE 4 -#define CS_IN2VALUE 5 +#define CS_IN2VALUE 5 #define CS_WAITDELIM 6 #define CS_INESC 7 #define CS_IN2ESC 8 static char * -nstrdup(char *ptr, int len) { - char *res=palloc(len+1), *cptr; - memcpy(res,ptr,len); - res[len]='\0'; +nstrdup(char *ptr, int len) +{ + char *res = palloc(len + 1), + *cptr; + + memcpy(res, ptr, len); + res[len] = '\0'; cptr = ptr = res; - while(*ptr) { - if ( *ptr == '\\' ) + while (*ptr) + { + if (*ptr == '\\') ptr++; - *cptr=*ptr; ptr++; cptr++; + *cptr = *ptr; + ptr++; + cptr++; } - *cptr='\0'; + *cptr = '\0'; return res; } void -parse_cfgdict(text *in, Map **m) { - Map *mptr; - char *ptr=VARDATA(in), *begin=NULL; - char num=0; - int state=CS_WAITKEY; +parse_cfgdict(text *in, Map ** m) +{ + Map *mptr; + char *ptr = VARDATA(in), + *begin = NULL; + char num = 0; + int state = CS_WAITKEY; - while( ptr-VARDATA(in) < VARSIZE(in) - VARHDRSZ ) { - if ( *ptr==',' ) num++; + while (ptr - VARDATA(in) < VARSIZE(in) - VARHDRSZ) + { + if (*ptr == ',') + num++; ptr++; } - *m=mptr=(Map*)palloc( sizeof(Map)*(num+2) ); - memset(mptr, 0, sizeof(Map)*(num+2) ); - ptr=VARDATA(in); - while( ptr-VARDATA(in) < VARSIZE(in) - VARHDRSZ ) { - if (state==CS_WAITKEY) { - if (isalpha(*ptr)) { - begin=ptr; - state=CS_INKEY; - } else if ( !isspace(*ptr) ) - ereport(ERROR, - (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("syntax error"), - errdetail("Syntax error in position %d near \"%c\"", - (int) (ptr-VARDATA(in)), *ptr))); - } else if (state==CS_INKEY) { - if ( isspace(*ptr) ) { - mptr->key=nstrdup(begin, ptr-begin); - state=CS_WAITEQ; - } else if ( *ptr=='=' ) { - mptr->key=nstrdup(begin, ptr-begin); - state=CS_WAITVALUE; - } else if ( !isalpha(*ptr) ) - ereport(ERROR, - (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("syntax error"), - errdetail("Syntax error in position %d near \"%c\"", - (int) (ptr-VARDATA(in)), *ptr))); - } else if ( state==CS_WAITEQ ) { - if ( *ptr=='=' ) - state=CS_WAITVALUE; - else if ( !isspace(*ptr) ) - ereport(ERROR, - (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("syntax error"), - errdetail("Syntax error in position %d near \"%c\"", - (int) (ptr-VARDATA(in)), *ptr))); - } else if ( state==CS_WAITVALUE ) { - if ( *ptr=='"' ) { - begin=ptr+1; - state=CS_INVALUE; - } else if ( !isspace(*ptr) ) { - begin=ptr; - state=CS_IN2VALUE; + *m = mptr = (Map *) palloc(sizeof(Map) * (num + 2)); + memset(mptr, 0, sizeof(Map) * (num + 2)); + ptr = VARDATA(in); + while (ptr - VARDATA(in) < VARSIZE(in) - VARHDRSZ) + { + if (state == CS_WAITKEY) + { + if (isalpha(*ptr)) + { + begin = ptr; + state = CS_INKEY; } - } else if ( state==CS_INVALUE ) { - if ( *ptr=='"' ) { - mptr->value = nstrdup(begin, ptr-begin); - mptr++; - state=CS_WAITDELIM; - } else if ( *ptr=='\\' ) - state=CS_INESC; - } else if ( state==CS_IN2VALUE ) { - if ( isspace(*ptr) || *ptr==',' ) { - mptr->value = nstrdup(begin, ptr-begin); - mptr++; - state=( *ptr==',' ) ? CS_WAITKEY : CS_WAITDELIM; - } else if ( *ptr=='\\' ) - state=CS_INESC; - } else if ( state==CS_WAITDELIM ) { - if ( *ptr==',' ) - state=CS_WAITKEY; - else if ( !isspace(*ptr) ) + else if (!isspace(*ptr)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), - errdetail("Syntax error in position %d near \"%c\"", - (int) (ptr-VARDATA(in)), *ptr))); - } else if ( state == CS_INESC ) { - state=CS_INVALUE; - } else if ( state == CS_IN2ESC ) { - state=CS_IN2VALUE; - } else + errdetail("Syntax error in position %d near \"%c\"", + (int) (ptr - VARDATA(in)), *ptr))); + } + else if (state == CS_INKEY) + { + if (isspace(*ptr)) + { + mptr->key = nstrdup(begin, ptr - begin); + state = CS_WAITEQ; + } + else if (*ptr == '=') + { + mptr->key = nstrdup(begin, ptr - begin); + state = CS_WAITVALUE; + } + else if (!isalpha(*ptr)) + ereport(ERROR, + (errcode(ERRCODE_SYNTAX_ERROR), + errmsg("syntax error"), + errdetail("Syntax error in position %d near \"%c\"", + (int) (ptr - VARDATA(in)), *ptr))); + } + else if (state == CS_WAITEQ) + { + if (*ptr == '=') + state = CS_WAITVALUE; + else if (!isspace(*ptr)) + ereport(ERROR, + (errcode(ERRCODE_SYNTAX_ERROR), + errmsg("syntax error"), + errdetail("Syntax error in position %d near \"%c\"", + (int) (ptr - VARDATA(in)), *ptr))); + } + else if (state == CS_WAITVALUE) + { + if (*ptr == '"') + { + begin = ptr + 1; + state = CS_INVALUE; + } + else if (!isspace(*ptr)) + { + begin = ptr; + state = CS_IN2VALUE; + } + } + else if (state == CS_INVALUE) + { + if (*ptr == '"') + { + mptr->value = nstrdup(begin, ptr - begin); + mptr++; + state = CS_WAITDELIM; + } + else if (*ptr == '\\') + state = CS_INESC; + } + else if (state == CS_IN2VALUE) + { + if (isspace(*ptr) || *ptr == ',') + { + mptr->value = nstrdup(begin, ptr - begin); + mptr++; + state = (*ptr == ',') ? CS_WAITKEY : CS_WAITDELIM; + } + else if (*ptr == '\\') + state = CS_INESC; + } + else if (state == CS_WAITDELIM) + { + if (*ptr == ',') + state = CS_WAITKEY; + else if (!isspace(*ptr)) + ereport(ERROR, + (errcode(ERRCODE_SYNTAX_ERROR), + errmsg("syntax error"), + errdetail("Syntax error in position %d near \"%c\"", + (int) (ptr - VARDATA(in)), *ptr))); + } + else if (state == CS_INESC) + state = CS_INVALUE; + else if (state == CS_IN2ESC) + state = CS_IN2VALUE; + else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("bad parser state"), errdetail("%d at position %d near \"%c\"", - state, (int) (ptr-VARDATA(in)), *ptr))); + state, (int) (ptr - VARDATA(in)), *ptr))); ptr++; } - if (state==CS_IN2VALUE) { - mptr->value = nstrdup(begin, ptr-begin); + if (state == CS_IN2VALUE) + { + mptr->value = nstrdup(begin, ptr - begin); mptr++; - } else if ( !(state==CS_WAITDELIM || state==CS_WAITKEY) ) + } + else if (!(state == CS_WAITDELIM || state == CS_WAITKEY)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("unexpected end of line"))); } - - diff --git a/contrib/tsearch2/query.c b/contrib/tsearch2/query.c index 14564c6289..0019b04f16 100644 --- a/contrib/tsearch2/query.c +++ b/contrib/tsearch2/query.c @@ -99,28 +99,40 @@ typedef struct TI_IN_STATE valstate; /* tscfg */ - int cfg_id; + int cfg_id; } QPRS_STATE; -static char* -get_weight(char *buf, int2 *weight) { +static char * +get_weight(char *buf, int2 *weight) +{ *weight = 0; - if ( *buf != ':' ) + if (*buf != ':') return buf; buf++; - while( *buf ) { - switch(tolower(*buf)) { - case 'a': *weight |= 1<<3; break; - case 'b': *weight |= 1<<2; break; - case 'c': *weight |= 1<<1; break; - case 'd': *weight |= 1; break; - default: return buf; + while (*buf) + { + switch (tolower(*buf)) + { + case 'a': + *weight |= 1 << 3; + break; + case 'b': + *weight |= 1 << 2; + break; + case 'c': + *weight |= 1 << 1; + break; + case 'd': + *weight |= 1; + break; + default: + return buf; } buf++; } - + return buf; } @@ -146,11 +158,15 @@ gettoken_query(QPRS_STATE * state, int4 *val, int4 *lenval, char **strval, int2 state->count++; (state->buf)++; return OPEN; - } else if ( *(state->buf) == ':' ) { + } + else if (*(state->buf) == ':') + { ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("error at start of operand"))); - } else if (*(state->buf) != ' ') { + } + else if (*(state->buf) != ' ') + { state->valstate.prsbuf = state->buf; state->state = WAITOPERATOR; if (gettoken_tsvector(&(state->valstate))) @@ -257,7 +273,7 @@ static void pushval_morph(QPRS_STATE * state, int typeval, char *strval, int lenval, int2 weight) { int4 count = 0; - PRSTEXT prs; + PRSTEXT prs; prs.lenwords = 32; prs.curwords = 0; @@ -266,16 +282,17 @@ pushval_morph(QPRS_STATE * state, int typeval, char *strval, int lenval, int2 we parsetext_v2(findcfg(state->cfg_id), &prs, strval, lenval); - for(count=0;countvalues+val->pos+SHORTALIGN(val->len)+sizeof(uint16)); - uint16 len = *( (uint16*) (chkval->values+val->pos+SHORTALIGN(val->len)) ); - while (len--) { - if ( item->weight & ( 1<weight ) ) +checkclass_str(CHKVAL * chkval, WordEntry * val, ITEM * item) +{ + WordEntryPos *ptr = (WordEntryPos *) (chkval->values + val->pos + SHORTALIGN(val->len) + sizeof(uint16)); + uint16 len = *((uint16 *) (chkval->values + val->pos + SHORTALIGN(val->len))); + + while (len--) + { + if (item->weight & (1 << ptr->weight)) return true; ptr++; } - return false; + return false; } /* @@ -410,8 +430,8 @@ checkcondition_str(void *checkval, ITEM * val) StopMiddle = StopLow + (StopHigh - StopLow) / 2; difference = ValCompare((CHKVAL *) checkval, StopMiddle, val); if (difference == 0) - return ( val->weight && StopMiddle->haspos ) ? - checkclass_str((CHKVAL *) checkval,StopMiddle, val) : true; + return (val->weight && StopMiddle->haspos) ? + checkclass_str((CHKVAL *) checkval, StopMiddle, val) : true; else if (difference < 0) StopLow = StopMiddle + 1; else @@ -468,7 +488,7 @@ rexectsq(PG_FUNCTION_ARGS) Datum exectsq(PG_FUNCTION_ARGS) { - tsvector *val = (tsvector *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0))); + tsvector *val = (tsvector *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0))); QUERYTYPE *query = (QUERYTYPE *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(1))); CHKVAL chkval; bool result; @@ -485,10 +505,10 @@ exectsq(PG_FUNCTION_ARGS) chkval.values = STRPTR(val); chkval.operand = GETOPERAND(query); result = TS_execute( - GETQUERY(query), - &chkval, - true, - checkcondition_str + GETQUERY(query), + &chkval, + true, + checkcondition_str ); PG_FREE_IF_COPY(val, 0); @@ -534,7 +554,7 @@ findoprnd(ITEM * ptr, int4 *pos) * input */ static QUERYTYPE * -queryin(char *buf, void (*pushval) (QPRS_STATE *, int, char *, int, int2), int cfg_id) + queryin(char *buf, void (*pushval) (QPRS_STATE *, int, char *, int, int2), int cfg_id) { QPRS_STATE state; int4 i; @@ -555,7 +575,7 @@ queryin(char *buf, void (*pushval) (QPRS_STATE *, int, char *, int, int2), int c state.count = 0; state.num = 0; state.str = NULL; - state.cfg_id=cfg_id; + state.cfg_id = cfg_id; /* init value parser's state */ state.valstate.oprisdelim = true; @@ -678,12 +698,30 @@ infix(INFIX * in, bool first) } *(in->cur) = '\''; in->cur++; - if ( in->curpol->weight ) { - *(in->cur) = ':'; in->cur++; - if ( in->curpol->weight & (1<<3) ) { *(in->cur) = 'A'; in->cur++; } - if ( in->curpol->weight & (1<<2) ) { *(in->cur) = 'B'; in->cur++; } - if ( in->curpol->weight & (1<<1) ) { *(in->cur) = 'C'; in->cur++; } - if ( in->curpol->weight & 1 ) { *(in->cur) = 'D'; in->cur++; } + if (in->curpol->weight) + { + *(in->cur) = ':'; + in->cur++; + if (in->curpol->weight & (1 << 3)) + { + *(in->cur) = 'A'; + in->cur++; + } + if (in->curpol->weight & (1 << 2)) + { + *(in->cur) = 'B'; + in->cur++; + } + if (in->curpol->weight & (1 << 1)) + { + *(in->cur) = 'C'; + in->cur++; + } + if (in->curpol->weight & 1) + { + *(in->cur) = 'D'; + in->cur++; + } } *(in->cur) = '\0'; in->curpol++; @@ -827,15 +865,16 @@ tsquerytree(PG_FUNCTION_ARGS) } Datum -to_tsquery(PG_FUNCTION_ARGS) { - text *in = PG_GETARG_TEXT_P(1); - char *str; +to_tsquery(PG_FUNCTION_ARGS) +{ + text *in = PG_GETARG_TEXT_P(1); + char *str; QUERYTYPE *query; ITEM *res; int4 len; - str=text2char(in); - PG_FREE_IF_COPY(in,1); + str = text2char(in); + PG_FREE_IF_COPY(in, 1); query = queryin(str, pushval_morph, PG_GETARG_INT32(0)); res = clean_fakeval_v2(GETQUERY(query), &len); @@ -851,25 +890,25 @@ to_tsquery(PG_FUNCTION_ARGS) { } Datum -to_tsquery_name(PG_FUNCTION_ARGS) { - text *name=PG_GETARG_TEXT_P(0); - Datum res= DirectFunctionCall2( - to_tsquery, - Int32GetDatum( name2id_cfg(name) ), - PG_GETARG_DATUM(1) +to_tsquery_name(PG_FUNCTION_ARGS) +{ + text *name = PG_GETARG_TEXT_P(0); + Datum res = DirectFunctionCall2( + to_tsquery, + Int32GetDatum(name2id_cfg(name)), + PG_GETARG_DATUM(1) ); - - PG_FREE_IF_COPY(name,1); + + PG_FREE_IF_COPY(name, 1); PG_RETURN_DATUM(res); } Datum -to_tsquery_current(PG_FUNCTION_ARGS) { - PG_RETURN_DATUM( DirectFunctionCall2( - to_tsquery, - Int32GetDatum( get_currcfg() ), - PG_GETARG_DATUM(0) - )); +to_tsquery_current(PG_FUNCTION_ARGS) +{ + PG_RETURN_DATUM(DirectFunctionCall2( + to_tsquery, + Int32GetDatum(get_currcfg()), + PG_GETARG_DATUM(0) + )); } - - diff --git a/contrib/tsearch2/query.h b/contrib/tsearch2/query.h index c0715a2a03..4a79efdc53 100644 --- a/contrib/tsearch2/query.h +++ b/contrib/tsearch2/query.h @@ -16,10 +16,10 @@ typedef struct ITEM int2 left; int4 val; /* user-friendly value, must correlate with WordEntry */ - uint32 - unused:1, - length:11, - distance:20; + uint32 + unused:1, + length:11, + distance:20; } ITEM; /* @@ -50,6 +50,6 @@ typedef struct #define VALFALSE 7 bool TS_execute(ITEM * curitem, void *checkval, - bool calcnot, bool (*chkcond) (void *checkval, ITEM * val)); + bool calcnot, bool (*chkcond) (void *checkval, ITEM * val)); #endif diff --git a/contrib/tsearch2/rank.c b/contrib/tsearch2/rank.c index 0840eb8347..5b62c9810b 100644 --- a/contrib/tsearch2/rank.c +++ b/contrib/tsearch2/rank.c @@ -37,29 +37,35 @@ Datum rank_cd_def(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(get_covers); Datum get_covers(PG_FUNCTION_ARGS); -static float weights[]={0.1, 0.2, 0.4, 1.0}; +static float weights[] = {0.1, 0.2, 0.4, 1.0}; #define wpos(wep) ( w[ ((WordEntryPos*)(wep))->weight ] ) -#define DEF_NORM_METHOD 0 +#define DEF_NORM_METHOD 0 /* * Returns a weight of a word collocation */ -static float4 word_distance ( int4 w ) { - if ( w>100 ) - return 1e-30; +static float4 +word_distance(int4 w) +{ + if (w > 100) + return 1e-30; - return 1.0/(1.005+0.05*exp( ((float4)w)/1.5-2) ); + return 1.0 / (1.005 + 0.05 * exp(((float4) w) / 1.5 - 2)); } static int -cnt_length( tsvector *t ) { - WordEntry *ptr=ARRPTR(t), *end=(WordEntry*)STRPTR(t); - int len = 0, clen; +cnt_length(tsvector * t) +{ + WordEntry *ptr = ARRPTR(t), + *end = (WordEntry *) STRPTR(t); + int len = 0, + clen; - while(ptr < end) { - if ( (clen=POSDATALEN(t, ptr)) == 0 ) + while (ptr < end) + { + if ((clen = POSDATALEN(t, ptr)) == 0) len += 1; else len += clen; @@ -70,191 +76,225 @@ cnt_length( tsvector *t ) { } static int4 -WordECompareITEM(char *eval, char *qval, WordEntry * ptr, ITEM * item) { - if (ptr->len == item->length) - return strncmp( - eval + ptr->pos, - qval + item->distance, - item->length); +WordECompareITEM(char *eval, char *qval, WordEntry * ptr, ITEM * item) +{ + if (ptr->len == item->length) + return strncmp( + eval + ptr->pos, + qval + item->distance, + item->length); - return (ptr->len > item->length) ? 1 : -1; + return (ptr->len > item->length) ? 1 : -1; } -static WordEntry* -find_wordentry(tsvector *t, QUERYTYPE *q, ITEM *item) { - WordEntry *StopLow = ARRPTR(t); - WordEntry *StopHigh = (WordEntry*)STRPTR(t); - WordEntry *StopMiddle; - int difference; +static WordEntry * +find_wordentry(tsvector * t, QUERYTYPE * q, ITEM * item) +{ + WordEntry *StopLow = ARRPTR(t); + WordEntry *StopHigh = (WordEntry *) STRPTR(t); + WordEntry *StopMiddle; + int difference; - /* Loop invariant: StopLow <= item < StopHigh */ + /* Loop invariant: StopLow <= item < StopHigh */ - while (StopLow < StopHigh) - { - StopMiddle = StopLow + (StopHigh - StopLow) / 2; - difference = WordECompareITEM(STRPTR(t), GETOPERAND(q), StopMiddle, item); - if (difference == 0) - return StopMiddle; - else if (difference < 0) - StopLow = StopMiddle + 1; - else - StopHigh = StopMiddle; - } + while (StopLow < StopHigh) + { + StopMiddle = StopLow + (StopHigh - StopLow) / 2; + difference = WordECompareITEM(STRPTR(t), GETOPERAND(q), StopMiddle, item); + if (difference == 0) + return StopMiddle; + else if (difference < 0) + StopLow = StopMiddle + 1; + else + StopHigh = StopMiddle; + } - return NULL; + return NULL; } -static WordEntryPos POSNULL[]={ - {0,0}, - {0,MAXENTRYPOS-1} +static WordEntryPos POSNULL[] = { + {0, 0}, + {0, MAXENTRYPOS - 1} }; static float -calc_rank_and(float *w, tsvector *t, QUERYTYPE *q) { - uint16 **pos=(uint16**)palloc(sizeof(uint16*) * q->size); - int i,k,l,p; - WordEntry *entry; - WordEntryPos *post,*ct; - int4 dimt,lenct,dist; - float res=-1.0; - ITEM *item=GETQUERY(q); +calc_rank_and(float *w, tsvector * t, QUERYTYPE * q) +{ + uint16 **pos = (uint16 **) palloc(sizeof(uint16 *) * q->size); + int i, + k, + l, + p; + WordEntry *entry; + WordEntryPos *post, + *ct; + int4 dimt, + lenct, + dist; + float res = -1.0; + ITEM *item = GETQUERY(q); - memset(pos,0,sizeof(uint16**) * q->size); - *(uint16*)POSNULL = lengthof(POSNULL)-1; + memset(pos, 0, sizeof(uint16 **) * q->size); + *(uint16 *) POSNULL = lengthof(POSNULL) - 1; - for(i=0; isize; i++) { - - if ( item[i].type != VAL ) + for (i = 0; i < q->size; i++) + { + + if (item[i].type != VAL) continue; - entry=find_wordentry(t,q,&(item[i])); - if ( !entry ) + entry = find_wordentry(t, q, &(item[i])); + if (!entry) continue; - if ( entry->haspos ) - pos[i] = (uint16*)_POSDATAPTR(t,entry); + if (entry->haspos) + pos[i] = (uint16 *) _POSDATAPTR(t, entry); else - pos[i] = (uint16*)POSNULL; + pos[i] = (uint16 *) POSNULL; - dimt = *(uint16*)(pos[i]); - post = (WordEntryPos*)(pos[i]+1); - for( k=0; ksize; i++) { - if ( item[i].type != VAL ) + for (i = 0; i < q->size; i++) + { + if (item[i].type != VAL) continue; - entry=find_wordentry(t,q,&(item[i])); - if ( !entry ) + entry = find_wordentry(t, q, &(item[i])); + if (!entry) continue; - if ( entry->haspos ) { - dimt = POSDATALEN(t,entry); - post = POSDATAPTR(t,entry); - } else { - dimt = *(uint16*)POSNULL; - post = POSNULL+1; + if (entry->haspos) + { + dimt = POSDATALEN(t, entry); + post = POSDATAPTR(t, entry); + } + else + { + dimt = *(uint16 *) POSNULL; + post = POSNULL + 1; } - for(j=0;jsize || !q->size) return 0.0; - res = ( item->type != VAL && item->val == (int4) '&' ) ? - calc_rank_and(w,t,q) : calc_rank_or(w,t,q); + res = (item->type != VAL && item->val == (int4) '&') ? + calc_rank_and(w, t, q) : calc_rank_or(w, t, q); - if ( res < 0 ) + if (res < 0) res = 1e-20; - switch(method) { - case 0: break; - case 1: res /= log((float)cnt_length(t)); break; - case 2: res /= (float)cnt_length(t); break; + switch (method) + { + case 0: + break; + case 1: + res /= log((float) cnt_length(t)); + break; + case 2: + res /= (float) cnt_length(t); + break; default: - /* internal error */ - elog(ERROR,"unrecognized normalization method: %d", method); - } + /* internal error */ + elog(ERROR, "unrecognized normalization method: %d", method); + } return res; } Datum -rank(PG_FUNCTION_ARGS) { +rank(PG_FUNCTION_ARGS) +{ ArrayType *win = (ArrayType *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); - tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); + tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); QUERYTYPE *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_DATUM(2)); - int method=DEF_NORM_METHOD; - float res=0.0; - float ws[ lengthof(weights) ]; - int i; + int method = DEF_NORM_METHOD; + float res = 0.0; + float ws[lengthof(weights)]; + int i; - if ( ARR_NDIM(win) != 1 ) + if (ARR_NDIM(win) != 1) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array of weight must be one-dimensional"))); - if ( ARRNELEMS(win) < lengthof(weights) ) + if (ARRNELEMS(win) < lengthof(weights)) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array of weight is too short"))); - for(i=0;i= 0 ) ? ((float4*)ARR_DATA_PTR(win))[i] : weights[i]; - if ( ws[ i ] > 1.0 ) + for (i = 0; i < lengthof(weights); i++) + { + ws[i] = (((float4 *) ARR_DATA_PTR(win))[i] >= 0) ? ((float4 *) ARR_DATA_PTR(win))[i] : weights[i]; + if (ws[i] > 1.0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("weight out of range"))); - } + } - if ( PG_NARGS() == 4 ) - method=PG_GETARG_INT32(3); + if (PG_NARGS() == 4) + method = PG_GETARG_INT32(3); + + res = calc_rank(ws, txt, query, method); - res=calc_rank(ws, txt, query, method); - PG_FREE_IF_COPY(win, 0); PG_FREE_IF_COPY(txt, 1); PG_FREE_IF_COPY(query, 2); @@ -262,108 +302,127 @@ rank(PG_FUNCTION_ARGS) { } Datum -rank_def(PG_FUNCTION_ARGS) { - tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); +rank_def(PG_FUNCTION_ARGS) +{ + tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); QUERYTYPE *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); - float res=0.0; - int method=DEF_NORM_METHOD; + float res = 0.0; + int method = DEF_NORM_METHOD; - if ( PG_NARGS() == 3 ) - method=PG_GETARG_INT32(2); + if (PG_NARGS() == 3) + method = PG_GETARG_INT32(2); + + res = calc_rank(weights, txt, query, method); - res=calc_rank(weights, txt, query, method); - PG_FREE_IF_COPY(txt, 0); PG_FREE_IF_COPY(query, 1); PG_RETURN_FLOAT4(res); } -typedef struct { - ITEM *item; - int32 pos; -} DocRepresentation; +typedef struct +{ + ITEM *item; + int32 pos; +} DocRepresentation; static int -compareDocR(const void *a, const void *b) { - if ( ((DocRepresentation *) a)->pos == ((DocRepresentation *) b)->pos ) +compareDocR(const void *a, const void *b) +{ + if (((DocRepresentation *) a)->pos == ((DocRepresentation *) b)->pos) return 1; - return ( ((DocRepresentation *) a)->pos > ((DocRepresentation *) b)->pos ) ? 1 : -1; + return (((DocRepresentation *) a)->pos > ((DocRepresentation *) b)->pos) ? 1 : -1; } -typedef struct { +typedef struct +{ DocRepresentation *doc; - int len; + int len; } ChkDocR; static bool -checkcondition_DR(void *checkval, ITEM *val) { - DocRepresentation *ptr = ((ChkDocR*)checkval)->doc; +checkcondition_DR(void *checkval, ITEM * val) +{ + DocRepresentation *ptr = ((ChkDocR *) checkval)->doc; - while( ptr - ((ChkDocR*)checkval)->doc < ((ChkDocR*)checkval)->len ) { - if ( val == ptr->item ) + while (ptr - ((ChkDocR *) checkval)->doc < ((ChkDocR *) checkval)->len) + { + if (val == ptr->item) return true; ptr++; - } + } return false; } static bool -Cover(DocRepresentation *doc, int len, QUERYTYPE *query, int *pos, int *p, int *q) { - int i; - DocRepresentation *ptr,*f=(DocRepresentation*)0xffffffff; - ITEM *item=GETQUERY(query); - int lastpos=*pos; - int oldq=*q; +Cover(DocRepresentation * doc, int len, QUERYTYPE * query, int *pos, int *p, int *q) +{ + int i; + DocRepresentation *ptr, + *f = (DocRepresentation *) 0xffffffff; + ITEM *item = GETQUERY(query); + int lastpos = *pos; + int oldq = *q; - *p=0x7fffffff; - *q=0; + *p = 0x7fffffff; + *q = 0; - for(i=0; isize; i++) { - if ( item->type != VAL ) { + for (i = 0; i < query->size; i++) + { + if (item->type != VAL) + { item++; continue; } ptr = doc + *pos; - while(ptr-docitem == item ) { - if ( ptr->pos > *q ) { + while (ptr - doc < len) + { + if (ptr->item == item) + { + if (ptr->pos > *q) + { *q = ptr->pos; - lastpos= ptr - doc; - } + lastpos = ptr - doc; + } break; - } + } ptr++; } item++; } - if (*q==0 ) + if (*q == 0) return false; - if (*q==oldq) { /* already check this pos */ + if (*q == oldq) + { /* already check this pos */ (*pos)++; - return Cover(doc, len, query, pos,p,q); - } + return Cover(doc, len, query, pos, p, q); + } - item=GETQUERY(query); - for(i=0; isize; i++) { - if ( item->type != VAL ) { + item = GETQUERY(query); + for (i = 0; i < query->size; i++) + { + if (item->type != VAL) + { item++; continue; } ptr = doc + lastpos; - while(ptr>=doc+*pos) { - if ( ptr->item == item ) { - if ( ptr->pos < *p ) { + while (ptr >= doc + *pos) + { + if (ptr->item == item) + { + if (ptr->pos < *p) + { *p = ptr->pos; - f=ptr; + f = ptr; } break; } @@ -371,106 +430,135 @@ Cover(DocRepresentation *doc, int len, QUERYTYPE *query, int *pos, int *p, int * } item++; } - - if ( *p<=*q ) { - ChkDocR ch = { f, (doc + lastpos)-f+1 }; - *pos = f-doc+1; - if ( TS_execute(GETQUERY(query), &ch, false, checkcondition_DR) ) { - /*elog(NOTICE,"OP:%d NP:%d P:%d Q:%d", *pos, lastpos, *p, *q);*/ + + if (*p <= *q) + { + ChkDocR ch = {f, (doc + lastpos) - f + 1}; + + *pos = f - doc + 1; + if (TS_execute(GETQUERY(query), &ch, false, checkcondition_DR)) + { + /* + * elog(NOTICE,"OP:%d NP:%d P:%d Q:%d", *pos, lastpos, *p, + * *q); + */ return true; - } else - return Cover(doc, len, query, pos,p,q); + } + else + return Cover(doc, len, query, pos, p, q); } - + return false; } -static DocRepresentation* -get_docrep(tsvector *txt, QUERYTYPE *query, int *doclen) { - ITEM *item=GETQUERY(query); - WordEntry *entry; - WordEntryPos *post; - int4 dimt,j,i; - int len=query->size*4,cur=0; +static DocRepresentation * +get_docrep(tsvector * txt, QUERYTYPE * query, int *doclen) +{ + ITEM *item = GETQUERY(query); + WordEntry *entry; + WordEntryPos *post; + int4 dimt, + j, + i; + int len = query->size * 4, + cur = 0; DocRepresentation *doc; - *(uint16*)POSNULL = lengthof(POSNULL)-1; - doc = (DocRepresentation*)palloc(sizeof(DocRepresentation)*len); - for(i=0; isize; i++) { - if ( item[i].type != VAL ) + *(uint16 *) POSNULL = lengthof(POSNULL) - 1; + doc = (DocRepresentation *) palloc(sizeof(DocRepresentation) * len); + for (i = 0; i < query->size; i++) + { + if (item[i].type != VAL) continue; - entry=find_wordentry(txt,query,&(item[i])); - if ( !entry ) + entry = find_wordentry(txt, query, &(item[i])); + if (!entry) continue; - if ( entry->haspos ) { - dimt = POSDATALEN(txt,entry); - post = POSDATAPTR(txt,entry); - } else { - dimt = *(uint16*)POSNULL; - post = POSNULL+1; + if (entry->haspos) + { + dimt = POSDATALEN(txt, entry); + post = POSDATAPTR(txt, entry); + } + else + { + dimt = *(uint16 *) POSNULL; + post = POSNULL + 1; } - while( cur+dimt >= len ) { - len*=2; - doc = (DocRepresentation*)repalloc(doc,sizeof(DocRepresentation)*len); + while (cur + dimt >= len) + { + len *= 2; + doc = (DocRepresentation *) repalloc(doc, sizeof(DocRepresentation) * len); } - for(j=0;j0 ) { - if ( cur>1 ) + *doclen = cur; + + if (cur > 0) + { + if (cur > 1) qsort((void *) doc, cur, sizeof(DocRepresentation), compareDocR); return doc; } - + pfree(doc); return NULL; } Datum -rank_cd(PG_FUNCTION_ARGS) { - int K = PG_GETARG_INT32(0); - tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); +rank_cd(PG_FUNCTION_ARGS) +{ + int K = PG_GETARG_INT32(0); + tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); QUERYTYPE *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_DATUM(2)); - int method=DEF_NORM_METHOD; - DocRepresentation *doc; - float res=0.0; - int p=0,q=0,len,cur; + int method = DEF_NORM_METHOD; + DocRepresentation *doc; + float res = 0.0; + int p = 0, + q = 0, + len, + cur; doc = get_docrep(txt, query, &len); - if ( !doc ) { + if (!doc) + { PG_FREE_IF_COPY(txt, 1); PG_FREE_IF_COPY(query, 2); PG_RETURN_FLOAT4(0.0); } - cur=0; - if (K<=0) - K=4; - while( Cover(doc, len, query, &cur, &p, &q) ) - res += ( q-p+1 > K ) ? ((float)K)/((float)(q-p+1)) : 1.0; + cur = 0; + if (K <= 0) + K = 4; + while (Cover(doc, len, query, &cur, &p, &q)) + res += (q - p + 1 > K) ? ((float) K) / ((float) (q - p + 1)) : 1.0; - if ( PG_NARGS() == 4 ) - method=PG_GETARG_INT32(3); + if (PG_NARGS() == 4) + method = PG_GETARG_INT32(3); - switch(method) { - case 0: break; - case 1: res /= log((float)cnt_length(txt)); break; - case 2: res /= (float)cnt_length(txt); break; + switch (method) + { + case 0: + break; + case 1: + res /= log((float) cnt_length(txt)); + break; + case 2: + res /= (float) cnt_length(txt); + break; default: - /* internal error */ - elog(ERROR,"unrecognized normalization method: %d", method); - } + /* internal error */ + elog(ERROR, "unrecognized normalization method: %d", method); + } pfree(doc); PG_FREE_IF_COPY(txt, 1); @@ -481,120 +569,141 @@ rank_cd(PG_FUNCTION_ARGS) { Datum -rank_cd_def(PG_FUNCTION_ARGS) { - PG_RETURN_DATUM( DirectFunctionCall4( - rank_cd, - Int32GetDatum(-1), - PG_GETARG_DATUM(0), - PG_GETARG_DATUM(1), - ( PG_NARGS() == 3 ) ? PG_GETARG_DATUM(2) : Int32GetDatum(DEF_NORM_METHOD) - )); +rank_cd_def(PG_FUNCTION_ARGS) +{ + PG_RETURN_DATUM(DirectFunctionCall4( + rank_cd, + Int32GetDatum(-1), + PG_GETARG_DATUM(0), + PG_GETARG_DATUM(1), + (PG_NARGS() == 3) ? PG_GETARG_DATUM(2) : Int32GetDatum(DEF_NORM_METHOD) + )); } /**************debug*************/ -typedef struct { - char *w; - int2 len; - int2 pos; - int2 start; - int2 finish; -} DocWord; +typedef struct +{ + char *w; + int2 len; + int2 pos; + int2 start; + int2 finish; +} DocWord; static int -compareDocWord(const void *a, const void *b) { - if ( ((DocWord *) a)->pos == ((DocWord *) b)->pos ) +compareDocWord(const void *a, const void *b) +{ + if (((DocWord *) a)->pos == ((DocWord *) b)->pos) return 1; - return ( ((DocWord *) a)->pos > ((DocWord *) b)->pos ) ? 1 : -1; + return (((DocWord *) a)->pos > ((DocWord *) b)->pos) ? 1 : -1; } -Datum -get_covers(PG_FUNCTION_ARGS) { - tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); +Datum +get_covers(PG_FUNCTION_ARGS) +{ + tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); QUERYTYPE *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); - WordEntry *pptr=ARRPTR(txt); - int i,dlen=0,j,cur=0,len=0,rlen; - DocWord *dw,*dwptr; - text *out; - char *cptr; + WordEntry *pptr = ARRPTR(txt); + int i, + dlen = 0, + j, + cur = 0, + len = 0, + rlen; + DocWord *dw, + *dwptr; + text *out; + char *cptr; DocRepresentation *doc; - int pos=0,p,q,olddwpos=0; - int ncover=1; + int pos = 0, + p, + q, + olddwpos = 0; + int ncover = 1; doc = get_docrep(txt, query, &rlen); - if ( !doc ) { - out=palloc(VARHDRSZ); + if (!doc) + { + out = palloc(VARHDRSZ); VARATT_SIZEP(out) = VARHDRSZ; - PG_FREE_IF_COPY(txt,0); - PG_FREE_IF_COPY(query,1); + PG_FREE_IF_COPY(txt, 0); + PG_FREE_IF_COPY(query, 1); PG_RETURN_POINTER(out); } - for(i=0;isize;i++) { + for (i = 0; i < txt->size; i++) + { if (!pptr[i].haspos) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("no pos info"))); - dlen += POSDATALEN(txt,&(pptr[i])); + dlen += POSDATALEN(txt, &(pptr[i])); } - dwptr=dw=palloc(sizeof(DocWord)*dlen); - memset(dw,0,sizeof(DocWord)*dlen); + dwptr = dw = palloc(sizeof(DocWord) * dlen); + memset(dw, 0, sizeof(DocWord) * dlen); - for(i=0;isize;i++) { - WordEntryPos *posdata = POSDATAPTR(txt,&(pptr[i])); - for(j=0;jsize; i++) + { + WordEntryPos *posdata = POSDATAPTR(txt, &(pptr[i])); + + for (j = 0; j < POSDATALEN(txt, &(pptr[i])); j++) + { + dw[cur].w = STRPTR(txt) + pptr[i].pos; + dw[cur].len = pptr[i].len; + dw[cur].pos = posdata[j].pos; cur++; } - len+=(pptr[i].len + 1) * (int)POSDATALEN(txt,&(pptr[i])); + len += (pptr[i].len + 1) * (int) POSDATALEN(txt, &(pptr[i])); } qsort((void *) dw, dlen, sizeof(DocWord), compareDocWord); - while( Cover(doc, rlen, query, &pos, &p, &q) ) { - dwptr=dw+olddwpos; - while(dwptr->pos < p && dwptr-dwpos < p && dwptr - dw < dlen) dwptr++; - olddwpos=dwptr-dw; - dwptr->start=ncover; - while(dwptr->pos < q+1 && dwptr-dwstart = ncover; + while (dwptr->pos < q + 1 && dwptr - dw < dlen) dwptr++; - (dwptr-1)->finish=ncover; - len+= 4 /* {}+two spaces */ + 2*16 /*numbers*/; - ncover++; - } - - out=palloc(VARHDRSZ+len); - cptr=((char*)out)+VARHDRSZ; - dwptr=dw; + (dwptr - 1)->finish = ncover; + len += 4 /* {}+two spaces */ + 2 * 16 /* numbers */ ; + ncover++; + } - while( dwptr-dw < dlen) { - if ( dwptr->start ) { - sprintf(cptr,"{%d ",dwptr->start); - cptr=strchr(cptr,'\0'); + out = palloc(VARHDRSZ + len); + cptr = ((char *) out) + VARHDRSZ; + dwptr = dw; + + while (dwptr - dw < dlen) + { + if (dwptr->start) + { + sprintf(cptr, "{%d ", dwptr->start); + cptr = strchr(cptr, '\0'); } - memcpy(cptr,dwptr->w,dwptr->len); - cptr+=dwptr->len; - *cptr=' '; + memcpy(cptr, dwptr->w, dwptr->len); + cptr += dwptr->len; + *cptr = ' '; cptr++; - if ( dwptr->finish ) { - sprintf(cptr,"}%d ",dwptr->finish); - cptr=strchr(cptr,'\0'); + if (dwptr->finish) + { + sprintf(cptr, "}%d ", dwptr->finish); + cptr = strchr(cptr, '\0'); } dwptr++; - } + } + + VARATT_SIZEP(out) = cptr - ((char *) out); - VARATT_SIZEP(out) = cptr - ((char*)out); - pfree(dw); pfree(doc); - PG_FREE_IF_COPY(txt,0); - PG_FREE_IF_COPY(query,1); + PG_FREE_IF_COPY(txt, 0); + PG_FREE_IF_COPY(query, 1); PG_RETURN_POINTER(out); } - diff --git a/contrib/tsearch2/snmap.c b/contrib/tsearch2/snmap.c index 023c9eb5f9..2cd3f53e49 100644 --- a/contrib/tsearch2/snmap.c +++ b/contrib/tsearch2/snmap.c @@ -1,4 +1,4 @@ -/* +/* * simple but fast map from str to Oid * Teodor Sigaev */ @@ -11,69 +11,85 @@ #include "common.h" static int -compareSNMapEntry(const void *a, const void *b) { - return strcmp( ((SNMapEntry*)a)->key, ((SNMapEntry*)b)->key ); +compareSNMapEntry(const void *a, const void *b) +{ + return strcmp(((SNMapEntry *) a)->key, ((SNMapEntry *) b)->key); } -void -addSNMap( SNMap *map, char *key, Oid value ) { - if (map->len>=map->reallen) { +void +addSNMap(SNMap * map, char *key, Oid value) +{ + if (map->len >= map->reallen) + { SNMapEntry *tmp; - int len = (map->reallen) ? 2*map->reallen : 16; - tmp=(SNMapEntry*)realloc(map->list, sizeof(SNMapEntry) * len); - if ( !tmp ) + int len = (map->reallen) ? 2 * map->reallen : 16; + + tmp = (SNMapEntry *) realloc(map->list, sizeof(SNMapEntry) * len); + if (!tmp) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - map->reallen=len; - map->list=tmp; + map->reallen = len; + map->list = tmp; } - map->list[ map->len ].key = strdup(key); - if ( ! map->list[ map->len ].key ) + map->list[map->len].key = strdup(key); + if (!map->list[map->len].key) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - map->list[ map->len ].value=value; + map->list[map->len].value = value; map->len++; - if ( map->len>1 ) qsort(map->list, map->len, sizeof(SNMapEntry), compareSNMapEntry); + if (map->len > 1) + qsort(map->list, map->len, sizeof(SNMapEntry), compareSNMapEntry); } -void -addSNMap_t( SNMap *map, text *key, Oid value ) { - char *k=text2char( key ); +void +addSNMap_t(SNMap * map, text *key, Oid value) +{ + char *k = text2char(key); + addSNMap(map, k, value); pfree(k); } -Oid -findSNMap( SNMap *map, char *key ) { +Oid +findSNMap(SNMap * map, char *key) +{ SNMapEntry *ptr; - SNMapEntry ks = {key, 0}; - if ( map->len==0 || !map->list ) - return 0; - ptr = (SNMapEntry*) bsearch(&ks, map->list, map->len, sizeof(SNMapEntry), compareSNMapEntry); + SNMapEntry ks = {key, 0}; + + if (map->len == 0 || !map->list) + return 0; + ptr = (SNMapEntry *) bsearch(&ks, map->list, map->len, sizeof(SNMapEntry), compareSNMapEntry); return (ptr) ? ptr->value : 0; } -Oid -findSNMap_t( SNMap *map, text *key ) { - char *k=text2char(key); - int res; - res= findSNMap(map, k); +Oid +findSNMap_t(SNMap * map, text *key) +{ + char *k = text2char(key); + int res; + + res = findSNMap(map, k); pfree(k); return res; } -void freeSNMap( SNMap *map ) { - SNMapEntry *entry=map->list; - if ( map->list ) { - while( map->len ) { - if ( entry->key ) free(entry->key); - entry++; map->len--; +void +freeSNMap(SNMap * map) +{ + SNMapEntry *entry = map->list; + + if (map->list) + { + while (map->len) + { + if (entry->key) + free(entry->key); + entry++; + map->len--; } - free( map->list ); + free(map->list); } - memset(map,0,sizeof(SNMap)); + memset(map, 0, sizeof(SNMap)); } - - diff --git a/contrib/tsearch2/snmap.h b/contrib/tsearch2/snmap.h index b4856019c9..ae188b66a4 100644 --- a/contrib/tsearch2/snmap.h +++ b/contrib/tsearch2/snmap.h @@ -3,21 +3,23 @@ #include "postgres.h" -typedef struct { - char *key; - Oid value; -} SNMapEntry; +typedef struct +{ + char *key; + Oid value; +} SNMapEntry; -typedef struct { - int len; - int reallen; - SNMapEntry *list; -} SNMap; +typedef struct +{ + int len; + int reallen; + SNMapEntry *list; +} SNMap; -void addSNMap( SNMap *map, char *key, Oid value ); -void addSNMap_t( SNMap *map, text *key, Oid value ); -Oid findSNMap( SNMap *map, char *key ); -Oid findSNMap_t( SNMap *map, text *key ); -void freeSNMap( SNMap *map ); +void addSNMap(SNMap * map, char *key, Oid value); +void addSNMap_t(SNMap * map, text *key, Oid value); +Oid findSNMap(SNMap * map, char *key); +Oid findSNMap_t(SNMap * map, text *key); +void freeSNMap(SNMap * map); #endif diff --git a/contrib/tsearch2/snowball/api.c b/contrib/tsearch2/snowball/api.c index 27bf31a588..5cbf37d73b 100644 --- a/contrib/tsearch2/snowball/api.c +++ b/contrib/tsearch2/snowball/api.c @@ -2,48 +2,64 @@ #include "header.h" -extern struct SN_env * SN_create_env(int S_size, int I_size, int B_size) -{ struct SN_env * z = (struct SN_env *) calloc(1, sizeof(struct SN_env)); - z->p = create_s(); - if (S_size) - { z->S = (symbol * *) calloc(S_size, sizeof(symbol *)); - { int i; - for (i = 0; i < S_size; i++) z->S[i] = create_s(); - } - z->S_size = S_size; - } - - if (I_size) - { z->I = (int *) calloc(I_size, sizeof(int)); - z->I_size = I_size; - } - - if (B_size) - { z->B = (symbol *) calloc(B_size, sizeof(symbol)); - z->B_size = B_size; - } - - return z; -} - -extern void SN_close_env(struct SN_env * z) +extern struct SN_env * +SN_create_env(int S_size, int I_size, int B_size) { - if (z->S_size) - { - { int i; - for (i = 0; i < z->S_size; i++) lose_s(z->S[i]); - } - free(z->S); - } - if (z->I_size) free(z->I); - if (z->B_size) free(z->B); - if (z->p) lose_s(z->p); - free(z); + struct SN_env *z = (struct SN_env *) calloc(1, sizeof(struct SN_env)); + + z->p = create_s(); + if (S_size) + { + z->S = (symbol * *) calloc(S_size, sizeof(symbol *)); + { + int i; + + for (i = 0; i < S_size; i++) + z->S[i] = create_s(); + } + z->S_size = S_size; + } + + if (I_size) + { + z->I = (int *) calloc(I_size, sizeof(int)); + z->I_size = I_size; + } + + if (B_size) + { + z->B = (symbol *) calloc(B_size, sizeof(symbol)); + z->B_size = B_size; + } + + return z; } -extern void SN_set_current(struct SN_env * z, int size, const symbol * s) +extern void +SN_close_env(struct SN_env * z) { - replace_s(z, 0, z->l, size, s); - z->c = 0; + if (z->S_size) + { + { + int i; + + for (i = 0; i < z->S_size; i++) + lose_s(z->S[i]); + } + free(z->S); + } + if (z->I_size) + free(z->I); + if (z->B_size) + free(z->B); + if (z->p) + lose_s(z->p); + free(z); } +extern void +SN_set_current(struct SN_env * z, int size, const symbol * s) +{ + replace_s(z, 0, z->l, size, s); + z->c = 0; +} diff --git a/contrib/tsearch2/snowball/api.h b/contrib/tsearch2/snowball/api.h index 3e8b6e1851..efad537b9e 100644 --- a/contrib/tsearch2/snowball/api.h +++ b/contrib/tsearch2/snowball/api.h @@ -11,17 +11,24 @@ typedef unsigned char symbol; */ -struct SN_env { - symbol * p; - int c; int a; int l; int lb; int bra; int ket; - int S_size; int I_size; int B_size; - symbol * * S; - int * I; - symbol * B; +struct SN_env +{ + symbol *p; + int c; + int a; + int l; + int lb; + int bra; + int ket; + int S_size; + int I_size; + int B_size; + symbol **S; + int *I; + symbol *B; }; -extern struct SN_env * SN_create_env(int S_size, int I_size, int B_size); +extern struct SN_env *SN_create_env(int S_size, int I_size, int B_size); extern void SN_close_env(struct SN_env * z); extern void SN_set_current(struct SN_env * z, int size, const symbol * s); - diff --git a/contrib/tsearch2/snowball/english_stem.c b/contrib/tsearch2/snowball/english_stem.c index f6ceb5c576..310eddf97d 100644 --- a/contrib/tsearch2/snowball/english_stem.c +++ b/contrib/tsearch2/snowball/english_stem.c @@ -3,891 +3,1103 @@ #include "header.h" -extern int english_stem(struct SN_env * z); -static int r_exception2(struct SN_env * z); -static int r_exception1(struct SN_env * z); -static int r_Step_5(struct SN_env * z); -static int r_Step_4(struct SN_env * z); -static int r_Step_3(struct SN_env * z); -static int r_Step_2(struct SN_env * z); -static int r_Step_1c(struct SN_env * z); -static int r_Step_1b(struct SN_env * z); -static int r_Step_1a(struct SN_env * z); -static int r_R2(struct SN_env * z); -static int r_R1(struct SN_env * z); -static int r_shortv(struct SN_env * z); -static int r_mark_regions(struct SN_env * z); -static int r_postlude(struct SN_env * z); -static int r_prelude(struct SN_env * z); +extern int english_stem(struct SN_env * z); +static int r_exception2(struct SN_env * z); +static int r_exception1(struct SN_env * z); +static int r_Step_5(struct SN_env * z); +static int r_Step_4(struct SN_env * z); +static int r_Step_3(struct SN_env * z); +static int r_Step_2(struct SN_env * z); +static int r_Step_1c(struct SN_env * z); +static int r_Step_1b(struct SN_env * z); +static int r_Step_1a(struct SN_env * z); +static int r_R2(struct SN_env * z); +static int r_R1(struct SN_env * z); +static int r_shortv(struct SN_env * z); +static int r_mark_regions(struct SN_env * z); +static int r_postlude(struct SN_env * z); +static int r_prelude(struct SN_env * z); -extern struct SN_env * english_create_env(void); +extern struct SN_env *english_create_env(void); extern void english_close_env(struct SN_env * z); -static symbol s_0_0[5] = { 'g', 'e', 'n', 'e', 'r' }; +static symbol s_0_0[5] = {'g', 'e', 'n', 'e', 'r'}; static struct among a_0[1] = { -/* 0 */ { 5, s_0_0, -1, -1, 0} + /* 0 */ {5, s_0_0, -1, -1, 0} }; -static symbol s_1_0[3] = { 'i', 'e', 'd' }; -static symbol s_1_1[1] = { 's' }; -static symbol s_1_2[3] = { 'i', 'e', 's' }; -static symbol s_1_3[4] = { 's', 's', 'e', 's' }; -static symbol s_1_4[2] = { 's', 's' }; -static symbol s_1_5[2] = { 'u', 's' }; +static symbol s_1_0[3] = {'i', 'e', 'd'}; +static symbol s_1_1[1] = {'s'}; +static symbol s_1_2[3] = {'i', 'e', 's'}; +static symbol s_1_3[4] = {'s', 's', 'e', 's'}; +static symbol s_1_4[2] = {'s', 's'}; +static symbol s_1_5[2] = {'u', 's'}; static struct among a_1[6] = { -/* 0 */ { 3, s_1_0, -1, 2, 0}, -/* 1 */ { 1, s_1_1, -1, 3, 0}, -/* 2 */ { 3, s_1_2, 1, 2, 0}, -/* 3 */ { 4, s_1_3, 1, 1, 0}, -/* 4 */ { 2, s_1_4, 1, -1, 0}, -/* 5 */ { 2, s_1_5, 1, -1, 0} + /* 0 */ {3, s_1_0, -1, 2, 0}, + /* 1 */ {1, s_1_1, -1, 3, 0}, + /* 2 */ {3, s_1_2, 1, 2, 0}, + /* 3 */ {4, s_1_3, 1, 1, 0}, + /* 4 */ {2, s_1_4, 1, -1, 0}, + /* 5 */ {2, s_1_5, 1, -1, 0} }; -static symbol s_2_1[2] = { 'b', 'b' }; -static symbol s_2_2[2] = { 'd', 'd' }; -static symbol s_2_3[2] = { 'f', 'f' }; -static symbol s_2_4[2] = { 'g', 'g' }; -static symbol s_2_5[2] = { 'b', 'l' }; -static symbol s_2_6[2] = { 'm', 'm' }; -static symbol s_2_7[2] = { 'n', 'n' }; -static symbol s_2_8[2] = { 'p', 'p' }; -static symbol s_2_9[2] = { 'r', 'r' }; -static symbol s_2_10[2] = { 'a', 't' }; -static symbol s_2_11[2] = { 't', 't' }; -static symbol s_2_12[2] = { 'i', 'z' }; +static symbol s_2_1[2] = {'b', 'b'}; +static symbol s_2_2[2] = {'d', 'd'}; +static symbol s_2_3[2] = {'f', 'f'}; +static symbol s_2_4[2] = {'g', 'g'}; +static symbol s_2_5[2] = {'b', 'l'}; +static symbol s_2_6[2] = {'m', 'm'}; +static symbol s_2_7[2] = {'n', 'n'}; +static symbol s_2_8[2] = {'p', 'p'}; +static symbol s_2_9[2] = {'r', 'r'}; +static symbol s_2_10[2] = {'a', 't'}; +static symbol s_2_11[2] = {'t', 't'}; +static symbol s_2_12[2] = {'i', 'z'}; static struct among a_2[13] = { -/* 0 */ { 0, 0, -1, 3, 0}, -/* 1 */ { 2, s_2_1, 0, 2, 0}, -/* 2 */ { 2, s_2_2, 0, 2, 0}, -/* 3 */ { 2, s_2_3, 0, 2, 0}, -/* 4 */ { 2, s_2_4, 0, 2, 0}, -/* 5 */ { 2, s_2_5, 0, 1, 0}, -/* 6 */ { 2, s_2_6, 0, 2, 0}, -/* 7 */ { 2, s_2_7, 0, 2, 0}, -/* 8 */ { 2, s_2_8, 0, 2, 0}, -/* 9 */ { 2, s_2_9, 0, 2, 0}, -/* 10 */ { 2, s_2_10, 0, 1, 0}, -/* 11 */ { 2, s_2_11, 0, 2, 0}, -/* 12 */ { 2, s_2_12, 0, 1, 0} + /* 0 */ {0, 0, -1, 3, 0}, + /* 1 */ {2, s_2_1, 0, 2, 0}, + /* 2 */ {2, s_2_2, 0, 2, 0}, + /* 3 */ {2, s_2_3, 0, 2, 0}, + /* 4 */ {2, s_2_4, 0, 2, 0}, + /* 5 */ {2, s_2_5, 0, 1, 0}, + /* 6 */ {2, s_2_6, 0, 2, 0}, + /* 7 */ {2, s_2_7, 0, 2, 0}, + /* 8 */ {2, s_2_8, 0, 2, 0}, + /* 9 */ {2, s_2_9, 0, 2, 0}, + /* 10 */ {2, s_2_10, 0, 1, 0}, + /* 11 */ {2, s_2_11, 0, 2, 0}, + /* 12 */ {2, s_2_12, 0, 1, 0} }; -static symbol s_3_0[2] = { 'e', 'd' }; -static symbol s_3_1[3] = { 'e', 'e', 'd' }; -static symbol s_3_2[3] = { 'i', 'n', 'g' }; -static symbol s_3_3[4] = { 'e', 'd', 'l', 'y' }; -static symbol s_3_4[5] = { 'e', 'e', 'd', 'l', 'y' }; -static symbol s_3_5[5] = { 'i', 'n', 'g', 'l', 'y' }; +static symbol s_3_0[2] = {'e', 'd'}; +static symbol s_3_1[3] = {'e', 'e', 'd'}; +static symbol s_3_2[3] = {'i', 'n', 'g'}; +static symbol s_3_3[4] = {'e', 'd', 'l', 'y'}; +static symbol s_3_4[5] = {'e', 'e', 'd', 'l', 'y'}; +static symbol s_3_5[5] = {'i', 'n', 'g', 'l', 'y'}; static struct among a_3[6] = { -/* 0 */ { 2, s_3_0, -1, 2, 0}, -/* 1 */ { 3, s_3_1, 0, 1, 0}, -/* 2 */ { 3, s_3_2, -1, 2, 0}, -/* 3 */ { 4, s_3_3, -1, 2, 0}, -/* 4 */ { 5, s_3_4, 3, 1, 0}, -/* 5 */ { 5, s_3_5, -1, 2, 0} + /* 0 */ {2, s_3_0, -1, 2, 0}, + /* 1 */ {3, s_3_1, 0, 1, 0}, + /* 2 */ {3, s_3_2, -1, 2, 0}, + /* 3 */ {4, s_3_3, -1, 2, 0}, + /* 4 */ {5, s_3_4, 3, 1, 0}, + /* 5 */ {5, s_3_5, -1, 2, 0} }; -static symbol s_4_0[4] = { 'a', 'n', 'c', 'i' }; -static symbol s_4_1[4] = { 'e', 'n', 'c', 'i' }; -static symbol s_4_2[3] = { 'o', 'g', 'i' }; -static symbol s_4_3[2] = { 'l', 'i' }; -static symbol s_4_4[3] = { 'b', 'l', 'i' }; -static symbol s_4_5[4] = { 'a', 'b', 'l', 'i' }; -static symbol s_4_6[4] = { 'a', 'l', 'l', 'i' }; -static symbol s_4_7[5] = { 'f', 'u', 'l', 'l', 'i' }; -static symbol s_4_8[6] = { 'l', 'e', 's', 's', 'l', 'i' }; -static symbol s_4_9[5] = { 'o', 'u', 's', 'l', 'i' }; -static symbol s_4_10[5] = { 'e', 'n', 't', 'l', 'i' }; -static symbol s_4_11[5] = { 'a', 'l', 'i', 't', 'i' }; -static symbol s_4_12[6] = { 'b', 'i', 'l', 'i', 't', 'i' }; -static symbol s_4_13[5] = { 'i', 'v', 'i', 't', 'i' }; -static symbol s_4_14[6] = { 't', 'i', 'o', 'n', 'a', 'l' }; -static symbol s_4_15[7] = { 'a', 't', 'i', 'o', 'n', 'a', 'l' }; -static symbol s_4_16[5] = { 'a', 'l', 'i', 's', 'm' }; -static symbol s_4_17[5] = { 'a', 't', 'i', 'o', 'n' }; -static symbol s_4_18[7] = { 'i', 'z', 'a', 't', 'i', 'o', 'n' }; -static symbol s_4_19[4] = { 'i', 'z', 'e', 'r' }; -static symbol s_4_20[4] = { 'a', 't', 'o', 'r' }; -static symbol s_4_21[7] = { 'i', 'v', 'e', 'n', 'e', 's', 's' }; -static symbol s_4_22[7] = { 'f', 'u', 'l', 'n', 'e', 's', 's' }; -static symbol s_4_23[7] = { 'o', 'u', 's', 'n', 'e', 's', 's' }; +static symbol s_4_0[4] = {'a', 'n', 'c', 'i'}; +static symbol s_4_1[4] = {'e', 'n', 'c', 'i'}; +static symbol s_4_2[3] = {'o', 'g', 'i'}; +static symbol s_4_3[2] = {'l', 'i'}; +static symbol s_4_4[3] = {'b', 'l', 'i'}; +static symbol s_4_5[4] = {'a', 'b', 'l', 'i'}; +static symbol s_4_6[4] = {'a', 'l', 'l', 'i'}; +static symbol s_4_7[5] = {'f', 'u', 'l', 'l', 'i'}; +static symbol s_4_8[6] = {'l', 'e', 's', 's', 'l', 'i'}; +static symbol s_4_9[5] = {'o', 'u', 's', 'l', 'i'}; +static symbol s_4_10[5] = {'e', 'n', 't', 'l', 'i'}; +static symbol s_4_11[5] = {'a', 'l', 'i', 't', 'i'}; +static symbol s_4_12[6] = {'b', 'i', 'l', 'i', 't', 'i'}; +static symbol s_4_13[5] = {'i', 'v', 'i', 't', 'i'}; +static symbol s_4_14[6] = {'t', 'i', 'o', 'n', 'a', 'l'}; +static symbol s_4_15[7] = {'a', 't', 'i', 'o', 'n', 'a', 'l'}; +static symbol s_4_16[5] = {'a', 'l', 'i', 's', 'm'}; +static symbol s_4_17[5] = {'a', 't', 'i', 'o', 'n'}; +static symbol s_4_18[7] = {'i', 'z', 'a', 't', 'i', 'o', 'n'}; +static symbol s_4_19[4] = {'i', 'z', 'e', 'r'}; +static symbol s_4_20[4] = {'a', 't', 'o', 'r'}; +static symbol s_4_21[7] = {'i', 'v', 'e', 'n', 'e', 's', 's'}; +static symbol s_4_22[7] = {'f', 'u', 'l', 'n', 'e', 's', 's'}; +static symbol s_4_23[7] = {'o', 'u', 's', 'n', 'e', 's', 's'}; static struct among a_4[24] = { -/* 0 */ { 4, s_4_0, -1, 3, 0}, -/* 1 */ { 4, s_4_1, -1, 2, 0}, -/* 2 */ { 3, s_4_2, -1, 13, 0}, -/* 3 */ { 2, s_4_3, -1, 16, 0}, -/* 4 */ { 3, s_4_4, 3, 12, 0}, -/* 5 */ { 4, s_4_5, 4, 4, 0}, -/* 6 */ { 4, s_4_6, 3, 8, 0}, -/* 7 */ { 5, s_4_7, 3, 14, 0}, -/* 8 */ { 6, s_4_8, 3, 15, 0}, -/* 9 */ { 5, s_4_9, 3, 10, 0}, -/* 10 */ { 5, s_4_10, 3, 5, 0}, -/* 11 */ { 5, s_4_11, -1, 8, 0}, -/* 12 */ { 6, s_4_12, -1, 12, 0}, -/* 13 */ { 5, s_4_13, -1, 11, 0}, -/* 14 */ { 6, s_4_14, -1, 1, 0}, -/* 15 */ { 7, s_4_15, 14, 7, 0}, -/* 16 */ { 5, s_4_16, -1, 8, 0}, -/* 17 */ { 5, s_4_17, -1, 7, 0}, -/* 18 */ { 7, s_4_18, 17, 6, 0}, -/* 19 */ { 4, s_4_19, -1, 6, 0}, -/* 20 */ { 4, s_4_20, -1, 7, 0}, -/* 21 */ { 7, s_4_21, -1, 11, 0}, -/* 22 */ { 7, s_4_22, -1, 9, 0}, -/* 23 */ { 7, s_4_23, -1, 10, 0} + /* 0 */ {4, s_4_0, -1, 3, 0}, + /* 1 */ {4, s_4_1, -1, 2, 0}, + /* 2 */ {3, s_4_2, -1, 13, 0}, + /* 3 */ {2, s_4_3, -1, 16, 0}, + /* 4 */ {3, s_4_4, 3, 12, 0}, + /* 5 */ {4, s_4_5, 4, 4, 0}, + /* 6 */ {4, s_4_6, 3, 8, 0}, + /* 7 */ {5, s_4_7, 3, 14, 0}, + /* 8 */ {6, s_4_8, 3, 15, 0}, + /* 9 */ {5, s_4_9, 3, 10, 0}, + /* 10 */ {5, s_4_10, 3, 5, 0}, + /* 11 */ {5, s_4_11, -1, 8, 0}, + /* 12 */ {6, s_4_12, -1, 12, 0}, + /* 13 */ {5, s_4_13, -1, 11, 0}, + /* 14 */ {6, s_4_14, -1, 1, 0}, + /* 15 */ {7, s_4_15, 14, 7, 0}, + /* 16 */ {5, s_4_16, -1, 8, 0}, + /* 17 */ {5, s_4_17, -1, 7, 0}, + /* 18 */ {7, s_4_18, 17, 6, 0}, + /* 19 */ {4, s_4_19, -1, 6, 0}, + /* 20 */ {4, s_4_20, -1, 7, 0}, + /* 21 */ {7, s_4_21, -1, 11, 0}, + /* 22 */ {7, s_4_22, -1, 9, 0}, + /* 23 */ {7, s_4_23, -1, 10, 0} }; -static symbol s_5_0[5] = { 'i', 'c', 'a', 't', 'e' }; -static symbol s_5_1[5] = { 'a', 't', 'i', 'v', 'e' }; -static symbol s_5_2[5] = { 'a', 'l', 'i', 'z', 'e' }; -static symbol s_5_3[5] = { 'i', 'c', 'i', 't', 'i' }; -static symbol s_5_4[4] = { 'i', 'c', 'a', 'l' }; -static symbol s_5_5[6] = { 't', 'i', 'o', 'n', 'a', 'l' }; -static symbol s_5_6[7] = { 'a', 't', 'i', 'o', 'n', 'a', 'l' }; -static symbol s_5_7[3] = { 'f', 'u', 'l' }; -static symbol s_5_8[4] = { 'n', 'e', 's', 's' }; +static symbol s_5_0[5] = {'i', 'c', 'a', 't', 'e'}; +static symbol s_5_1[5] = {'a', 't', 'i', 'v', 'e'}; +static symbol s_5_2[5] = {'a', 'l', 'i', 'z', 'e'}; +static symbol s_5_3[5] = {'i', 'c', 'i', 't', 'i'}; +static symbol s_5_4[4] = {'i', 'c', 'a', 'l'}; +static symbol s_5_5[6] = {'t', 'i', 'o', 'n', 'a', 'l'}; +static symbol s_5_6[7] = {'a', 't', 'i', 'o', 'n', 'a', 'l'}; +static symbol s_5_7[3] = {'f', 'u', 'l'}; +static symbol s_5_8[4] = {'n', 'e', 's', 's'}; static struct among a_5[9] = { -/* 0 */ { 5, s_5_0, -1, 4, 0}, -/* 1 */ { 5, s_5_1, -1, 6, 0}, -/* 2 */ { 5, s_5_2, -1, 3, 0}, -/* 3 */ { 5, s_5_3, -1, 4, 0}, -/* 4 */ { 4, s_5_4, -1, 4, 0}, -/* 5 */ { 6, s_5_5, -1, 1, 0}, -/* 6 */ { 7, s_5_6, 5, 2, 0}, -/* 7 */ { 3, s_5_7, -1, 5, 0}, -/* 8 */ { 4, s_5_8, -1, 5, 0} + /* 0 */ {5, s_5_0, -1, 4, 0}, + /* 1 */ {5, s_5_1, -1, 6, 0}, + /* 2 */ {5, s_5_2, -1, 3, 0}, + /* 3 */ {5, s_5_3, -1, 4, 0}, + /* 4 */ {4, s_5_4, -1, 4, 0}, + /* 5 */ {6, s_5_5, -1, 1, 0}, + /* 6 */ {7, s_5_6, 5, 2, 0}, + /* 7 */ {3, s_5_7, -1, 5, 0}, + /* 8 */ {4, s_5_8, -1, 5, 0} }; -static symbol s_6_0[2] = { 'i', 'c' }; -static symbol s_6_1[4] = { 'a', 'n', 'c', 'e' }; -static symbol s_6_2[4] = { 'e', 'n', 'c', 'e' }; -static symbol s_6_3[4] = { 'a', 'b', 'l', 'e' }; -static symbol s_6_4[4] = { 'i', 'b', 'l', 'e' }; -static symbol s_6_5[3] = { 'a', 't', 'e' }; -static symbol s_6_6[3] = { 'i', 'v', 'e' }; -static symbol s_6_7[3] = { 'i', 'z', 'e' }; -static symbol s_6_8[3] = { 'i', 't', 'i' }; -static symbol s_6_9[2] = { 'a', 'l' }; -static symbol s_6_10[3] = { 'i', 's', 'm' }; -static symbol s_6_11[3] = { 'i', 'o', 'n' }; -static symbol s_6_12[2] = { 'e', 'r' }; -static symbol s_6_13[3] = { 'o', 'u', 's' }; -static symbol s_6_14[3] = { 'a', 'n', 't' }; -static symbol s_6_15[3] = { 'e', 'n', 't' }; -static symbol s_6_16[4] = { 'm', 'e', 'n', 't' }; -static symbol s_6_17[5] = { 'e', 'm', 'e', 'n', 't' }; +static symbol s_6_0[2] = {'i', 'c'}; +static symbol s_6_1[4] = {'a', 'n', 'c', 'e'}; +static symbol s_6_2[4] = {'e', 'n', 'c', 'e'}; +static symbol s_6_3[4] = {'a', 'b', 'l', 'e'}; +static symbol s_6_4[4] = {'i', 'b', 'l', 'e'}; +static symbol s_6_5[3] = {'a', 't', 'e'}; +static symbol s_6_6[3] = {'i', 'v', 'e'}; +static symbol s_6_7[3] = {'i', 'z', 'e'}; +static symbol s_6_8[3] = {'i', 't', 'i'}; +static symbol s_6_9[2] = {'a', 'l'}; +static symbol s_6_10[3] = {'i', 's', 'm'}; +static symbol s_6_11[3] = {'i', 'o', 'n'}; +static symbol s_6_12[2] = {'e', 'r'}; +static symbol s_6_13[3] = {'o', 'u', 's'}; +static symbol s_6_14[3] = {'a', 'n', 't'}; +static symbol s_6_15[3] = {'e', 'n', 't'}; +static symbol s_6_16[4] = {'m', 'e', 'n', 't'}; +static symbol s_6_17[5] = {'e', 'm', 'e', 'n', 't'}; static struct among a_6[18] = { -/* 0 */ { 2, s_6_0, -1, 1, 0}, -/* 1 */ { 4, s_6_1, -1, 1, 0}, -/* 2 */ { 4, s_6_2, -1, 1, 0}, -/* 3 */ { 4, s_6_3, -1, 1, 0}, -/* 4 */ { 4, s_6_4, -1, 1, 0}, -/* 5 */ { 3, s_6_5, -1, 1, 0}, -/* 6 */ { 3, s_6_6, -1, 1, 0}, -/* 7 */ { 3, s_6_7, -1, 1, 0}, -/* 8 */ { 3, s_6_8, -1, 1, 0}, -/* 9 */ { 2, s_6_9, -1, 1, 0}, -/* 10 */ { 3, s_6_10, -1, 1, 0}, -/* 11 */ { 3, s_6_11, -1, 2, 0}, -/* 12 */ { 2, s_6_12, -1, 1, 0}, -/* 13 */ { 3, s_6_13, -1, 1, 0}, -/* 14 */ { 3, s_6_14, -1, 1, 0}, -/* 15 */ { 3, s_6_15, -1, 1, 0}, -/* 16 */ { 4, s_6_16, 15, 1, 0}, -/* 17 */ { 5, s_6_17, 16, 1, 0} + /* 0 */ {2, s_6_0, -1, 1, 0}, + /* 1 */ {4, s_6_1, -1, 1, 0}, + /* 2 */ {4, s_6_2, -1, 1, 0}, + /* 3 */ {4, s_6_3, -1, 1, 0}, + /* 4 */ {4, s_6_4, -1, 1, 0}, + /* 5 */ {3, s_6_5, -1, 1, 0}, + /* 6 */ {3, s_6_6, -1, 1, 0}, + /* 7 */ {3, s_6_7, -1, 1, 0}, + /* 8 */ {3, s_6_8, -1, 1, 0}, + /* 9 */ {2, s_6_9, -1, 1, 0}, + /* 10 */ {3, s_6_10, -1, 1, 0}, + /* 11 */ {3, s_6_11, -1, 2, 0}, + /* 12 */ {2, s_6_12, -1, 1, 0}, + /* 13 */ {3, s_6_13, -1, 1, 0}, + /* 14 */ {3, s_6_14, -1, 1, 0}, + /* 15 */ {3, s_6_15, -1, 1, 0}, + /* 16 */ {4, s_6_16, 15, 1, 0}, + /* 17 */ {5, s_6_17, 16, 1, 0} }; -static symbol s_7_0[1] = { 'e' }; -static symbol s_7_1[1] = { 'l' }; +static symbol s_7_0[1] = {'e'}; +static symbol s_7_1[1] = {'l'}; static struct among a_7[2] = { -/* 0 */ { 1, s_7_0, -1, 1, 0}, -/* 1 */ { 1, s_7_1, -1, 2, 0} + /* 0 */ {1, s_7_0, -1, 1, 0}, + /* 1 */ {1, s_7_1, -1, 2, 0} }; -static symbol s_8_0[7] = { 's', 'u', 'c', 'c', 'e', 'e', 'd' }; -static symbol s_8_1[7] = { 'p', 'r', 'o', 'c', 'e', 'e', 'd' }; -static symbol s_8_2[6] = { 'e', 'x', 'c', 'e', 'e', 'd' }; -static symbol s_8_3[7] = { 'c', 'a', 'n', 'n', 'i', 'n', 'g' }; -static symbol s_8_4[6] = { 'i', 'n', 'n', 'i', 'n', 'g' }; -static symbol s_8_5[7] = { 'e', 'a', 'r', 'r', 'i', 'n', 'g' }; -static symbol s_8_6[7] = { 'h', 'e', 'r', 'r', 'i', 'n', 'g' }; -static symbol s_8_7[6] = { 'o', 'u', 't', 'i', 'n', 'g' }; +static symbol s_8_0[7] = {'s', 'u', 'c', 'c', 'e', 'e', 'd'}; +static symbol s_8_1[7] = {'p', 'r', 'o', 'c', 'e', 'e', 'd'}; +static symbol s_8_2[6] = {'e', 'x', 'c', 'e', 'e', 'd'}; +static symbol s_8_3[7] = {'c', 'a', 'n', 'n', 'i', 'n', 'g'}; +static symbol s_8_4[6] = {'i', 'n', 'n', 'i', 'n', 'g'}; +static symbol s_8_5[7] = {'e', 'a', 'r', 'r', 'i', 'n', 'g'}; +static symbol s_8_6[7] = {'h', 'e', 'r', 'r', 'i', 'n', 'g'}; +static symbol s_8_7[6] = {'o', 'u', 't', 'i', 'n', 'g'}; static struct among a_8[8] = { -/* 0 */ { 7, s_8_0, -1, -1, 0}, -/* 1 */ { 7, s_8_1, -1, -1, 0}, -/* 2 */ { 6, s_8_2, -1, -1, 0}, -/* 3 */ { 7, s_8_3, -1, -1, 0}, -/* 4 */ { 6, s_8_4, -1, -1, 0}, -/* 5 */ { 7, s_8_5, -1, -1, 0}, -/* 6 */ { 7, s_8_6, -1, -1, 0}, -/* 7 */ { 6, s_8_7, -1, -1, 0} + /* 0 */ {7, s_8_0, -1, -1, 0}, + /* 1 */ {7, s_8_1, -1, -1, 0}, + /* 2 */ {6, s_8_2, -1, -1, 0}, + /* 3 */ {7, s_8_3, -1, -1, 0}, + /* 4 */ {6, s_8_4, -1, -1, 0}, + /* 5 */ {7, s_8_5, -1, -1, 0}, + /* 6 */ {7, s_8_6, -1, -1, 0}, + /* 7 */ {6, s_8_7, -1, -1, 0} }; -static symbol s_9_0[5] = { 'a', 'n', 'd', 'e', 's' }; -static symbol s_9_1[5] = { 'a', 't', 'l', 'a', 's' }; -static symbol s_9_2[4] = { 'b', 'i', 'a', 's' }; -static symbol s_9_3[6] = { 'c', 'o', 's', 'm', 'o', 's' }; -static symbol s_9_4[5] = { 'd', 'y', 'i', 'n', 'g' }; -static symbol s_9_5[5] = { 'e', 'a', 'r', 'l', 'y' }; -static symbol s_9_6[6] = { 'g', 'e', 'n', 't', 'l', 'y' }; -static symbol s_9_7[4] = { 'h', 'o', 'w', 'e' }; -static symbol s_9_8[4] = { 'i', 'd', 'l', 'y' }; -static symbol s_9_9[5] = { 'l', 'y', 'i', 'n', 'g' }; -static symbol s_9_10[4] = { 'n', 'e', 'w', 's' }; -static symbol s_9_11[4] = { 'o', 'n', 'l', 'y' }; -static symbol s_9_12[6] = { 's', 'i', 'n', 'g', 'l', 'y' }; -static symbol s_9_13[5] = { 's', 'k', 'i', 'e', 's' }; -static symbol s_9_14[4] = { 's', 'k', 'i', 's' }; -static symbol s_9_15[3] = { 's', 'k', 'y' }; -static symbol s_9_16[5] = { 't', 'y', 'i', 'n', 'g' }; -static symbol s_9_17[4] = { 'u', 'g', 'l', 'y' }; +static symbol s_9_0[5] = {'a', 'n', 'd', 'e', 's'}; +static symbol s_9_1[5] = {'a', 't', 'l', 'a', 's'}; +static symbol s_9_2[4] = {'b', 'i', 'a', 's'}; +static symbol s_9_3[6] = {'c', 'o', 's', 'm', 'o', 's'}; +static symbol s_9_4[5] = {'d', 'y', 'i', 'n', 'g'}; +static symbol s_9_5[5] = {'e', 'a', 'r', 'l', 'y'}; +static symbol s_9_6[6] = {'g', 'e', 'n', 't', 'l', 'y'}; +static symbol s_9_7[4] = {'h', 'o', 'w', 'e'}; +static symbol s_9_8[4] = {'i', 'd', 'l', 'y'}; +static symbol s_9_9[5] = {'l', 'y', 'i', 'n', 'g'}; +static symbol s_9_10[4] = {'n', 'e', 'w', 's'}; +static symbol s_9_11[4] = {'o', 'n', 'l', 'y'}; +static symbol s_9_12[6] = {'s', 'i', 'n', 'g', 'l', 'y'}; +static symbol s_9_13[5] = {'s', 'k', 'i', 'e', 's'}; +static symbol s_9_14[4] = {'s', 'k', 'i', 's'}; +static symbol s_9_15[3] = {'s', 'k', 'y'}; +static symbol s_9_16[5] = {'t', 'y', 'i', 'n', 'g'}; +static symbol s_9_17[4] = {'u', 'g', 'l', 'y'}; static struct among a_9[18] = { -/* 0 */ { 5, s_9_0, -1, -1, 0}, -/* 1 */ { 5, s_9_1, -1, -1, 0}, -/* 2 */ { 4, s_9_2, -1, -1, 0}, -/* 3 */ { 6, s_9_3, -1, -1, 0}, -/* 4 */ { 5, s_9_4, -1, 3, 0}, -/* 5 */ { 5, s_9_5, -1, 9, 0}, -/* 6 */ { 6, s_9_6, -1, 7, 0}, -/* 7 */ { 4, s_9_7, -1, -1, 0}, -/* 8 */ { 4, s_9_8, -1, 6, 0}, -/* 9 */ { 5, s_9_9, -1, 4, 0}, -/* 10 */ { 4, s_9_10, -1, -1, 0}, -/* 11 */ { 4, s_9_11, -1, 10, 0}, -/* 12 */ { 6, s_9_12, -1, 11, 0}, -/* 13 */ { 5, s_9_13, -1, 2, 0}, -/* 14 */ { 4, s_9_14, -1, 1, 0}, -/* 15 */ { 3, s_9_15, -1, -1, 0}, -/* 16 */ { 5, s_9_16, -1, 5, 0}, -/* 17 */ { 4, s_9_17, -1, 8, 0} + /* 0 */ {5, s_9_0, -1, -1, 0}, + /* 1 */ {5, s_9_1, -1, -1, 0}, + /* 2 */ {4, s_9_2, -1, -1, 0}, + /* 3 */ {6, s_9_3, -1, -1, 0}, + /* 4 */ {5, s_9_4, -1, 3, 0}, + /* 5 */ {5, s_9_5, -1, 9, 0}, + /* 6 */ {6, s_9_6, -1, 7, 0}, + /* 7 */ {4, s_9_7, -1, -1, 0}, + /* 8 */ {4, s_9_8, -1, 6, 0}, + /* 9 */ {5, s_9_9, -1, 4, 0}, + /* 10 */ {4, s_9_10, -1, -1, 0}, + /* 11 */ {4, s_9_11, -1, 10, 0}, + /* 12 */ {6, s_9_12, -1, 11, 0}, + /* 13 */ {5, s_9_13, -1, 2, 0}, + /* 14 */ {4, s_9_14, -1, 1, 0}, + /* 15 */ {3, s_9_15, -1, -1, 0}, + /* 16 */ {5, s_9_16, -1, 5, 0}, + /* 17 */ {4, s_9_17, -1, 8, 0} }; -static unsigned char g_v[] = { 17, 65, 16, 1 }; +static unsigned char g_v[] = {17, 65, 16, 1}; -static unsigned char g_v_WXY[] = { 1, 17, 65, 208, 1 }; +static unsigned char g_v_WXY[] = {1, 17, 65, 208, 1}; -static unsigned char g_valid_LI[] = { 55, 141, 2 }; +static unsigned char g_valid_LI[] = {55, 141, 2}; -static symbol s_0[] = { 'y' }; -static symbol s_1[] = { 'Y' }; -static symbol s_2[] = { 'y' }; -static symbol s_3[] = { 'Y' }; -static symbol s_4[] = { 's', 's' }; -static symbol s_5[] = { 'i', 'e' }; -static symbol s_6[] = { 'i' }; -static symbol s_7[] = { 'e', 'e' }; -static symbol s_8[] = { 'e' }; -static symbol s_9[] = { 'e' }; -static symbol s_10[] = { 'y' }; -static symbol s_11[] = { 'Y' }; -static symbol s_12[] = { 'i' }; -static symbol s_13[] = { 't', 'i', 'o', 'n' }; -static symbol s_14[] = { 'e', 'n', 'c', 'e' }; -static symbol s_15[] = { 'a', 'n', 'c', 'e' }; -static symbol s_16[] = { 'a', 'b', 'l', 'e' }; -static symbol s_17[] = { 'e', 'n', 't' }; -static symbol s_18[] = { 'i', 'z', 'e' }; -static symbol s_19[] = { 'a', 't', 'e' }; -static symbol s_20[] = { 'a', 'l' }; -static symbol s_21[] = { 'f', 'u', 'l' }; -static symbol s_22[] = { 'o', 'u', 's' }; -static symbol s_23[] = { 'i', 'v', 'e' }; -static symbol s_24[] = { 'b', 'l', 'e' }; -static symbol s_25[] = { 'l' }; -static symbol s_26[] = { 'o', 'g' }; -static symbol s_27[] = { 'f', 'u', 'l' }; -static symbol s_28[] = { 'l', 'e', 's', 's' }; -static symbol s_29[] = { 't', 'i', 'o', 'n' }; -static symbol s_30[] = { 'a', 't', 'e' }; -static symbol s_31[] = { 'a', 'l' }; -static symbol s_32[] = { 'i', 'c' }; -static symbol s_33[] = { 's' }; -static symbol s_34[] = { 't' }; -static symbol s_35[] = { 'l' }; -static symbol s_36[] = { 's', 'k', 'i' }; -static symbol s_37[] = { 's', 'k', 'y' }; -static symbol s_38[] = { 'd', 'i', 'e' }; -static symbol s_39[] = { 'l', 'i', 'e' }; -static symbol s_40[] = { 't', 'i', 'e' }; -static symbol s_41[] = { 'i', 'd', 'l' }; -static symbol s_42[] = { 'g', 'e', 'n', 't', 'l' }; -static symbol s_43[] = { 'u', 'g', 'l', 'i' }; -static symbol s_44[] = { 'e', 'a', 'r', 'l', 'i' }; -static symbol s_45[] = { 'o', 'n', 'l', 'i' }; -static symbol s_46[] = { 's', 'i', 'n', 'g', 'l' }; -static symbol s_47[] = { 'Y' }; -static symbol s_48[] = { 'y' }; +static symbol s_0[] = {'y'}; +static symbol s_1[] = {'Y'}; +static symbol s_2[] = {'y'}; +static symbol s_3[] = {'Y'}; +static symbol s_4[] = {'s', 's'}; +static symbol s_5[] = {'i', 'e'}; +static symbol s_6[] = {'i'}; +static symbol s_7[] = {'e', 'e'}; +static symbol s_8[] = {'e'}; +static symbol s_9[] = {'e'}; +static symbol s_10[] = {'y'}; +static symbol s_11[] = {'Y'}; +static symbol s_12[] = {'i'}; +static symbol s_13[] = {'t', 'i', 'o', 'n'}; +static symbol s_14[] = {'e', 'n', 'c', 'e'}; +static symbol s_15[] = {'a', 'n', 'c', 'e'}; +static symbol s_16[] = {'a', 'b', 'l', 'e'}; +static symbol s_17[] = {'e', 'n', 't'}; +static symbol s_18[] = {'i', 'z', 'e'}; +static symbol s_19[] = {'a', 't', 'e'}; +static symbol s_20[] = {'a', 'l'}; +static symbol s_21[] = {'f', 'u', 'l'}; +static symbol s_22[] = {'o', 'u', 's'}; +static symbol s_23[] = {'i', 'v', 'e'}; +static symbol s_24[] = {'b', 'l', 'e'}; +static symbol s_25[] = {'l'}; +static symbol s_26[] = {'o', 'g'}; +static symbol s_27[] = {'f', 'u', 'l'}; +static symbol s_28[] = {'l', 'e', 's', 's'}; +static symbol s_29[] = {'t', 'i', 'o', 'n'}; +static symbol s_30[] = {'a', 't', 'e'}; +static symbol s_31[] = {'a', 'l'}; +static symbol s_32[] = {'i', 'c'}; +static symbol s_33[] = {'s'}; +static symbol s_34[] = {'t'}; +static symbol s_35[] = {'l'}; +static symbol s_36[] = {'s', 'k', 'i'}; +static symbol s_37[] = {'s', 'k', 'y'}; +static symbol s_38[] = {'d', 'i', 'e'}; +static symbol s_39[] = {'l', 'i', 'e'}; +static symbol s_40[] = {'t', 'i', 'e'}; +static symbol s_41[] = {'i', 'd', 'l'}; +static symbol s_42[] = {'g', 'e', 'n', 't', 'l'}; +static symbol s_43[] = {'u', 'g', 'l', 'i'}; +static symbol s_44[] = {'e', 'a', 'r', 'l', 'i'}; +static symbol s_45[] = {'o', 'n', 'l', 'i'}; +static symbol s_46[] = {'s', 'i', 'n', 'g', 'l'}; +static symbol s_47[] = {'Y'}; +static symbol s_48[] = {'y'}; -static int r_prelude(struct SN_env * z) { - z->B[0] = 0; /* unset Y_found, line 24 */ - { int c = z->c; /* do, line 25 */ - z->bra = z->c; /* [, line 25 */ - if (!(eq_s(z, 1, s_0))) goto lab0; - z->ket = z->c; /* ], line 25 */ - if (!(in_grouping(z, g_v, 97, 121))) goto lab0; - slice_from_s(z, 1, s_1); /* <-, line 25 */ - z->B[0] = 1; /* set Y_found, line 25 */ - lab0: - z->c = c; - } - { int c = z->c; /* do, line 26 */ - while(1) { /* repeat, line 26 */ - int c = z->c; - while(1) { /* goto, line 26 */ - int c = z->c; - if (!(in_grouping(z, g_v, 97, 121))) goto lab3; - z->bra = z->c; /* [, line 26 */ - if (!(eq_s(z, 1, s_2))) goto lab3; - z->ket = z->c; /* ], line 26 */ - z->c = c; - break; - lab3: - z->c = c; - if (z->c >= z->l) goto lab2; - z->c++; - } - slice_from_s(z, 1, s_3); /* <-, line 26 */ - z->B[0] = 1; /* set Y_found, line 26 */ - continue; - lab2: - z->c = c; - break; - } - z->c = c; - } - return 1; -} +static int +r_prelude(struct SN_env * z) +{ + z->B[0] = 0; /* unset Y_found, line 24 */ + { + int c = z->c; /* do, line 25 */ -static int r_mark_regions(struct SN_env * z) { - z->I[0] = z->l; - z->I[1] = z->l; - { int c = z->c; /* do, line 32 */ - { int c = z->c; /* or, line 36 */ - if (!(find_among(z, a_0, 1))) goto lab2; /* among, line 33 */ - goto lab1; - lab2: - z->c = c; - while(1) { /* gopast, line 36 */ - if (!(in_grouping(z, g_v, 97, 121))) goto lab3; - break; - lab3: - if (z->c >= z->l) goto lab0; - z->c++; - } - while(1) { /* gopast, line 36 */ - if (!(out_grouping(z, g_v, 97, 121))) goto lab4; - break; - lab4: - if (z->c >= z->l) goto lab0; - z->c++; - } - } - lab1: - z->I[0] = z->c; /* setmark p1, line 37 */ - while(1) { /* gopast, line 38 */ - if (!(in_grouping(z, g_v, 97, 121))) goto lab5; - break; - lab5: - if (z->c >= z->l) goto lab0; - z->c++; - } - while(1) { /* gopast, line 38 */ - if (!(out_grouping(z, g_v, 97, 121))) goto lab6; - break; - lab6: - if (z->c >= z->l) goto lab0; - z->c++; - } - z->I[1] = z->c; /* setmark p2, line 38 */ - lab0: - z->c = c; - } - return 1; -} - -static int r_shortv(struct SN_env * z) { - { int m = z->l - z->c; /* or, line 46 */ - if (!(out_grouping_b(z, g_v_WXY, 89, 121))) goto lab1; - if (!(in_grouping_b(z, g_v, 97, 121))) goto lab1; - if (!(out_grouping_b(z, g_v, 97, 121))) goto lab1; - goto lab0; - lab1: - z->c = z->l - m; - if (!(out_grouping_b(z, g_v, 97, 121))) return 0; - if (!(in_grouping_b(z, g_v, 97, 121))) return 0; - if (z->c > z->lb) return 0; /* atlimit, line 47 */ - } + z->bra = z->c; /* [, line 25 */ + if (!(eq_s(z, 1, s_0))) + goto lab0; + z->ket = z->c; /* ], line 25 */ + if (!(in_grouping(z, g_v, 97, 121))) + goto lab0; + slice_from_s(z, 1, s_1); /* <-, line 25 */ + z->B[0] = 1; /* set Y_found, line 25 */ lab0: - return 1; + z->c = c; + } + { + int c = z->c; /* do, line 26 */ + + while (1) + { /* repeat, line 26 */ + int c = z->c; + + while (1) + { /* goto, line 26 */ + int c = z->c; + + if (!(in_grouping(z, g_v, 97, 121))) + goto lab3; + z->bra = z->c; /* [, line 26 */ + if (!(eq_s(z, 1, s_2))) + goto lab3; + z->ket = z->c; /* ], line 26 */ + z->c = c; + break; + lab3: + z->c = c; + if (z->c >= z->l) + goto lab2; + z->c++; + } + slice_from_s(z, 1, s_3); /* <-, line 26 */ + z->B[0] = 1; /* set Y_found, line 26 */ + continue; + lab2: + z->c = c; + break; + } + z->c = c; + } + return 1; } -static int r_R1(struct SN_env * z) { - if (!(z->I[0] <= z->c)) return 0; - return 1; -} +static int +r_mark_regions(struct SN_env * z) +{ + z->I[0] = z->l; + z->I[1] = z->l; + { + int c = z->c; /* do, line 32 */ -static int r_R2(struct SN_env * z) { - if (!(z->I[1] <= z->c)) return 0; - return 1; -} + { + int c = z->c; /* or, line 36 */ -static int r_Step_1a(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 54 */ - among_var = find_among_b(z, a_1, 6); /* substring, line 54 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 54 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_from_s(z, 2, s_4); /* <-, line 55 */ - break; - case 2: - { int m = z->l - z->c; /* or, line 57 */ - if (z->c <= z->lb) goto lab1; - z->c--; /* next, line 57 */ - if (z->c > z->lb) goto lab1; /* atlimit, line 57 */ - slice_from_s(z, 2, s_5); /* <-, line 57 */ - goto lab0; - lab1: - z->c = z->l - m; - slice_from_s(z, 1, s_6); /* <-, line 57 */ - } - lab0: - break; - case 3: - if (z->c <= z->lb) return 0; - z->c--; /* next, line 58 */ - while(1) { /* gopast, line 58 */ - if (!(in_grouping_b(z, g_v, 97, 121))) goto lab2; - break; - lab2: - if (z->c <= z->lb) return 0; - z->c--; - } - slice_del(z); /* delete, line 58 */ - break; - } - return 1; -} - -static int r_Step_1b(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 64 */ - among_var = find_among_b(z, a_3, 6); /* substring, line 64 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 64 */ - switch(among_var) { - case 0: return 0; - case 1: - if (!r_R1(z)) return 0; /* call R1, line 66 */ - slice_from_s(z, 2, s_7); /* <-, line 66 */ - break; - case 2: - { int m_test = z->l - z->c; /* test, line 69 */ - while(1) { /* gopast, line 69 */ - if (!(in_grouping_b(z, g_v, 97, 121))) goto lab0; - break; - lab0: - if (z->c <= z->lb) return 0; - z->c--; - } - z->c = z->l - m_test; - } - slice_del(z); /* delete, line 69 */ - { int m_test = z->l - z->c; /* test, line 70 */ - among_var = find_among_b(z, a_2, 13); /* substring, line 70 */ - if (!(among_var)) return 0; - z->c = z->l - m_test; - } - switch(among_var) { - case 0: return 0; - case 1: - { int c = z->c; - insert_s(z, z->c, z->c, 1, s_8); /* <+, line 72 */ - z->c = c; - } - break; - case 2: - z->ket = z->c; /* [, line 75 */ - if (z->c <= z->lb) return 0; - z->c--; /* next, line 75 */ - z->bra = z->c; /* ], line 75 */ - slice_del(z); /* delete, line 75 */ - break; - case 3: - if (z->c != z->I[0]) return 0; /* atmark, line 76 */ - { int m_test = z->l - z->c; /* test, line 76 */ - if (!r_shortv(z)) return 0; /* call shortv, line 76 */ - z->c = z->l - m_test; - } - { int c = z->c; - insert_s(z, z->c, z->c, 1, s_9); /* <+, line 76 */ - z->c = c; - } - break; - } - break; - } - return 1; -} - -static int r_Step_1c(struct SN_env * z) { - z->ket = z->c; /* [, line 83 */ - { int m = z->l - z->c; /* or, line 83 */ - if (!(eq_s_b(z, 1, s_10))) goto lab1; - goto lab0; - lab1: - z->c = z->l - m; - if (!(eq_s_b(z, 1, s_11))) return 0; - } + if (!(find_among(z, a_0, 1))) + goto lab2; /* among, line 33 */ + goto lab1; + lab2: + z->c = c; + while (1) + { /* gopast, line 36 */ + if (!(in_grouping(z, g_v, 97, 121))) + goto lab3; + break; + lab3: + if (z->c >= z->l) + goto lab0; + z->c++; + } + while (1) + { /* gopast, line 36 */ + if (!(out_grouping(z, g_v, 97, 121))) + goto lab4; + break; + lab4: + if (z->c >= z->l) + goto lab0; + z->c++; + } + } +lab1: + z->I[0] = z->c; /* setmark p1, line 37 */ + while (1) + { /* gopast, line 38 */ + if (!(in_grouping(z, g_v, 97, 121))) + goto lab5; + break; + lab5: + if (z->c >= z->l) + goto lab0; + z->c++; + } + while (1) + { /* gopast, line 38 */ + if (!(out_grouping(z, g_v, 97, 121))) + goto lab6; + break; + lab6: + if (z->c >= z->l) + goto lab0; + z->c++; + } + z->I[1] = z->c; /* setmark p2, line 38 */ lab0: - z->bra = z->c; /* ], line 83 */ - if (!(out_grouping_b(z, g_v, 97, 121))) return 0; - { int m = z->l - z->c; /* not, line 84 */ - if (z->c > z->lb) goto lab2; /* atlimit, line 84 */ - return 0; - lab2: - z->c = z->l - m; - } - slice_from_s(z, 1, s_12); /* <-, line 85 */ - return 1; + z->c = c; + } + return 1; } -static int r_Step_2(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 89 */ - among_var = find_among_b(z, a_4, 24); /* substring, line 89 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 89 */ - if (!r_R1(z)) return 0; /* call R1, line 89 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_from_s(z, 4, s_13); /* <-, line 90 */ - break; - case 2: - slice_from_s(z, 4, s_14); /* <-, line 91 */ - break; - case 3: - slice_from_s(z, 4, s_15); /* <-, line 92 */ - break; - case 4: - slice_from_s(z, 4, s_16); /* <-, line 93 */ - break; - case 5: - slice_from_s(z, 3, s_17); /* <-, line 94 */ - break; - case 6: - slice_from_s(z, 3, s_18); /* <-, line 96 */ - break; - case 7: - slice_from_s(z, 3, s_19); /* <-, line 98 */ - break; - case 8: - slice_from_s(z, 2, s_20); /* <-, line 100 */ - break; - case 9: - slice_from_s(z, 3, s_21); /* <-, line 101 */ - break; - case 10: - slice_from_s(z, 3, s_22); /* <-, line 103 */ - break; - case 11: - slice_from_s(z, 3, s_23); /* <-, line 105 */ - break; - case 12: - slice_from_s(z, 3, s_24); /* <-, line 107 */ - break; - case 13: - if (!(eq_s_b(z, 1, s_25))) return 0; - slice_from_s(z, 2, s_26); /* <-, line 108 */ - break; - case 14: - slice_from_s(z, 3, s_27); /* <-, line 109 */ - break; - case 15: - slice_from_s(z, 4, s_28); /* <-, line 110 */ - break; - case 16: - if (!(in_grouping_b(z, g_valid_LI, 99, 116))) return 0; - slice_del(z); /* delete, line 111 */ - break; - } - return 1; -} +static int +r_shortv(struct SN_env * z) +{ + { + int m = z->l - z->c; /* or, line 46 */ -static int r_Step_3(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 116 */ - among_var = find_among_b(z, a_5, 9); /* substring, line 116 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 116 */ - if (!r_R1(z)) return 0; /* call R1, line 116 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_from_s(z, 4, s_29); /* <-, line 117 */ - break; - case 2: - slice_from_s(z, 3, s_30); /* <-, line 118 */ - break; - case 3: - slice_from_s(z, 2, s_31); /* <-, line 119 */ - break; - case 4: - slice_from_s(z, 2, s_32); /* <-, line 121 */ - break; - case 5: - slice_del(z); /* delete, line 123 */ - break; - case 6: - if (!r_R2(z)) return 0; /* call R2, line 125 */ - slice_del(z); /* delete, line 125 */ - break; - } - return 1; -} - -static int r_Step_4(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 130 */ - among_var = find_among_b(z, a_6, 18); /* substring, line 130 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 130 */ - if (!r_R2(z)) return 0; /* call R2, line 130 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_del(z); /* delete, line 133 */ - break; - case 2: - { int m = z->l - z->c; /* or, line 134 */ - if (!(eq_s_b(z, 1, s_33))) goto lab1; - goto lab0; - lab1: - z->c = z->l - m; - if (!(eq_s_b(z, 1, s_34))) return 0; - } - lab0: - slice_del(z); /* delete, line 134 */ - break; - } - return 1; -} - -static int r_Step_5(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 139 */ - among_var = find_among_b(z, a_7, 2); /* substring, line 139 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 139 */ - switch(among_var) { - case 0: return 0; - case 1: - { int m = z->l - z->c; /* or, line 140 */ - if (!r_R2(z)) goto lab1; /* call R2, line 140 */ - goto lab0; - lab1: - z->c = z->l - m; - if (!r_R1(z)) return 0; /* call R1, line 140 */ - { int m = z->l - z->c; /* not, line 140 */ - if (!r_shortv(z)) goto lab2; /* call shortv, line 140 */ - return 0; - lab2: - z->c = z->l - m; - } - } - lab0: - slice_del(z); /* delete, line 140 */ - break; - case 2: - if (!r_R2(z)) return 0; /* call R2, line 141 */ - if (!(eq_s_b(z, 1, s_35))) return 0; - slice_del(z); /* delete, line 141 */ - break; - } - return 1; -} - -static int r_exception2(struct SN_env * z) { - z->ket = z->c; /* [, line 147 */ - if (!(find_among_b(z, a_8, 8))) return 0; /* substring, line 147 */ - z->bra = z->c; /* ], line 147 */ - if (z->c > z->lb) return 0; /* atlimit, line 147 */ - return 1; -} - -static int r_exception1(struct SN_env * z) { - int among_var; - z->bra = z->c; /* [, line 159 */ - among_var = find_among(z, a_9, 18); /* substring, line 159 */ - if (!(among_var)) return 0; - z->ket = z->c; /* ], line 159 */ - if (z->c < z->l) return 0; /* atlimit, line 159 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_from_s(z, 3, s_36); /* <-, line 163 */ - break; - case 2: - slice_from_s(z, 3, s_37); /* <-, line 164 */ - break; - case 3: - slice_from_s(z, 3, s_38); /* <-, line 165 */ - break; - case 4: - slice_from_s(z, 3, s_39); /* <-, line 166 */ - break; - case 5: - slice_from_s(z, 3, s_40); /* <-, line 167 */ - break; - case 6: - slice_from_s(z, 3, s_41); /* <-, line 171 */ - break; - case 7: - slice_from_s(z, 5, s_42); /* <-, line 172 */ - break; - case 8: - slice_from_s(z, 4, s_43); /* <-, line 173 */ - break; - case 9: - slice_from_s(z, 5, s_44); /* <-, line 174 */ - break; - case 10: - slice_from_s(z, 4, s_45); /* <-, line 175 */ - break; - case 11: - slice_from_s(z, 5, s_46); /* <-, line 176 */ - break; - } - return 1; -} - -static int r_postlude(struct SN_env * z) { - if (!(z->B[0])) return 0; /* Boolean test Y_found, line 192 */ - while(1) { /* repeat, line 192 */ - int c = z->c; - while(1) { /* goto, line 192 */ - int c = z->c; - z->bra = z->c; /* [, line 192 */ - if (!(eq_s(z, 1, s_47))) goto lab1; - z->ket = z->c; /* ], line 192 */ - z->c = c; - break; - lab1: - z->c = c; - if (z->c >= z->l) goto lab0; - z->c++; - } - slice_from_s(z, 1, s_48); /* <-, line 192 */ - continue; - lab0: - z->c = c; - break; - } - return 1; -} - -extern int english_stem(struct SN_env * z) { - { int c = z->c; /* or, line 196 */ - if (!r_exception1(z)) goto lab1; /* call exception1, line 196 */ - goto lab0; - lab1: - z->c = c; - { int c_test = z->c; /* test, line 198 */ - { int c = z->c + 3; - if (0 > c || c > z->l) return 0; - z->c = c; /* hop, line 198 */ - } - z->c = c_test; - } - { int c = z->c; /* do, line 199 */ - if (!r_prelude(z)) goto lab2; /* call prelude, line 199 */ - lab2: - z->c = c; - } - { int c = z->c; /* do, line 200 */ - if (!r_mark_regions(z)) goto lab3; /* call mark_regions, line 200 */ - lab3: - z->c = c; - } - z->lb = z->c; z->c = z->l; /* backwards, line 201 */ - - { int m = z->l - z->c; /* do, line 203 */ - if (!r_Step_1a(z)) goto lab4; /* call Step_1a, line 203 */ - lab4: - z->c = z->l - m; - } - { int m = z->l - z->c; /* or, line 205 */ - if (!r_exception2(z)) goto lab6; /* call exception2, line 205 */ - goto lab5; - lab6: - z->c = z->l - m; - { int m = z->l - z->c; /* do, line 207 */ - if (!r_Step_1b(z)) goto lab7; /* call Step_1b, line 207 */ - lab7: - z->c = z->l - m; - } - { int m = z->l - z->c; /* do, line 208 */ - if (!r_Step_1c(z)) goto lab8; /* call Step_1c, line 208 */ - lab8: - z->c = z->l - m; - } - { int m = z->l - z->c; /* do, line 210 */ - if (!r_Step_2(z)) goto lab9; /* call Step_2, line 210 */ - lab9: - z->c = z->l - m; - } - { int m = z->l - z->c; /* do, line 211 */ - if (!r_Step_3(z)) goto lab10; /* call Step_3, line 211 */ - lab10: - z->c = z->l - m; - } - { int m = z->l - z->c; /* do, line 212 */ - if (!r_Step_4(z)) goto lab11; /* call Step_4, line 212 */ - lab11: - z->c = z->l - m; - } - { int m = z->l - z->c; /* do, line 214 */ - if (!r_Step_5(z)) goto lab12; /* call Step_5, line 214 */ - lab12: - z->c = z->l - m; - } - } - lab5: - z->c = z->lb; - { int c = z->c; /* do, line 217 */ - if (!r_postlude(z)) goto lab13; /* call postlude, line 217 */ - lab13: - z->c = c; - } - } + if (!(out_grouping_b(z, g_v_WXY, 89, 121))) + goto lab1; + if (!(in_grouping_b(z, g_v, 97, 121))) + goto lab1; + if (!(out_grouping_b(z, g_v, 97, 121))) + goto lab1; + goto lab0; +lab1: + z->c = z->l - m; + if (!(out_grouping_b(z, g_v, 97, 121))) + return 0; + if (!(in_grouping_b(z, g_v, 97, 121))) + return 0; + if (z->c > z->lb) + return 0; /* atlimit, line 47 */ + } lab0: - return 1; + return 1; } -extern struct SN_env * english_create_env(void) { return SN_create_env(0, 2, 1); } +static int +r_R1(struct SN_env * z) +{ + if (!(z->I[0] <= z->c)) + return 0; + return 1; +} -extern void english_close_env(struct SN_env * z) { SN_close_env(z); } +static int +r_R2(struct SN_env * z) +{ + if (!(z->I[1] <= z->c)) + return 0; + return 1; +} +static int +r_Step_1a(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 54 */ + among_var = find_among_b(z, a_1, 6); /* substring, line 54 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 54 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_from_s(z, 2, s_4); /* <-, line 55 */ + break; + case 2: + { + int m = z->l - z->c; /* or, line 57 */ + + if (z->c <= z->lb) + goto lab1; + z->c--; /* next, line 57 */ + if (z->c > z->lb) + goto lab1; /* atlimit, line 57 */ + slice_from_s(z, 2, s_5); /* <-, line 57 */ + goto lab0; + lab1: + z->c = z->l - m; + slice_from_s(z, 1, s_6); /* <-, line 57 */ + } + lab0: + break; + case 3: + if (z->c <= z->lb) + return 0; + z->c--; /* next, line 58 */ + while (1) + { /* gopast, line 58 */ + if (!(in_grouping_b(z, g_v, 97, 121))) + goto lab2; + break; + lab2: + if (z->c <= z->lb) + return 0; + z->c--; + } + slice_del(z); /* delete, line 58 */ + break; + } + return 1; +} + +static int +r_Step_1b(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 64 */ + among_var = find_among_b(z, a_3, 6); /* substring, line 64 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 64 */ + switch (among_var) + { + case 0: + return 0; + case 1: + if (!r_R1(z)) + return 0; /* call R1, line 66 */ + slice_from_s(z, 2, s_7); /* <-, line 66 */ + break; + case 2: + { + int m_test = z->l - z->c; /* test, line 69 */ + + while (1) + { /* gopast, line 69 */ + if (!(in_grouping_b(z, g_v, 97, 121))) + goto lab0; + break; + lab0: + if (z->c <= z->lb) + return 0; + z->c--; + } + z->c = z->l - m_test; + } + slice_del(z); /* delete, line 69 */ + { + int m_test = z->l - z->c; /* test, line 70 */ + + among_var = find_among_b(z, a_2, 13); /* substring, line 70 */ + if (!(among_var)) + return 0; + z->c = z->l - m_test; + } + switch (among_var) + { + case 0: + return 0; + case 1: + { + int c = z->c; + + insert_s(z, z->c, z->c, 1, s_8); /* <+, line 72 */ + z->c = c; + } + break; + case 2: + z->ket = z->c; /* [, line 75 */ + if (z->c <= z->lb) + return 0; + z->c--; /* next, line 75 */ + z->bra = z->c; /* ], line 75 */ + slice_del(z); /* delete, line 75 */ + break; + case 3: + if (z->c != z->I[0]) + return 0; /* atmark, line 76 */ + { + int m_test = z->l - z->c; /* test, line 76 */ + + if (!r_shortv(z)) + return 0; /* call shortv, line 76 */ + z->c = z->l - m_test; + } + { + int c = z->c; + + insert_s(z, z->c, z->c, 1, s_9); /* <+, line 76 */ + z->c = c; + } + break; + } + break; + } + return 1; +} + +static int +r_Step_1c(struct SN_env * z) +{ + z->ket = z->c; /* [, line 83 */ + { + int m = z->l - z->c; /* or, line 83 */ + + if (!(eq_s_b(z, 1, s_10))) + goto lab1; + goto lab0; +lab1: + z->c = z->l - m; + if (!(eq_s_b(z, 1, s_11))) + return 0; + } +lab0: + z->bra = z->c; /* ], line 83 */ + if (!(out_grouping_b(z, g_v, 97, 121))) + return 0; + { + int m = z->l - z->c; /* not, line 84 */ + + if (z->c > z->lb) + goto lab2; /* atlimit, line 84 */ + return 0; +lab2: + z->c = z->l - m; + } + slice_from_s(z, 1, s_12); /* <-, line 85 */ + return 1; +} + +static int +r_Step_2(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 89 */ + among_var = find_among_b(z, a_4, 24); /* substring, line 89 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 89 */ + if (!r_R1(z)) + return 0; /* call R1, line 89 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_from_s(z, 4, s_13); /* <-, line 90 */ + break; + case 2: + slice_from_s(z, 4, s_14); /* <-, line 91 */ + break; + case 3: + slice_from_s(z, 4, s_15); /* <-, line 92 */ + break; + case 4: + slice_from_s(z, 4, s_16); /* <-, line 93 */ + break; + case 5: + slice_from_s(z, 3, s_17); /* <-, line 94 */ + break; + case 6: + slice_from_s(z, 3, s_18); /* <-, line 96 */ + break; + case 7: + slice_from_s(z, 3, s_19); /* <-, line 98 */ + break; + case 8: + slice_from_s(z, 2, s_20); /* <-, line 100 */ + break; + case 9: + slice_from_s(z, 3, s_21); /* <-, line 101 */ + break; + case 10: + slice_from_s(z, 3, s_22); /* <-, line 103 */ + break; + case 11: + slice_from_s(z, 3, s_23); /* <-, line 105 */ + break; + case 12: + slice_from_s(z, 3, s_24); /* <-, line 107 */ + break; + case 13: + if (!(eq_s_b(z, 1, s_25))) + return 0; + slice_from_s(z, 2, s_26); /* <-, line 108 */ + break; + case 14: + slice_from_s(z, 3, s_27); /* <-, line 109 */ + break; + case 15: + slice_from_s(z, 4, s_28); /* <-, line 110 */ + break; + case 16: + if (!(in_grouping_b(z, g_valid_LI, 99, 116))) + return 0; + slice_del(z); /* delete, line 111 */ + break; + } + return 1; +} + +static int +r_Step_3(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 116 */ + among_var = find_among_b(z, a_5, 9); /* substring, line 116 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 116 */ + if (!r_R1(z)) + return 0; /* call R1, line 116 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_from_s(z, 4, s_29); /* <-, line 117 */ + break; + case 2: + slice_from_s(z, 3, s_30); /* <-, line 118 */ + break; + case 3: + slice_from_s(z, 2, s_31); /* <-, line 119 */ + break; + case 4: + slice_from_s(z, 2, s_32); /* <-, line 121 */ + break; + case 5: + slice_del(z); /* delete, line 123 */ + break; + case 6: + if (!r_R2(z)) + return 0; /* call R2, line 125 */ + slice_del(z); /* delete, line 125 */ + break; + } + return 1; +} + +static int +r_Step_4(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 130 */ + among_var = find_among_b(z, a_6, 18); /* substring, line 130 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 130 */ + if (!r_R2(z)) + return 0; /* call R2, line 130 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_del(z); /* delete, line 133 */ + break; + case 2: + { + int m = z->l - z->c; /* or, line 134 */ + + if (!(eq_s_b(z, 1, s_33))) + goto lab1; + goto lab0; + lab1: + z->c = z->l - m; + if (!(eq_s_b(z, 1, s_34))) + return 0; + } + lab0: + slice_del(z); /* delete, line 134 */ + break; + } + return 1; +} + +static int +r_Step_5(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 139 */ + among_var = find_among_b(z, a_7, 2); /* substring, line 139 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 139 */ + switch (among_var) + { + case 0: + return 0; + case 1: + { + int m = z->l - z->c; /* or, line 140 */ + + if (!r_R2(z)) + goto lab1; /* call R2, line 140 */ + goto lab0; + lab1: + z->c = z->l - m; + if (!r_R1(z)) + return 0; /* call R1, line 140 */ + { + int m = z->l - z->c; /* not, line 140 */ + + if (!r_shortv(z)) + goto lab2; /* call shortv, line 140 */ + return 0; + lab2: + z->c = z->l - m; + } + } + lab0: + slice_del(z); /* delete, line 140 */ + break; + case 2: + if (!r_R2(z)) + return 0; /* call R2, line 141 */ + if (!(eq_s_b(z, 1, s_35))) + return 0; + slice_del(z); /* delete, line 141 */ + break; + } + return 1; +} + +static int +r_exception2(struct SN_env * z) +{ + z->ket = z->c; /* [, line 147 */ + if (!(find_among_b(z, a_8, 8))) + return 0; /* substring, line 147 */ + z->bra = z->c; /* ], line 147 */ + if (z->c > z->lb) + return 0; /* atlimit, line 147 */ + return 1; +} + +static int +r_exception1(struct SN_env * z) +{ + int among_var; + + z->bra = z->c; /* [, line 159 */ + among_var = find_among(z, a_9, 18); /* substring, line 159 */ + if (!(among_var)) + return 0; + z->ket = z->c; /* ], line 159 */ + if (z->c < z->l) + return 0; /* atlimit, line 159 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_from_s(z, 3, s_36); /* <-, line 163 */ + break; + case 2: + slice_from_s(z, 3, s_37); /* <-, line 164 */ + break; + case 3: + slice_from_s(z, 3, s_38); /* <-, line 165 */ + break; + case 4: + slice_from_s(z, 3, s_39); /* <-, line 166 */ + break; + case 5: + slice_from_s(z, 3, s_40); /* <-, line 167 */ + break; + case 6: + slice_from_s(z, 3, s_41); /* <-, line 171 */ + break; + case 7: + slice_from_s(z, 5, s_42); /* <-, line 172 */ + break; + case 8: + slice_from_s(z, 4, s_43); /* <-, line 173 */ + break; + case 9: + slice_from_s(z, 5, s_44); /* <-, line 174 */ + break; + case 10: + slice_from_s(z, 4, s_45); /* <-, line 175 */ + break; + case 11: + slice_from_s(z, 5, s_46); /* <-, line 176 */ + break; + } + return 1; +} + +static int +r_postlude(struct SN_env * z) +{ + if (!(z->B[0])) + return 0; /* Boolean test Y_found, line 192 */ + while (1) + { /* repeat, line 192 */ + int c = z->c; + + while (1) + { /* goto, line 192 */ + int c = z->c; + + z->bra = z->c; /* [, line 192 */ + if (!(eq_s(z, 1, s_47))) + goto lab1; + z->ket = z->c; /* ], line 192 */ + z->c = c; + break; + lab1: + z->c = c; + if (z->c >= z->l) + goto lab0; + z->c++; + } + slice_from_s(z, 1, s_48); /* <-, line 192 */ + continue; +lab0: + z->c = c; + break; + } + return 1; +} + +extern int +english_stem(struct SN_env * z) +{ + { + int c = z->c; /* or, line 196 */ + + if (!r_exception1(z)) + goto lab1; /* call exception1, line 196 */ + goto lab0; +lab1: + z->c = c; + { + int c_test = z->c; /* test, line 198 */ + + { + int c = z->c + 3; + + if (0 > c || c > z->l) + return 0; + z->c = c; /* hop, line 198 */ + } + z->c = c_test; + } + { + int c = z->c; /* do, line 199 */ + + if (!r_prelude(z)) + goto lab2; /* call prelude, line 199 */ + lab2: + z->c = c; + } + { + int c = z->c; /* do, line 200 */ + + if (!r_mark_regions(z)) + goto lab3; /* call mark_regions, line 200 */ + lab3: + z->c = c; + } + z->lb = z->c; + z->c = z->l; /* backwards, line 201 */ + + { + int m = z->l - z->c; /* do, line 203 */ + + if (!r_Step_1a(z)) + goto lab4; /* call Step_1a, line 203 */ + lab4: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* or, line 205 */ + + if (!r_exception2(z)) + goto lab6; /* call exception2, line 205 */ + goto lab5; + lab6: + z->c = z->l - m; + { + int m = z->l - z->c; /* do, line 207 */ + + if (!r_Step_1b(z)) + goto lab7; /* call Step_1b, line 207 */ + lab7: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* do, line 208 */ + + if (!r_Step_1c(z)) + goto lab8; /* call Step_1c, line 208 */ + lab8: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* do, line 210 */ + + if (!r_Step_2(z)) + goto lab9; /* call Step_2, line 210 */ + lab9: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* do, line 211 */ + + if (!r_Step_3(z)) + goto lab10; /* call Step_3, line 211 */ + lab10: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* do, line 212 */ + + if (!r_Step_4(z)) + goto lab11; /* call Step_4, line 212 */ + lab11: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* do, line 214 */ + + if (!r_Step_5(z)) + goto lab12; /* call Step_5, line 214 */ + lab12: + z->c = z->l - m; + } + } +lab5: + z->c = z->lb; + { + int c = z->c; /* do, line 217 */ + + if (!r_postlude(z)) + goto lab13; /* call postlude, line 217 */ + lab13: + z->c = c; + } + } +lab0: + return 1; +} + +extern struct SN_env *english_create_env(void) +{ + return SN_create_env(0, 2, 1); +} + +extern void english_close_env(struct SN_env * z) +{ + SN_close_env(z); +} diff --git a/contrib/tsearch2/snowball/english_stem.h b/contrib/tsearch2/snowball/english_stem.h index bfefcd5656..7a52f9cde1 100644 --- a/contrib/tsearch2/snowball/english_stem.h +++ b/contrib/tsearch2/snowball/english_stem.h @@ -1,8 +1,7 @@ /* This file was generated automatically by the Snowball to ANSI C compiler */ -extern struct SN_env * english_create_env(void); +extern struct SN_env *english_create_env(void); extern void english_close_env(struct SN_env * z); -extern int english_stem(struct SN_env * z); - +extern int english_stem(struct SN_env * z); diff --git a/contrib/tsearch2/snowball/header.h b/contrib/tsearch2/snowball/header.h index 6b63697202..4d4f127d6a 100644 --- a/contrib/tsearch2/snowball/header.h +++ b/contrib/tsearch2/snowball/header.h @@ -2,41 +2,42 @@ #define HEAD 2*sizeof(int) -#define SIZE(p) ((int *)(p))[-1] +#define SIZE(p) ((int *)(p))[-1] #define SET_SIZE(p, n) ((int *)(p))[-1] = n #define CAPACITY(p) ((int *)(p))[-2] struct among -{ int s_size; /* number of chars in string */ - symbol * s; /* search string */ - int substring_i;/* index to longest matching substring */ - int result; /* result of the lookup */ - int (* function)(struct SN_env *); +{ + int s_size; /* number of chars in string */ + symbol *s; /* search string */ + int substring_i; /* index to longest matching substring */ + int result; /* result of the lookup */ + int (*function) (struct SN_env *); }; -extern symbol * create_s(void); +extern symbol *create_s(void); extern void lose_s(symbol * p); -extern int in_grouping(struct SN_env * z, unsigned char * s, int min, int max); -extern int in_grouping_b(struct SN_env * z, unsigned char * s, int min, int max); -extern int out_grouping(struct SN_env * z, unsigned char * s, int min, int max); -extern int out_grouping_b(struct SN_env * z, unsigned char * s, int min, int max); +extern int in_grouping(struct SN_env * z, unsigned char *s, int min, int max); +extern int in_grouping_b(struct SN_env * z, unsigned char *s, int min, int max); +extern int out_grouping(struct SN_env * z, unsigned char *s, int min, int max); +extern int out_grouping_b(struct SN_env * z, unsigned char *s, int min, int max); -extern int in_range(struct SN_env * z, int min, int max); -extern int in_range_b(struct SN_env * z, int min, int max); -extern int out_range(struct SN_env * z, int min, int max); -extern int out_range_b(struct SN_env * z, int min, int max); +extern int in_range(struct SN_env * z, int min, int max); +extern int in_range_b(struct SN_env * z, int min, int max); +extern int out_range(struct SN_env * z, int min, int max); +extern int out_range_b(struct SN_env * z, int min, int max); -extern int eq_s(struct SN_env * z, int s_size, symbol * s); -extern int eq_s_b(struct SN_env * z, int s_size, symbol * s); -extern int eq_v(struct SN_env * z, symbol * p); -extern int eq_v_b(struct SN_env * z, symbol * p); +extern int eq_s(struct SN_env * z, int s_size, symbol * s); +extern int eq_s_b(struct SN_env * z, int s_size, symbol * s); +extern int eq_v(struct SN_env * z, symbol * p); +extern int eq_v_b(struct SN_env * z, symbol * p); -extern int find_among(struct SN_env * z, struct among * v, int v_size); -extern int find_among_b(struct SN_env * z, struct among * v, int v_size); +extern int find_among(struct SN_env * z, struct among * v, int v_size); +extern int find_among_b(struct SN_env * z, struct among * v, int v_size); -extern symbol * increase_size(symbol * p, int n); -extern int replace_s(struct SN_env * z, int c_bra, int c_ket, int s_size, const symbol * s); +extern symbol *increase_size(symbol * p, int n); +extern int replace_s(struct SN_env * z, int c_bra, int c_ket, int s_size, const symbol * s); extern void slice_from_s(struct SN_env * z, int s_size, symbol * s); extern void slice_from_v(struct SN_env * z, symbol * p); extern void slice_del(struct SN_env * z); @@ -44,8 +45,7 @@ extern void slice_del(struct SN_env * z); extern void insert_s(struct SN_env * z, int bra, int ket, int s_size, symbol * s); extern void insert_v(struct SN_env * z, int bra, int ket, symbol * p); -extern symbol * slice_to(struct SN_env * z, symbol * p); -extern symbol * assign_to(struct SN_env * z, symbol * p); +extern symbol *slice_to(struct SN_env * z, symbol * p); +extern symbol *assign_to(struct SN_env * z, symbol * p); extern void debug(struct SN_env * z, int number, int line_count); - diff --git a/contrib/tsearch2/snowball/russian_stem.c b/contrib/tsearch2/snowball/russian_stem.c index 14fd49156b..db698ce53f 100644 --- a/contrib/tsearch2/snowball/russian_stem.c +++ b/contrib/tsearch2/snowball/russian_stem.c @@ -3,624 +3,762 @@ #include "header.h" -extern int russian_stem(struct SN_env * z); -static int r_tidy_up(struct SN_env * z); -static int r_derivational(struct SN_env * z); -static int r_noun(struct SN_env * z); -static int r_verb(struct SN_env * z); -static int r_reflexive(struct SN_env * z); -static int r_adjectival(struct SN_env * z); -static int r_adjective(struct SN_env * z); -static int r_perfective_gerund(struct SN_env * z); -static int r_R2(struct SN_env * z); -static int r_mark_regions(struct SN_env * z); +extern int russian_stem(struct SN_env * z); +static int r_tidy_up(struct SN_env * z); +static int r_derivational(struct SN_env * z); +static int r_noun(struct SN_env * z); +static int r_verb(struct SN_env * z); +static int r_reflexive(struct SN_env * z); +static int r_adjectival(struct SN_env * z); +static int r_adjective(struct SN_env * z); +static int r_perfective_gerund(struct SN_env * z); +static int r_R2(struct SN_env * z); +static int r_mark_regions(struct SN_env * z); -extern struct SN_env * russian_create_env(void); +extern struct SN_env *russian_create_env(void); extern void russian_close_env(struct SN_env * z); -static symbol s_0_0[3] = { 215, 219, 201 }; -static symbol s_0_1[4] = { 201, 215, 219, 201 }; -static symbol s_0_2[4] = { 217, 215, 219, 201 }; -static symbol s_0_3[1] = { 215 }; -static symbol s_0_4[2] = { 201, 215 }; -static symbol s_0_5[2] = { 217, 215 }; -static symbol s_0_6[5] = { 215, 219, 201, 211, 216 }; -static symbol s_0_7[6] = { 201, 215, 219, 201, 211, 216 }; -static symbol s_0_8[6] = { 217, 215, 219, 201, 211, 216 }; +static symbol s_0_0[3] = {215, 219, 201}; +static symbol s_0_1[4] = {201, 215, 219, 201}; +static symbol s_0_2[4] = {217, 215, 219, 201}; +static symbol s_0_3[1] = {215}; +static symbol s_0_4[2] = {201, 215}; +static symbol s_0_5[2] = {217, 215}; +static symbol s_0_6[5] = {215, 219, 201, 211, 216}; +static symbol s_0_7[6] = {201, 215, 219, 201, 211, 216}; +static symbol s_0_8[6] = {217, 215, 219, 201, 211, 216}; static struct among a_0[9] = { -/* 0 */ { 3, s_0_0, -1, 1, 0}, -/* 1 */ { 4, s_0_1, 0, 2, 0}, -/* 2 */ { 4, s_0_2, 0, 2, 0}, -/* 3 */ { 1, s_0_3, -1, 1, 0}, -/* 4 */ { 2, s_0_4, 3, 2, 0}, -/* 5 */ { 2, s_0_5, 3, 2, 0}, -/* 6 */ { 5, s_0_6, -1, 1, 0}, -/* 7 */ { 6, s_0_7, 6, 2, 0}, -/* 8 */ { 6, s_0_8, 6, 2, 0} + /* 0 */ {3, s_0_0, -1, 1, 0}, + /* 1 */ {4, s_0_1, 0, 2, 0}, + /* 2 */ {4, s_0_2, 0, 2, 0}, + /* 3 */ {1, s_0_3, -1, 1, 0}, + /* 4 */ {2, s_0_4, 3, 2, 0}, + /* 5 */ {2, s_0_5, 3, 2, 0}, + /* 6 */ {5, s_0_6, -1, 1, 0}, + /* 7 */ {6, s_0_7, 6, 2, 0}, + /* 8 */ {6, s_0_8, 6, 2, 0} }; -static symbol s_1_0[2] = { 192, 192 }; -static symbol s_1_1[2] = { 197, 192 }; -static symbol s_1_2[2] = { 207, 192 }; -static symbol s_1_3[2] = { 213, 192 }; -static symbol s_1_4[2] = { 197, 197 }; -static symbol s_1_5[2] = { 201, 197 }; -static symbol s_1_6[2] = { 207, 197 }; -static symbol s_1_7[2] = { 217, 197 }; -static symbol s_1_8[2] = { 201, 200 }; -static symbol s_1_9[2] = { 217, 200 }; -static symbol s_1_10[3] = { 201, 205, 201 }; -static symbol s_1_11[3] = { 217, 205, 201 }; -static symbol s_1_12[2] = { 197, 202 }; -static symbol s_1_13[2] = { 201, 202 }; -static symbol s_1_14[2] = { 207, 202 }; -static symbol s_1_15[2] = { 217, 202 }; -static symbol s_1_16[2] = { 197, 205 }; -static symbol s_1_17[2] = { 201, 205 }; -static symbol s_1_18[2] = { 207, 205 }; -static symbol s_1_19[2] = { 217, 205 }; -static symbol s_1_20[3] = { 197, 199, 207 }; -static symbol s_1_21[3] = { 207, 199, 207 }; -static symbol s_1_22[2] = { 193, 209 }; -static symbol s_1_23[2] = { 209, 209 }; -static symbol s_1_24[3] = { 197, 205, 213 }; -static symbol s_1_25[3] = { 207, 205, 213 }; +static symbol s_1_0[2] = {192, 192}; +static symbol s_1_1[2] = {197, 192}; +static symbol s_1_2[2] = {207, 192}; +static symbol s_1_3[2] = {213, 192}; +static symbol s_1_4[2] = {197, 197}; +static symbol s_1_5[2] = {201, 197}; +static symbol s_1_6[2] = {207, 197}; +static symbol s_1_7[2] = {217, 197}; +static symbol s_1_8[2] = {201, 200}; +static symbol s_1_9[2] = {217, 200}; +static symbol s_1_10[3] = {201, 205, 201}; +static symbol s_1_11[3] = {217, 205, 201}; +static symbol s_1_12[2] = {197, 202}; +static symbol s_1_13[2] = {201, 202}; +static symbol s_1_14[2] = {207, 202}; +static symbol s_1_15[2] = {217, 202}; +static symbol s_1_16[2] = {197, 205}; +static symbol s_1_17[2] = {201, 205}; +static symbol s_1_18[2] = {207, 205}; +static symbol s_1_19[2] = {217, 205}; +static symbol s_1_20[3] = {197, 199, 207}; +static symbol s_1_21[3] = {207, 199, 207}; +static symbol s_1_22[2] = {193, 209}; +static symbol s_1_23[2] = {209, 209}; +static symbol s_1_24[3] = {197, 205, 213}; +static symbol s_1_25[3] = {207, 205, 213}; static struct among a_1[26] = { -/* 0 */ { 2, s_1_0, -1, 1, 0}, -/* 1 */ { 2, s_1_1, -1, 1, 0}, -/* 2 */ { 2, s_1_2, -1, 1, 0}, -/* 3 */ { 2, s_1_3, -1, 1, 0}, -/* 4 */ { 2, s_1_4, -1, 1, 0}, -/* 5 */ { 2, s_1_5, -1, 1, 0}, -/* 6 */ { 2, s_1_6, -1, 1, 0}, -/* 7 */ { 2, s_1_7, -1, 1, 0}, -/* 8 */ { 2, s_1_8, -1, 1, 0}, -/* 9 */ { 2, s_1_9, -1, 1, 0}, -/* 10 */ { 3, s_1_10, -1, 1, 0}, -/* 11 */ { 3, s_1_11, -1, 1, 0}, -/* 12 */ { 2, s_1_12, -1, 1, 0}, -/* 13 */ { 2, s_1_13, -1, 1, 0}, -/* 14 */ { 2, s_1_14, -1, 1, 0}, -/* 15 */ { 2, s_1_15, -1, 1, 0}, -/* 16 */ { 2, s_1_16, -1, 1, 0}, -/* 17 */ { 2, s_1_17, -1, 1, 0}, -/* 18 */ { 2, s_1_18, -1, 1, 0}, -/* 19 */ { 2, s_1_19, -1, 1, 0}, -/* 20 */ { 3, s_1_20, -1, 1, 0}, -/* 21 */ { 3, s_1_21, -1, 1, 0}, -/* 22 */ { 2, s_1_22, -1, 1, 0}, -/* 23 */ { 2, s_1_23, -1, 1, 0}, -/* 24 */ { 3, s_1_24, -1, 1, 0}, -/* 25 */ { 3, s_1_25, -1, 1, 0} + /* 0 */ {2, s_1_0, -1, 1, 0}, + /* 1 */ {2, s_1_1, -1, 1, 0}, + /* 2 */ {2, s_1_2, -1, 1, 0}, + /* 3 */ {2, s_1_3, -1, 1, 0}, + /* 4 */ {2, s_1_4, -1, 1, 0}, + /* 5 */ {2, s_1_5, -1, 1, 0}, + /* 6 */ {2, s_1_6, -1, 1, 0}, + /* 7 */ {2, s_1_7, -1, 1, 0}, + /* 8 */ {2, s_1_8, -1, 1, 0}, + /* 9 */ {2, s_1_9, -1, 1, 0}, + /* 10 */ {3, s_1_10, -1, 1, 0}, + /* 11 */ {3, s_1_11, -1, 1, 0}, + /* 12 */ {2, s_1_12, -1, 1, 0}, + /* 13 */ {2, s_1_13, -1, 1, 0}, + /* 14 */ {2, s_1_14, -1, 1, 0}, + /* 15 */ {2, s_1_15, -1, 1, 0}, + /* 16 */ {2, s_1_16, -1, 1, 0}, + /* 17 */ {2, s_1_17, -1, 1, 0}, + /* 18 */ {2, s_1_18, -1, 1, 0}, + /* 19 */ {2, s_1_19, -1, 1, 0}, + /* 20 */ {3, s_1_20, -1, 1, 0}, + /* 21 */ {3, s_1_21, -1, 1, 0}, + /* 22 */ {2, s_1_22, -1, 1, 0}, + /* 23 */ {2, s_1_23, -1, 1, 0}, + /* 24 */ {3, s_1_24, -1, 1, 0}, + /* 25 */ {3, s_1_25, -1, 1, 0} }; -static symbol s_2_0[2] = { 197, 205 }; -static symbol s_2_1[2] = { 206, 206 }; -static symbol s_2_2[2] = { 215, 219 }; -static symbol s_2_3[3] = { 201, 215, 219 }; -static symbol s_2_4[3] = { 217, 215, 219 }; -static symbol s_2_5[1] = { 221 }; -static symbol s_2_6[2] = { 192, 221 }; -static symbol s_2_7[3] = { 213, 192, 221 }; +static symbol s_2_0[2] = {197, 205}; +static symbol s_2_1[2] = {206, 206}; +static symbol s_2_2[2] = {215, 219}; +static symbol s_2_3[3] = {201, 215, 219}; +static symbol s_2_4[3] = {217, 215, 219}; +static symbol s_2_5[1] = {221}; +static symbol s_2_6[2] = {192, 221}; +static symbol s_2_7[3] = {213, 192, 221}; static struct among a_2[8] = { -/* 0 */ { 2, s_2_0, -1, 1, 0}, -/* 1 */ { 2, s_2_1, -1, 1, 0}, -/* 2 */ { 2, s_2_2, -1, 1, 0}, -/* 3 */ { 3, s_2_3, 2, 2, 0}, -/* 4 */ { 3, s_2_4, 2, 2, 0}, -/* 5 */ { 1, s_2_5, -1, 1, 0}, -/* 6 */ { 2, s_2_6, 5, 1, 0}, -/* 7 */ { 3, s_2_7, 6, 2, 0} + /* 0 */ {2, s_2_0, -1, 1, 0}, + /* 1 */ {2, s_2_1, -1, 1, 0}, + /* 2 */ {2, s_2_2, -1, 1, 0}, + /* 3 */ {3, s_2_3, 2, 2, 0}, + /* 4 */ {3, s_2_4, 2, 2, 0}, + /* 5 */ {1, s_2_5, -1, 1, 0}, + /* 6 */ {2, s_2_6, 5, 1, 0}, + /* 7 */ {3, s_2_7, 6, 2, 0} }; -static symbol s_3_0[2] = { 211, 209 }; -static symbol s_3_1[2] = { 211, 216 }; +static symbol s_3_0[2] = {211, 209}; +static symbol s_3_1[2] = {211, 216}; static struct among a_3[2] = { -/* 0 */ { 2, s_3_0, -1, 1, 0}, -/* 1 */ { 2, s_3_1, -1, 1, 0} + /* 0 */ {2, s_3_0, -1, 1, 0}, + /* 1 */ {2, s_3_1, -1, 1, 0} }; -static symbol s_4_0[1] = { 192 }; -static symbol s_4_1[2] = { 213, 192 }; -static symbol s_4_2[2] = { 204, 193 }; -static symbol s_4_3[3] = { 201, 204, 193 }; -static symbol s_4_4[3] = { 217, 204, 193 }; -static symbol s_4_5[2] = { 206, 193 }; -static symbol s_4_6[3] = { 197, 206, 193 }; -static symbol s_4_7[3] = { 197, 212, 197 }; -static symbol s_4_8[3] = { 201, 212, 197 }; -static symbol s_4_9[3] = { 202, 212, 197 }; -static symbol s_4_10[4] = { 197, 202, 212, 197 }; -static symbol s_4_11[4] = { 213, 202, 212, 197 }; -static symbol s_4_12[2] = { 204, 201 }; -static symbol s_4_13[3] = { 201, 204, 201 }; -static symbol s_4_14[3] = { 217, 204, 201 }; -static symbol s_4_15[1] = { 202 }; -static symbol s_4_16[2] = { 197, 202 }; -static symbol s_4_17[2] = { 213, 202 }; -static symbol s_4_18[1] = { 204 }; -static symbol s_4_19[2] = { 201, 204 }; -static symbol s_4_20[2] = { 217, 204 }; -static symbol s_4_21[2] = { 197, 205 }; -static symbol s_4_22[2] = { 201, 205 }; -static symbol s_4_23[2] = { 217, 205 }; -static symbol s_4_24[1] = { 206 }; -static symbol s_4_25[2] = { 197, 206 }; -static symbol s_4_26[2] = { 204, 207 }; -static symbol s_4_27[3] = { 201, 204, 207 }; -static symbol s_4_28[3] = { 217, 204, 207 }; -static symbol s_4_29[2] = { 206, 207 }; -static symbol s_4_30[3] = { 197, 206, 207 }; -static symbol s_4_31[3] = { 206, 206, 207 }; -static symbol s_4_32[2] = { 192, 212 }; -static symbol s_4_33[3] = { 213, 192, 212 }; -static symbol s_4_34[2] = { 197, 212 }; -static symbol s_4_35[3] = { 213, 197, 212 }; -static symbol s_4_36[2] = { 201, 212 }; -static symbol s_4_37[2] = { 209, 212 }; -static symbol s_4_38[2] = { 217, 212 }; -static symbol s_4_39[2] = { 212, 216 }; -static symbol s_4_40[3] = { 201, 212, 216 }; -static symbol s_4_41[3] = { 217, 212, 216 }; -static symbol s_4_42[3] = { 197, 219, 216 }; -static symbol s_4_43[3] = { 201, 219, 216 }; -static symbol s_4_44[2] = { 206, 217 }; -static symbol s_4_45[3] = { 197, 206, 217 }; +static symbol s_4_0[1] = {192}; +static symbol s_4_1[2] = {213, 192}; +static symbol s_4_2[2] = {204, 193}; +static symbol s_4_3[3] = {201, 204, 193}; +static symbol s_4_4[3] = {217, 204, 193}; +static symbol s_4_5[2] = {206, 193}; +static symbol s_4_6[3] = {197, 206, 193}; +static symbol s_4_7[3] = {197, 212, 197}; +static symbol s_4_8[3] = {201, 212, 197}; +static symbol s_4_9[3] = {202, 212, 197}; +static symbol s_4_10[4] = {197, 202, 212, 197}; +static symbol s_4_11[4] = {213, 202, 212, 197}; +static symbol s_4_12[2] = {204, 201}; +static symbol s_4_13[3] = {201, 204, 201}; +static symbol s_4_14[3] = {217, 204, 201}; +static symbol s_4_15[1] = {202}; +static symbol s_4_16[2] = {197, 202}; +static symbol s_4_17[2] = {213, 202}; +static symbol s_4_18[1] = {204}; +static symbol s_4_19[2] = {201, 204}; +static symbol s_4_20[2] = {217, 204}; +static symbol s_4_21[2] = {197, 205}; +static symbol s_4_22[2] = {201, 205}; +static symbol s_4_23[2] = {217, 205}; +static symbol s_4_24[1] = {206}; +static symbol s_4_25[2] = {197, 206}; +static symbol s_4_26[2] = {204, 207}; +static symbol s_4_27[3] = {201, 204, 207}; +static symbol s_4_28[3] = {217, 204, 207}; +static symbol s_4_29[2] = {206, 207}; +static symbol s_4_30[3] = {197, 206, 207}; +static symbol s_4_31[3] = {206, 206, 207}; +static symbol s_4_32[2] = {192, 212}; +static symbol s_4_33[3] = {213, 192, 212}; +static symbol s_4_34[2] = {197, 212}; +static symbol s_4_35[3] = {213, 197, 212}; +static symbol s_4_36[2] = {201, 212}; +static symbol s_4_37[2] = {209, 212}; +static symbol s_4_38[2] = {217, 212}; +static symbol s_4_39[2] = {212, 216}; +static symbol s_4_40[3] = {201, 212, 216}; +static symbol s_4_41[3] = {217, 212, 216}; +static symbol s_4_42[3] = {197, 219, 216}; +static symbol s_4_43[3] = {201, 219, 216}; +static symbol s_4_44[2] = {206, 217}; +static symbol s_4_45[3] = {197, 206, 217}; static struct among a_4[46] = { -/* 0 */ { 1, s_4_0, -1, 2, 0}, -/* 1 */ { 2, s_4_1, 0, 2, 0}, -/* 2 */ { 2, s_4_2, -1, 1, 0}, -/* 3 */ { 3, s_4_3, 2, 2, 0}, -/* 4 */ { 3, s_4_4, 2, 2, 0}, -/* 5 */ { 2, s_4_5, -1, 1, 0}, -/* 6 */ { 3, s_4_6, 5, 2, 0}, -/* 7 */ { 3, s_4_7, -1, 1, 0}, -/* 8 */ { 3, s_4_8, -1, 2, 0}, -/* 9 */ { 3, s_4_9, -1, 1, 0}, -/* 10 */ { 4, s_4_10, 9, 2, 0}, -/* 11 */ { 4, s_4_11, 9, 2, 0}, -/* 12 */ { 2, s_4_12, -1, 1, 0}, -/* 13 */ { 3, s_4_13, 12, 2, 0}, -/* 14 */ { 3, s_4_14, 12, 2, 0}, -/* 15 */ { 1, s_4_15, -1, 1, 0}, -/* 16 */ { 2, s_4_16, 15, 2, 0}, -/* 17 */ { 2, s_4_17, 15, 2, 0}, -/* 18 */ { 1, s_4_18, -1, 1, 0}, -/* 19 */ { 2, s_4_19, 18, 2, 0}, -/* 20 */ { 2, s_4_20, 18, 2, 0}, -/* 21 */ { 2, s_4_21, -1, 1, 0}, -/* 22 */ { 2, s_4_22, -1, 2, 0}, -/* 23 */ { 2, s_4_23, -1, 2, 0}, -/* 24 */ { 1, s_4_24, -1, 1, 0}, -/* 25 */ { 2, s_4_25, 24, 2, 0}, -/* 26 */ { 2, s_4_26, -1, 1, 0}, -/* 27 */ { 3, s_4_27, 26, 2, 0}, -/* 28 */ { 3, s_4_28, 26, 2, 0}, -/* 29 */ { 2, s_4_29, -1, 1, 0}, -/* 30 */ { 3, s_4_30, 29, 2, 0}, -/* 31 */ { 3, s_4_31, 29, 1, 0}, -/* 32 */ { 2, s_4_32, -1, 1, 0}, -/* 33 */ { 3, s_4_33, 32, 2, 0}, -/* 34 */ { 2, s_4_34, -1, 1, 0}, -/* 35 */ { 3, s_4_35, 34, 2, 0}, -/* 36 */ { 2, s_4_36, -1, 2, 0}, -/* 37 */ { 2, s_4_37, -1, 2, 0}, -/* 38 */ { 2, s_4_38, -1, 2, 0}, -/* 39 */ { 2, s_4_39, -1, 1, 0}, -/* 40 */ { 3, s_4_40, 39, 2, 0}, -/* 41 */ { 3, s_4_41, 39, 2, 0}, -/* 42 */ { 3, s_4_42, -1, 1, 0}, -/* 43 */ { 3, s_4_43, -1, 2, 0}, -/* 44 */ { 2, s_4_44, -1, 1, 0}, -/* 45 */ { 3, s_4_45, 44, 2, 0} + /* 0 */ {1, s_4_0, -1, 2, 0}, + /* 1 */ {2, s_4_1, 0, 2, 0}, + /* 2 */ {2, s_4_2, -1, 1, 0}, + /* 3 */ {3, s_4_3, 2, 2, 0}, + /* 4 */ {3, s_4_4, 2, 2, 0}, + /* 5 */ {2, s_4_5, -1, 1, 0}, + /* 6 */ {3, s_4_6, 5, 2, 0}, + /* 7 */ {3, s_4_7, -1, 1, 0}, + /* 8 */ {3, s_4_8, -1, 2, 0}, + /* 9 */ {3, s_4_9, -1, 1, 0}, + /* 10 */ {4, s_4_10, 9, 2, 0}, + /* 11 */ {4, s_4_11, 9, 2, 0}, + /* 12 */ {2, s_4_12, -1, 1, 0}, + /* 13 */ {3, s_4_13, 12, 2, 0}, + /* 14 */ {3, s_4_14, 12, 2, 0}, + /* 15 */ {1, s_4_15, -1, 1, 0}, + /* 16 */ {2, s_4_16, 15, 2, 0}, + /* 17 */ {2, s_4_17, 15, 2, 0}, + /* 18 */ {1, s_4_18, -1, 1, 0}, + /* 19 */ {2, s_4_19, 18, 2, 0}, + /* 20 */ {2, s_4_20, 18, 2, 0}, + /* 21 */ {2, s_4_21, -1, 1, 0}, + /* 22 */ {2, s_4_22, -1, 2, 0}, + /* 23 */ {2, s_4_23, -1, 2, 0}, + /* 24 */ {1, s_4_24, -1, 1, 0}, + /* 25 */ {2, s_4_25, 24, 2, 0}, + /* 26 */ {2, s_4_26, -1, 1, 0}, + /* 27 */ {3, s_4_27, 26, 2, 0}, + /* 28 */ {3, s_4_28, 26, 2, 0}, + /* 29 */ {2, s_4_29, -1, 1, 0}, + /* 30 */ {3, s_4_30, 29, 2, 0}, + /* 31 */ {3, s_4_31, 29, 1, 0}, + /* 32 */ {2, s_4_32, -1, 1, 0}, + /* 33 */ {3, s_4_33, 32, 2, 0}, + /* 34 */ {2, s_4_34, -1, 1, 0}, + /* 35 */ {3, s_4_35, 34, 2, 0}, + /* 36 */ {2, s_4_36, -1, 2, 0}, + /* 37 */ {2, s_4_37, -1, 2, 0}, + /* 38 */ {2, s_4_38, -1, 2, 0}, + /* 39 */ {2, s_4_39, -1, 1, 0}, + /* 40 */ {3, s_4_40, 39, 2, 0}, + /* 41 */ {3, s_4_41, 39, 2, 0}, + /* 42 */ {3, s_4_42, -1, 1, 0}, + /* 43 */ {3, s_4_43, -1, 2, 0}, + /* 44 */ {2, s_4_44, -1, 1, 0}, + /* 45 */ {3, s_4_45, 44, 2, 0} }; -static symbol s_5_0[1] = { 192 }; -static symbol s_5_1[2] = { 201, 192 }; -static symbol s_5_2[2] = { 216, 192 }; -static symbol s_5_3[1] = { 193 }; -static symbol s_5_4[1] = { 197 }; -static symbol s_5_5[2] = { 201, 197 }; -static symbol s_5_6[2] = { 216, 197 }; -static symbol s_5_7[2] = { 193, 200 }; -static symbol s_5_8[2] = { 209, 200 }; -static symbol s_5_9[3] = { 201, 209, 200 }; -static symbol s_5_10[1] = { 201 }; -static symbol s_5_11[2] = { 197, 201 }; -static symbol s_5_12[2] = { 201, 201 }; -static symbol s_5_13[3] = { 193, 205, 201 }; -static symbol s_5_14[3] = { 209, 205, 201 }; -static symbol s_5_15[4] = { 201, 209, 205, 201 }; -static symbol s_5_16[1] = { 202 }; -static symbol s_5_17[2] = { 197, 202 }; -static symbol s_5_18[3] = { 201, 197, 202 }; -static symbol s_5_19[2] = { 201, 202 }; -static symbol s_5_20[2] = { 207, 202 }; -static symbol s_5_21[2] = { 193, 205 }; -static symbol s_5_22[2] = { 197, 205 }; -static symbol s_5_23[3] = { 201, 197, 205 }; -static symbol s_5_24[2] = { 207, 205 }; -static symbol s_5_25[2] = { 209, 205 }; -static symbol s_5_26[3] = { 201, 209, 205 }; -static symbol s_5_27[1] = { 207 }; -static symbol s_5_28[1] = { 209 }; -static symbol s_5_29[2] = { 201, 209 }; -static symbol s_5_30[2] = { 216, 209 }; -static symbol s_5_31[1] = { 213 }; -static symbol s_5_32[2] = { 197, 215 }; -static symbol s_5_33[2] = { 207, 215 }; -static symbol s_5_34[1] = { 216 }; -static symbol s_5_35[1] = { 217 }; +static symbol s_5_0[1] = {192}; +static symbol s_5_1[2] = {201, 192}; +static symbol s_5_2[2] = {216, 192}; +static symbol s_5_3[1] = {193}; +static symbol s_5_4[1] = {197}; +static symbol s_5_5[2] = {201, 197}; +static symbol s_5_6[2] = {216, 197}; +static symbol s_5_7[2] = {193, 200}; +static symbol s_5_8[2] = {209, 200}; +static symbol s_5_9[3] = {201, 209, 200}; +static symbol s_5_10[1] = {201}; +static symbol s_5_11[2] = {197, 201}; +static symbol s_5_12[2] = {201, 201}; +static symbol s_5_13[3] = {193, 205, 201}; +static symbol s_5_14[3] = {209, 205, 201}; +static symbol s_5_15[4] = {201, 209, 205, 201}; +static symbol s_5_16[1] = {202}; +static symbol s_5_17[2] = {197, 202}; +static symbol s_5_18[3] = {201, 197, 202}; +static symbol s_5_19[2] = {201, 202}; +static symbol s_5_20[2] = {207, 202}; +static symbol s_5_21[2] = {193, 205}; +static symbol s_5_22[2] = {197, 205}; +static symbol s_5_23[3] = {201, 197, 205}; +static symbol s_5_24[2] = {207, 205}; +static symbol s_5_25[2] = {209, 205}; +static symbol s_5_26[3] = {201, 209, 205}; +static symbol s_5_27[1] = {207}; +static symbol s_5_28[1] = {209}; +static symbol s_5_29[2] = {201, 209}; +static symbol s_5_30[2] = {216, 209}; +static symbol s_5_31[1] = {213}; +static symbol s_5_32[2] = {197, 215}; +static symbol s_5_33[2] = {207, 215}; +static symbol s_5_34[1] = {216}; +static symbol s_5_35[1] = {217}; static struct among a_5[36] = { -/* 0 */ { 1, s_5_0, -1, 1, 0}, -/* 1 */ { 2, s_5_1, 0, 1, 0}, -/* 2 */ { 2, s_5_2, 0, 1, 0}, -/* 3 */ { 1, s_5_3, -1, 1, 0}, -/* 4 */ { 1, s_5_4, -1, 1, 0}, -/* 5 */ { 2, s_5_5, 4, 1, 0}, -/* 6 */ { 2, s_5_6, 4, 1, 0}, -/* 7 */ { 2, s_5_7, -1, 1, 0}, -/* 8 */ { 2, s_5_8, -1, 1, 0}, -/* 9 */ { 3, s_5_9, 8, 1, 0}, -/* 10 */ { 1, s_5_10, -1, 1, 0}, -/* 11 */ { 2, s_5_11, 10, 1, 0}, -/* 12 */ { 2, s_5_12, 10, 1, 0}, -/* 13 */ { 3, s_5_13, 10, 1, 0}, -/* 14 */ { 3, s_5_14, 10, 1, 0}, -/* 15 */ { 4, s_5_15, 14, 1, 0}, -/* 16 */ { 1, s_5_16, -1, 1, 0}, -/* 17 */ { 2, s_5_17, 16, 1, 0}, -/* 18 */ { 3, s_5_18, 17, 1, 0}, -/* 19 */ { 2, s_5_19, 16, 1, 0}, -/* 20 */ { 2, s_5_20, 16, 1, 0}, -/* 21 */ { 2, s_5_21, -1, 1, 0}, -/* 22 */ { 2, s_5_22, -1, 1, 0}, -/* 23 */ { 3, s_5_23, 22, 1, 0}, -/* 24 */ { 2, s_5_24, -1, 1, 0}, -/* 25 */ { 2, s_5_25, -1, 1, 0}, -/* 26 */ { 3, s_5_26, 25, 1, 0}, -/* 27 */ { 1, s_5_27, -1, 1, 0}, -/* 28 */ { 1, s_5_28, -1, 1, 0}, -/* 29 */ { 2, s_5_29, 28, 1, 0}, -/* 30 */ { 2, s_5_30, 28, 1, 0}, -/* 31 */ { 1, s_5_31, -1, 1, 0}, -/* 32 */ { 2, s_5_32, -1, 1, 0}, -/* 33 */ { 2, s_5_33, -1, 1, 0}, -/* 34 */ { 1, s_5_34, -1, 1, 0}, -/* 35 */ { 1, s_5_35, -1, 1, 0} + /* 0 */ {1, s_5_0, -1, 1, 0}, + /* 1 */ {2, s_5_1, 0, 1, 0}, + /* 2 */ {2, s_5_2, 0, 1, 0}, + /* 3 */ {1, s_5_3, -1, 1, 0}, + /* 4 */ {1, s_5_4, -1, 1, 0}, + /* 5 */ {2, s_5_5, 4, 1, 0}, + /* 6 */ {2, s_5_6, 4, 1, 0}, + /* 7 */ {2, s_5_7, -1, 1, 0}, + /* 8 */ {2, s_5_8, -1, 1, 0}, + /* 9 */ {3, s_5_9, 8, 1, 0}, + /* 10 */ {1, s_5_10, -1, 1, 0}, + /* 11 */ {2, s_5_11, 10, 1, 0}, + /* 12 */ {2, s_5_12, 10, 1, 0}, + /* 13 */ {3, s_5_13, 10, 1, 0}, + /* 14 */ {3, s_5_14, 10, 1, 0}, + /* 15 */ {4, s_5_15, 14, 1, 0}, + /* 16 */ {1, s_5_16, -1, 1, 0}, + /* 17 */ {2, s_5_17, 16, 1, 0}, + /* 18 */ {3, s_5_18, 17, 1, 0}, + /* 19 */ {2, s_5_19, 16, 1, 0}, + /* 20 */ {2, s_5_20, 16, 1, 0}, + /* 21 */ {2, s_5_21, -1, 1, 0}, + /* 22 */ {2, s_5_22, -1, 1, 0}, + /* 23 */ {3, s_5_23, 22, 1, 0}, + /* 24 */ {2, s_5_24, -1, 1, 0}, + /* 25 */ {2, s_5_25, -1, 1, 0}, + /* 26 */ {3, s_5_26, 25, 1, 0}, + /* 27 */ {1, s_5_27, -1, 1, 0}, + /* 28 */ {1, s_5_28, -1, 1, 0}, + /* 29 */ {2, s_5_29, 28, 1, 0}, + /* 30 */ {2, s_5_30, 28, 1, 0}, + /* 31 */ {1, s_5_31, -1, 1, 0}, + /* 32 */ {2, s_5_32, -1, 1, 0}, + /* 33 */ {2, s_5_33, -1, 1, 0}, + /* 34 */ {1, s_5_34, -1, 1, 0}, + /* 35 */ {1, s_5_35, -1, 1, 0} }; -static symbol s_6_0[3] = { 207, 211, 212 }; -static symbol s_6_1[4] = { 207, 211, 212, 216 }; +static symbol s_6_0[3] = {207, 211, 212}; +static symbol s_6_1[4] = {207, 211, 212, 216}; static struct among a_6[2] = { -/* 0 */ { 3, s_6_0, -1, 1, 0}, -/* 1 */ { 4, s_6_1, -1, 1, 0} + /* 0 */ {3, s_6_0, -1, 1, 0}, + /* 1 */ {4, s_6_1, -1, 1, 0} }; -static symbol s_7_0[4] = { 197, 202, 219, 197 }; -static symbol s_7_1[1] = { 206 }; -static symbol s_7_2[1] = { 216 }; -static symbol s_7_3[3] = { 197, 202, 219 }; +static symbol s_7_0[4] = {197, 202, 219, 197}; +static symbol s_7_1[1] = {206}; +static symbol s_7_2[1] = {216}; +static symbol s_7_3[3] = {197, 202, 219}; static struct among a_7[4] = { -/* 0 */ { 4, s_7_0, -1, 1, 0}, -/* 1 */ { 1, s_7_1, -1, 2, 0}, -/* 2 */ { 1, s_7_2, -1, 3, 0}, -/* 3 */ { 3, s_7_3, -1, 1, 0} + /* 0 */ {4, s_7_0, -1, 1, 0}, + /* 1 */ {1, s_7_1, -1, 2, 0}, + /* 2 */ {1, s_7_2, -1, 3, 0}, + /* 3 */ {3, s_7_3, -1, 1, 0} }; -static unsigned char g_v[] = { 35, 130, 34, 18 }; +static unsigned char g_v[] = {35, 130, 34, 18}; -static symbol s_0[] = { 193 }; -static symbol s_1[] = { 209 }; -static symbol s_2[] = { 193 }; -static symbol s_3[] = { 209 }; -static symbol s_4[] = { 193 }; -static symbol s_5[] = { 209 }; -static symbol s_6[] = { 206 }; -static symbol s_7[] = { 206 }; -static symbol s_8[] = { 206 }; -static symbol s_9[] = { 201 }; +static symbol s_0[] = {193}; +static symbol s_1[] = {209}; +static symbol s_2[] = {193}; +static symbol s_3[] = {209}; +static symbol s_4[] = {193}; +static symbol s_5[] = {209}; +static symbol s_6[] = {206}; +static symbol s_7[] = {206}; +static symbol s_8[] = {206}; +static symbol s_9[] = {201}; -static int r_mark_regions(struct SN_env * z) { - z->I[0] = z->l; - z->I[1] = z->l; - { int c = z->c; /* do, line 100 */ - while(1) { /* gopast, line 101 */ - if (!(in_grouping(z, g_v, 192, 220))) goto lab1; - break; - lab1: - if (z->c >= z->l) goto lab0; - z->c++; - } - z->I[0] = z->c; /* setmark pV, line 101 */ - while(1) { /* gopast, line 101 */ - if (!(out_grouping(z, g_v, 192, 220))) goto lab2; - break; - lab2: - if (z->c >= z->l) goto lab0; - z->c++; - } - while(1) { /* gopast, line 102 */ - if (!(in_grouping(z, g_v, 192, 220))) goto lab3; - break; - lab3: - if (z->c >= z->l) goto lab0; - z->c++; - } - while(1) { /* gopast, line 102 */ - if (!(out_grouping(z, g_v, 192, 220))) goto lab4; - break; - lab4: - if (z->c >= z->l) goto lab0; - z->c++; - } - z->I[1] = z->c; /* setmark p2, line 102 */ - lab0: - z->c = c; - } - return 1; +static int +r_mark_regions(struct SN_env * z) +{ + z->I[0] = z->l; + z->I[1] = z->l; + { + int c = z->c; /* do, line 100 */ + + while (1) + { /* gopast, line 101 */ + if (!(in_grouping(z, g_v, 192, 220))) + goto lab1; + break; + lab1: + if (z->c >= z->l) + goto lab0; + z->c++; + } + z->I[0] = z->c; /* setmark pV, line 101 */ + while (1) + { /* gopast, line 101 */ + if (!(out_grouping(z, g_v, 192, 220))) + goto lab2; + break; + lab2: + if (z->c >= z->l) + goto lab0; + z->c++; + } + while (1) + { /* gopast, line 102 */ + if (!(in_grouping(z, g_v, 192, 220))) + goto lab3; + break; + lab3: + if (z->c >= z->l) + goto lab0; + z->c++; + } + while (1) + { /* gopast, line 102 */ + if (!(out_grouping(z, g_v, 192, 220))) + goto lab4; + break; + lab4: + if (z->c >= z->l) + goto lab0; + z->c++; + } + z->I[1] = z->c; /* setmark p2, line 102 */ +lab0: + z->c = c; + } + return 1; } -static int r_R2(struct SN_env * z) { - if (!(z->I[1] <= z->c)) return 0; - return 1; +static int +r_R2(struct SN_env * z) +{ + if (!(z->I[1] <= z->c)) + return 0; + return 1; } -static int r_perfective_gerund(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 111 */ - among_var = find_among_b(z, a_0, 9); /* substring, line 111 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 111 */ - switch(among_var) { - case 0: return 0; - case 1: - { int m = z->l - z->c; /* or, line 115 */ - if (!(eq_s_b(z, 1, s_0))) goto lab1; - goto lab0; - lab1: - z->c = z->l - m; - if (!(eq_s_b(z, 1, s_1))) return 0; - } - lab0: - slice_del(z); /* delete, line 115 */ - break; - case 2: - slice_del(z); /* delete, line 122 */ - break; - } - return 1; +static int +r_perfective_gerund(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 111 */ + among_var = find_among_b(z, a_0, 9); /* substring, line 111 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 111 */ + switch (among_var) + { + case 0: + return 0; + case 1: + { + int m = z->l - z->c; /* or, line 115 */ + + if (!(eq_s_b(z, 1, s_0))) + goto lab1; + goto lab0; + lab1: + z->c = z->l - m; + if (!(eq_s_b(z, 1, s_1))) + return 0; + } + lab0: + slice_del(z); /* delete, line 115 */ + break; + case 2: + slice_del(z); /* delete, line 122 */ + break; + } + return 1; } -static int r_adjective(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 127 */ - among_var = find_among_b(z, a_1, 26); /* substring, line 127 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 127 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_del(z); /* delete, line 136 */ - break; - } - return 1; +static int +r_adjective(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 127 */ + among_var = find_among_b(z, a_1, 26); /* substring, line 127 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 127 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_del(z); /* delete, line 136 */ + break; + } + return 1; } -static int r_adjectival(struct SN_env * z) { - int among_var; - if (!r_adjective(z)) return 0; /* call adjective, line 141 */ - { int m = z->l - z->c; /* try, line 148 */ - z->ket = z->c; /* [, line 149 */ - among_var = find_among_b(z, a_2, 8); /* substring, line 149 */ - if (!(among_var)) { z->c = z->l - m; goto lab0; } - z->bra = z->c; /* ], line 149 */ - switch(among_var) { - case 0: { z->c = z->l - m; goto lab0; } - case 1: - { int m = z->l - z->c; /* or, line 154 */ - if (!(eq_s_b(z, 1, s_2))) goto lab2; - goto lab1; - lab2: - z->c = z->l - m; - if (!(eq_s_b(z, 1, s_3))) { z->c = z->l - m; goto lab0; } - } - lab1: - slice_del(z); /* delete, line 154 */ - break; - case 2: - slice_del(z); /* delete, line 161 */ - break; - } - lab0: - ; - } - return 1; +static int +r_adjectival(struct SN_env * z) +{ + int among_var; + + if (!r_adjective(z)) + return 0; /* call adjective, line 141 */ + { + int m = z->l - z->c; /* try, line 148 */ + + z->ket = z->c; /* [, line 149 */ + among_var = find_among_b(z, a_2, 8); /* substring, line 149 */ + if (!(among_var)) + { + z->c = z->l - m; + goto lab0; + } + z->bra = z->c; /* ], line 149 */ + switch (among_var) + { + case 0: + { + z->c = z->l - m; + goto lab0; + } + case 1: + { + int m = z->l - z->c; /* or, line 154 */ + + if (!(eq_s_b(z, 1, s_2))) + goto lab2; + goto lab1; + lab2: + z->c = z->l - m; + if (!(eq_s_b(z, 1, s_3))) + { + z->c = z->l - m; + goto lab0; + } + } + lab1: + slice_del(z); /* delete, line 154 */ + break; + case 2: + slice_del(z); /* delete, line 161 */ + break; + } +lab0: + ; + } + return 1; } -static int r_reflexive(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 168 */ - among_var = find_among_b(z, a_3, 2); /* substring, line 168 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 168 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_del(z); /* delete, line 171 */ - break; - } - return 1; +static int +r_reflexive(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 168 */ + among_var = find_among_b(z, a_3, 2); /* substring, line 168 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 168 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_del(z); /* delete, line 171 */ + break; + } + return 1; } -static int r_verb(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 176 */ - among_var = find_among_b(z, a_4, 46); /* substring, line 176 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 176 */ - switch(among_var) { - case 0: return 0; - case 1: - { int m = z->l - z->c; /* or, line 182 */ - if (!(eq_s_b(z, 1, s_4))) goto lab1; - goto lab0; - lab1: - z->c = z->l - m; - if (!(eq_s_b(z, 1, s_5))) return 0; - } - lab0: - slice_del(z); /* delete, line 182 */ - break; - case 2: - slice_del(z); /* delete, line 190 */ - break; - } - return 1; +static int +r_verb(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 176 */ + among_var = find_among_b(z, a_4, 46); /* substring, line 176 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 176 */ + switch (among_var) + { + case 0: + return 0; + case 1: + { + int m = z->l - z->c; /* or, line 182 */ + + if (!(eq_s_b(z, 1, s_4))) + goto lab1; + goto lab0; + lab1: + z->c = z->l - m; + if (!(eq_s_b(z, 1, s_5))) + return 0; + } + lab0: + slice_del(z); /* delete, line 182 */ + break; + case 2: + slice_del(z); /* delete, line 190 */ + break; + } + return 1; } -static int r_noun(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 199 */ - among_var = find_among_b(z, a_5, 36); /* substring, line 199 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 199 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_del(z); /* delete, line 206 */ - break; - } - return 1; +static int +r_noun(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 199 */ + among_var = find_among_b(z, a_5, 36); /* substring, line 199 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 199 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_del(z); /* delete, line 206 */ + break; + } + return 1; } -static int r_derivational(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 215 */ - among_var = find_among_b(z, a_6, 2); /* substring, line 215 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 215 */ - if (!r_R2(z)) return 0; /* call R2, line 215 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_del(z); /* delete, line 218 */ - break; - } - return 1; +static int +r_derivational(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 215 */ + among_var = find_among_b(z, a_6, 2); /* substring, line 215 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 215 */ + if (!r_R2(z)) + return 0; /* call R2, line 215 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_del(z); /* delete, line 218 */ + break; + } + return 1; } -static int r_tidy_up(struct SN_env * z) { - int among_var; - z->ket = z->c; /* [, line 223 */ - among_var = find_among_b(z, a_7, 4); /* substring, line 223 */ - if (!(among_var)) return 0; - z->bra = z->c; /* ], line 223 */ - switch(among_var) { - case 0: return 0; - case 1: - slice_del(z); /* delete, line 227 */ - z->ket = z->c; /* [, line 228 */ - if (!(eq_s_b(z, 1, s_6))) return 0; - z->bra = z->c; /* ], line 228 */ - if (!(eq_s_b(z, 1, s_7))) return 0; - slice_del(z); /* delete, line 228 */ - break; - case 2: - if (!(eq_s_b(z, 1, s_8))) return 0; - slice_del(z); /* delete, line 231 */ - break; - case 3: - slice_del(z); /* delete, line 233 */ - break; - } - return 1; +static int +r_tidy_up(struct SN_env * z) +{ + int among_var; + + z->ket = z->c; /* [, line 223 */ + among_var = find_among_b(z, a_7, 4); /* substring, line 223 */ + if (!(among_var)) + return 0; + z->bra = z->c; /* ], line 223 */ + switch (among_var) + { + case 0: + return 0; + case 1: + slice_del(z); /* delete, line 227 */ + z->ket = z->c; /* [, line 228 */ + if (!(eq_s_b(z, 1, s_6))) + return 0; + z->bra = z->c; /* ], line 228 */ + if (!(eq_s_b(z, 1, s_7))) + return 0; + slice_del(z); /* delete, line 228 */ + break; + case 2: + if (!(eq_s_b(z, 1, s_8))) + return 0; + slice_del(z); /* delete, line 231 */ + break; + case 3: + slice_del(z); /* delete, line 233 */ + break; + } + return 1; } -extern int russian_stem(struct SN_env * z) { - { int c = z->c; /* do, line 240 */ - if (!r_mark_regions(z)) goto lab0; /* call mark_regions, line 240 */ - lab0: - z->c = c; - } - z->lb = z->c; z->c = z->l; /* backwards, line 241 */ +extern int +russian_stem(struct SN_env * z) +{ + { + int c = z->c; /* do, line 240 */ - { int m = z->l - z->c; /* setlimit, line 241 */ - int m3; - if (z->c < z->I[0]) return 0; - z->c = z->I[0]; /* tomark, line 241 */ - m3 = z->lb; z->lb = z->c; - z->c = z->l - m; - { int m = z->l - z->c; /* do, line 242 */ - { int m = z->l - z->c; /* or, line 243 */ - if (!r_perfective_gerund(z)) goto lab3; /* call perfective_gerund, line 243 */ - goto lab2; - lab3: - z->c = z->l - m; - { int m = z->l - z->c; /* try, line 244 */ - if (!r_reflexive(z)) { z->c = z->l - m; goto lab4; } /* call reflexive, line 244 */ - lab4: - ; - } - { int m = z->l - z->c; /* or, line 245 */ - if (!r_adjectival(z)) goto lab6; /* call adjectival, line 245 */ - goto lab5; - lab6: - z->c = z->l - m; - if (!r_verb(z)) goto lab7; /* call verb, line 245 */ - goto lab5; - lab7: - z->c = z->l - m; - if (!r_noun(z)) goto lab1; /* call noun, line 245 */ - } - lab5: - ; - } - lab2: - lab1: - z->c = z->l - m; - } - { int m = z->l - z->c; /* try, line 248 */ - z->ket = z->c; /* [, line 248 */ - if (!(eq_s_b(z, 1, s_9))) { z->c = z->l - m; goto lab8; } - z->bra = z->c; /* ], line 248 */ - slice_del(z); /* delete, line 248 */ - lab8: - ; - } - { int m = z->l - z->c; /* do, line 251 */ - if (!r_derivational(z)) goto lab9; /* call derivational, line 251 */ - lab9: - z->c = z->l - m; - } - { int m = z->l - z->c; /* do, line 252 */ - if (!r_tidy_up(z)) goto lab10; /* call tidy_up, line 252 */ - lab10: - z->c = z->l - m; - } - z->lb = m3; - } - z->c = z->lb; - return 1; + if (!r_mark_regions(z)) + goto lab0; /* call mark_regions, line 240 */ +lab0: + z->c = c; + } + z->lb = z->c; + z->c = z->l; /* backwards, line 241 */ + + { + int m = z->l - z->c; /* setlimit, line 241 */ + int m3; + + if (z->c < z->I[0]) + return 0; + z->c = z->I[0]; /* tomark, line 241 */ + m3 = z->lb; + z->lb = z->c; + z->c = z->l - m; + { + int m = z->l - z->c; /* do, line 242 */ + + { + int m = z->l - z->c; /* or, line 243 */ + + if (!r_perfective_gerund(z)) + goto lab3; /* call perfective_gerund, line 243 */ + goto lab2; + lab3: + z->c = z->l - m; + { + int m = z->l - z->c; /* try, line 244 */ + + if (!r_reflexive(z)) + { + z->c = z->l - m; + goto lab4; + } /* call reflexive, line 244 */ + lab4: + ; + } + { + int m = z->l - z->c; /* or, line 245 */ + + if (!r_adjectival(z)) + goto lab6; /* call adjectival, line 245 */ + goto lab5; + lab6: + z->c = z->l - m; + if (!r_verb(z)) + goto lab7; /* call verb, line 245 */ + goto lab5; + lab7: + z->c = z->l - m; + if (!r_noun(z)) + goto lab1; /* call noun, line 245 */ + } + lab5: + ; + } + lab2: + lab1: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* try, line 248 */ + + z->ket = z->c; /* [, line 248 */ + if (!(eq_s_b(z, 1, s_9))) + { + z->c = z->l - m; + goto lab8; + } + z->bra = z->c; /* ], line 248 */ + slice_del(z); /* delete, line 248 */ + lab8: + ; + } + { + int m = z->l - z->c; /* do, line 251 */ + + if (!r_derivational(z)) + goto lab9; /* call derivational, line 251 */ + lab9: + z->c = z->l - m; + } + { + int m = z->l - z->c; /* do, line 252 */ + + if (!r_tidy_up(z)) + goto lab10; /* call tidy_up, line 252 */ + lab10: + z->c = z->l - m; + } + z->lb = m3; + } + z->c = z->lb; + return 1; } -extern struct SN_env * russian_create_env(void) { return SN_create_env(0, 2, 0); } - -extern void russian_close_env(struct SN_env * z) { SN_close_env(z); } +extern struct SN_env *russian_create_env(void) +{ + return SN_create_env(0, 2, 0); +} +extern void russian_close_env(struct SN_env * z) +{ + SN_close_env(z); +} diff --git a/contrib/tsearch2/snowball/russian_stem.h b/contrib/tsearch2/snowball/russian_stem.h index 7dc26d45c8..69369e295b 100644 --- a/contrib/tsearch2/snowball/russian_stem.h +++ b/contrib/tsearch2/snowball/russian_stem.h @@ -1,8 +1,7 @@ /* This file was generated automatically by the Snowball to ANSI C compiler */ -extern struct SN_env * russian_create_env(void); +extern struct SN_env *russian_create_env(void); extern void russian_close_env(struct SN_env * z); -extern int russian_stem(struct SN_env * z); - +extern int russian_stem(struct SN_env * z); diff --git a/contrib/tsearch2/snowball/utilities.c b/contrib/tsearch2/snowball/utilities.c index 5dc752445b..374d2c11bb 100644 --- a/contrib/tsearch2/snowball/utilities.c +++ b/contrib/tsearch2/snowball/utilities.c @@ -9,320 +9,507 @@ #define CREATE_SIZE 1 -extern symbol * create_s(void) -{ symbol * p = (symbol *) (HEAD + (char *) malloc(HEAD + (CREATE_SIZE + 1) * sizeof(symbol))); - CAPACITY(p) = CREATE_SIZE; - SET_SIZE(p, CREATE_SIZE); - return p; -} - -extern void lose_s(symbol * p) { free((char *) p - HEAD); } - -extern int in_grouping(struct SN_env * z, unsigned char * s, int min, int max) -{ if (z->c >= z->l) return 0; - { int ch = z->p[z->c]; - if - (ch > max || (ch -= min) < 0 || - (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return 0; - } - z->c++; return 1; -} - -extern int in_grouping_b(struct SN_env * z, unsigned char * s, int min, int max) -{ if (z->c <= z->lb) return 0; - { int ch = z->p[z->c - 1]; - if - (ch > max || (ch -= min) < 0 || - (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return 0; - } - z->c--; return 1; -} - -extern int out_grouping(struct SN_env * z, unsigned char * s, int min, int max) -{ if (z->c >= z->l) return 0; - { int ch = z->p[z->c]; - unless - (ch > max || (ch -= min) < 0 || - (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return 0; - } - z->c++; return 1; -} - -extern int out_grouping_b(struct SN_env * z, unsigned char * s, int min, int max) -{ if (z->c <= z->lb) return 0; - { int ch = z->p[z->c - 1]; - unless - (ch > max || (ch -= min) < 0 || - (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return 0; - } - z->c--; return 1; -} - - -extern int in_range(struct SN_env * z, int min, int max) -{ if (z->c >= z->l) return 0; - { int ch = z->p[z->c]; - if - (ch > max || ch < min) return 0; - } - z->c++; return 1; -} - -extern int in_range_b(struct SN_env * z, int min, int max) -{ if (z->c <= z->lb) return 0; - { int ch = z->p[z->c - 1]; - if - (ch > max || ch < min) return 0; - } - z->c--; return 1; -} - -extern int out_range(struct SN_env * z, int min, int max) -{ if (z->c >= z->l) return 0; - { int ch = z->p[z->c]; - unless - (ch > max || ch < min) return 0; - } - z->c++; return 1; -} - -extern int out_range_b(struct SN_env * z, int min, int max) -{ if (z->c <= z->lb) return 0; - { int ch = z->p[z->c - 1]; - unless - (ch > max || ch < min) return 0; - } - z->c--; return 1; -} - -extern int eq_s(struct SN_env * z, int s_size, symbol * s) -{ if (z->l - z->c < s_size || - memcmp(z->p + z->c, s, s_size * sizeof(symbol)) != 0) return 0; - z->c += s_size; return 1; -} - -extern int eq_s_b(struct SN_env * z, int s_size, symbol * s) -{ if (z->c - z->lb < s_size || - memcmp(z->p + z->c - s_size, s, s_size * sizeof(symbol)) != 0) return 0; - z->c -= s_size; return 1; -} - -extern int eq_v(struct SN_env * z, symbol * p) -{ return eq_s(z, SIZE(p), p); -} - -extern int eq_v_b(struct SN_env * z, symbol * p) -{ return eq_s_b(z, SIZE(p), p); -} - -extern int find_among(struct SN_env * z, struct among * v, int v_size) +extern symbol * +create_s(void) { - int i = 0; - int j = v_size; + symbol *p = (symbol *) (HEAD + (char *) malloc(HEAD + (CREATE_SIZE + 1) * sizeof(symbol))); - int c = z->c; int l = z->l; - symbol * q = z->p + c; + CAPACITY(p) = CREATE_SIZE; + SET_SIZE(p, CREATE_SIZE); + return p; +} - struct among * w; +extern void lose_s(symbol * p) +{ + free((char *) p - HEAD); +} - int common_i = 0; - int common_j = 0; +extern int +in_grouping(struct SN_env * z, unsigned char *s, int min, int max) +{ + if (z->c >= z->l) + return 0; + { + int ch = z->p[z->c]; - int first_key_inspected = 0; + if + (ch > max || (ch -= min) < 0 || + (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) + return 0; + } + z->c++; + return 1; +} - while(1) - { int k = i + ((j - i) >> 1); - int diff = 0; - int common = common_i < common_j ? common_i : common_j; /* smaller */ - w = v + k; - { int i; for (i = common; i < w->s_size; i++) - { if (c + common == l) { diff = -1; break; } - diff = q[common] - w->s[i]; - if (diff != 0) break; - common++; - } - } - if (diff < 0) { j = k; common_j = common; } - else { i = k; common_i = common; } - if (j - i <= 1) - { if (i > 0) break; /* v->s has been inspected */ - if (j == i) break; /* only one item in v */ +extern int +in_grouping_b(struct SN_env * z, unsigned char *s, int min, int max) +{ + if (z->c <= z->lb) + return 0; + { + int ch = z->p[z->c - 1]; - /* - but now we need to go round once more to get - v->s inspected. This looks messy, but is actually - the optimal approach. */ + if + (ch > max || (ch -= min) < 0 || + (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) + return 0; + } + z->c--; + return 1; +} - if (first_key_inspected) break; - first_key_inspected = 1; - } - } - while(1) - { w = v + i; - if (common_i >= w->s_size) - { z->c = c + w->s_size; - if (w->function == 0) return w->result; - { int res = w->function(z); - z->c = c + w->s_size; - if (res) return w->result; - } - } - i = w->substring_i; - if (i < 0) return 0; - } +extern int +out_grouping(struct SN_env * z, unsigned char *s, int min, int max) +{ + if (z->c >= z->l) + return 0; + { + int ch = z->p[z->c]; + + unless + (ch > max || (ch -= min) < 0 || + (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return 0; + } + z->c++; + return 1; +} + +extern int +out_grouping_b(struct SN_env * z, unsigned char *s, int min, int max) +{ + if (z->c <= z->lb) + return 0; + { + int ch = z->p[z->c - 1]; + + unless + (ch > max || (ch -= min) < 0 || + (s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return 0; + } + z->c--; + return 1; +} + + +extern int +in_range(struct SN_env * z, int min, int max) +{ + if (z->c >= z->l) + return 0; + { + int ch = z->p[z->c]; + + if + (ch > max || ch < min) + return 0; + } + z->c++; + return 1; +} + +extern int +in_range_b(struct SN_env * z, int min, int max) +{ + if (z->c <= z->lb) + return 0; + { + int ch = z->p[z->c - 1]; + + if + (ch > max || ch < min) + return 0; + } + z->c--; + return 1; +} + +extern int +out_range(struct SN_env * z, int min, int max) +{ + if (z->c >= z->l) + return 0; + { + int ch = z->p[z->c]; + + unless + (ch > max || ch < min) return 0; + } + z->c++; + return 1; +} + +extern int +out_range_b(struct SN_env * z, int min, int max) +{ + if (z->c <= z->lb) + return 0; + { + int ch = z->p[z->c - 1]; + + unless + (ch > max || ch < min) return 0; + } + z->c--; + return 1; +} + +extern int +eq_s(struct SN_env * z, int s_size, symbol * s) +{ + if (z->l - z->c < s_size || + memcmp(z->p + z->c, s, s_size * sizeof(symbol)) != 0) + return 0; + z->c += s_size; + return 1; +} + +extern int +eq_s_b(struct SN_env * z, int s_size, symbol * s) +{ + if (z->c - z->lb < s_size || + memcmp(z->p + z->c - s_size, s, s_size * sizeof(symbol)) != 0) + return 0; + z->c -= s_size; + return 1; +} + +extern int +eq_v(struct SN_env * z, symbol * p) +{ + return eq_s(z, SIZE(p), p); +} + +extern int +eq_v_b(struct SN_env * z, symbol * p) +{ + return eq_s_b(z, SIZE(p), p); +} + +extern int +find_among(struct SN_env * z, struct among * v, int v_size) +{ + int i = 0; + int j = v_size; + + int c = z->c; + int l = z->l; + symbol *q = z->p + c; + + struct among *w; + + int common_i = 0; + int common_j = 0; + + int first_key_inspected = 0; + + while (1) + { + int k = i + ((j - i) >> 1); + int diff = 0; + int common = common_i < common_j ? common_i : common_j; /* smaller */ + + w = v + k; + { + int i; + + for (i = common; i < w->s_size; i++) + { + if (c + common == l) + { + diff = -1; + break; + } + diff = q[common] - w->s[i]; + if (diff != 0) + break; + common++; + } + } + if (diff < 0) + { + j = k; + common_j = common; + } + else + { + i = k; + common_i = common; + } + if (j - i <= 1) + { + if (i > 0) + break; /* v->s has been inspected */ + if (j == i) + break; /* only one item in v */ + + /* + * - but now we need to go round once more to get v->s + * inspected. This looks messy, but is actually the optimal + * approach. + */ + + if (first_key_inspected) + break; + first_key_inspected = 1; + } + } + while (1) + { + w = v + i; + if (common_i >= w->s_size) + { + z->c = c + w->s_size; + if (w->function == 0) + return w->result; + { + int res = w->function(z); + + z->c = c + w->s_size; + if (res) + return w->result; + } + } + i = w->substring_i; + if (i < 0) + return 0; + } } /* find_among_b is for backwards processing. Same comments apply */ -extern int find_among_b(struct SN_env * z, struct among * v, int v_size) +extern int +find_among_b(struct SN_env * z, struct among * v, int v_size) { - int i = 0; - int j = v_size; + int i = 0; + int j = v_size; - int c = z->c; int lb = z->lb; - symbol * q = z->p + c - 1; + int c = z->c; + int lb = z->lb; + symbol *q = z->p + c - 1; - struct among * w; + struct among *w; - int common_i = 0; - int common_j = 0; + int common_i = 0; + int common_j = 0; - int first_key_inspected = 0; + int first_key_inspected = 0; - while(1) - { int k = i + ((j - i) >> 1); - int diff = 0; - int common = common_i < common_j ? common_i : common_j; - w = v + k; - { int i; for (i = w->s_size - 1 - common; i >= 0; i--) - { if (c - common == lb) { diff = -1; break; } - diff = q[- common] - w->s[i]; - if (diff != 0) break; - common++; - } - } - if (diff < 0) { j = k; common_j = common; } - else { i = k; common_i = common; } - if (j - i <= 1) - { if (i > 0) break; - if (j == i) break; - if (first_key_inspected) break; - first_key_inspected = 1; - } - } - while(1) - { w = v + i; - if (common_i >= w->s_size) - { z->c = c - w->s_size; - if (w->function == 0) return w->result; - { int res = w->function(z); - z->c = c - w->s_size; - if (res) return w->result; - } - } - i = w->substring_i; - if (i < 0) return 0; - } + while (1) + { + int k = i + ((j - i) >> 1); + int diff = 0; + int common = common_i < common_j ? common_i : common_j; + + w = v + k; + { + int i; + + for (i = w->s_size - 1 - common; i >= 0; i--) + { + if (c - common == lb) + { + diff = -1; + break; + } + diff = q[-common] - w->s[i]; + if (diff != 0) + break; + common++; + } + } + if (diff < 0) + { + j = k; + common_j = common; + } + else + { + i = k; + common_i = common; + } + if (j - i <= 1) + { + if (i > 0) + break; + if (j == i) + break; + if (first_key_inspected) + break; + first_key_inspected = 1; + } + } + while (1) + { + w = v + i; + if (common_i >= w->s_size) + { + z->c = c - w->s_size; + if (w->function == 0) + return w->result; + { + int res = w->function(z); + + z->c = c - w->s_size; + if (res) + return w->result; + } + } + i = w->substring_i; + if (i < 0) + return 0; + } } -extern symbol * increase_size(symbol * p, int n) -{ int new_size = n + 20; - symbol * q = (symbol *) (HEAD + (char *) malloc(HEAD + (new_size + 1) * sizeof(symbol))); - CAPACITY(q) = new_size; - memmove(q, p, CAPACITY(p) * sizeof(symbol)); lose_s(p); return q; +extern symbol * +increase_size(symbol * p, int n) +{ + int new_size = n + 20; + symbol *q = (symbol *) (HEAD + (char *) malloc(HEAD + (new_size + 1) * sizeof(symbol))); + + CAPACITY(q) = new_size; + memmove(q, p, CAPACITY(p) * sizeof(symbol)); + lose_s(p); + return q; } /* to replace symbols between c_bra and c_ket in z->p by the s_size symbols at s */ -extern int replace_s(struct SN_env * z, int c_bra, int c_ket, int s_size, const symbol * s) -{ int adjustment = s_size - (c_ket - c_bra); - int len = SIZE(z->p); - if (adjustment != 0) - { if (adjustment + len > CAPACITY(z->p)) z->p = increase_size(z->p, adjustment + len); - memmove(z->p + c_ket + adjustment, z->p + c_ket, (len - c_ket) * sizeof(symbol)); - SET_SIZE(z->p, adjustment + len); - z->l += adjustment; - if (z->c >= c_ket) z->c += adjustment; else - if (z->c > c_bra) z->c = c_bra; - } - unless (s_size == 0) memmove(z->p + c_bra, s, s_size * sizeof(symbol)); - return adjustment; -} - -static void slice_check(struct SN_env * z) +extern int +replace_s(struct SN_env * z, int c_bra, int c_ket, int s_size, const symbol * s) { - if (!(0 <= z->bra && - z->bra <= z->ket && - z->ket <= z->l && - z->l <= SIZE(z->p))) /* this line could be removed */ - { - fprintf(stderr, "faulty slice operation:\n"); - debug(z, -1, 0); - exit(1); - } + int adjustment = s_size - (c_ket - c_bra); + int len = SIZE(z->p); + + if (adjustment != 0) + { + if (adjustment + len > CAPACITY(z->p)) + z->p = increase_size(z->p, adjustment + len); + memmove(z->p + c_ket + adjustment, z->p + c_ket, (len - c_ket) * sizeof(symbol)); + SET_SIZE(z->p, adjustment + len); + z->l += adjustment; + if (z->c >= c_ket) + z->c += adjustment; + else if (z->c > c_bra) + z->c = c_bra; + } + unless(s_size == 0) memmove(z->p + c_bra, s, s_size * sizeof(symbol)); + return adjustment; } -extern void slice_from_s(struct SN_env * z, int s_size, symbol * s) -{ slice_check(z); - replace_s(z, z->bra, z->ket, s_size, s); +static void +slice_check(struct SN_env * z) +{ + if (!(0 <= z->bra && + z->bra <= z->ket && + z->ket <= z->l && + z->l <= SIZE(z->p))) /* this line could be removed */ + { + fprintf(stderr, "faulty slice operation:\n"); + debug(z, -1, 0); + exit(1); + } } -extern void slice_from_v(struct SN_env * z, symbol * p) -{ slice_from_s(z, SIZE(p), p); +extern void +slice_from_s(struct SN_env * z, int s_size, symbol * s) +{ + slice_check(z); + replace_s(z, z->bra, z->ket, s_size, s); } -extern void slice_del(struct SN_env * z) -{ slice_from_s(z, 0, 0); +extern void +slice_from_v(struct SN_env * z, symbol * p) +{ + slice_from_s(z, SIZE(p), p); } -extern void insert_s(struct SN_env * z, int bra, int ket, int s_size, symbol * s) -{ int adjustment = replace_s(z, bra, ket, s_size, s); - if (bra <= z->bra) z->bra += adjustment; - if (bra <= z->ket) z->ket += adjustment; +extern void +slice_del(struct SN_env * z) +{ + slice_from_s(z, 0, 0); } -extern void insert_v(struct SN_env * z, int bra, int ket, symbol * p) -{ int adjustment = replace_s(z, bra, ket, SIZE(p), p); - if (bra <= z->bra) z->bra += adjustment; - if (bra <= z->ket) z->ket += adjustment; +extern void +insert_s(struct SN_env * z, int bra, int ket, int s_size, symbol * s) +{ + int adjustment = replace_s(z, bra, ket, s_size, s); + + if (bra <= z->bra) + z->bra += adjustment; + if (bra <= z->ket) + z->ket += adjustment; } -extern symbol * slice_to(struct SN_env * z, symbol * p) -{ slice_check(z); - { int len = z->ket - z->bra; - if (CAPACITY(p) < len) p = increase_size(p, len); - memmove(p, z->p + z->bra, len * sizeof(symbol)); - SET_SIZE(p, len); - } - return p; +extern void +insert_v(struct SN_env * z, int bra, int ket, symbol * p) +{ + int adjustment = replace_s(z, bra, ket, SIZE(p), p); + + if (bra <= z->bra) + z->bra += adjustment; + if (bra <= z->ket) + z->ket += adjustment; } -extern symbol * assign_to(struct SN_env * z, symbol * p) -{ int len = z->l; - if (CAPACITY(p) < len) p = increase_size(p, len); - memmove(p, z->p, len * sizeof(symbol)); - SET_SIZE(p, len); - return p; +extern symbol * +slice_to(struct SN_env * z, symbol * p) +{ + slice_check(z); + { + int len = z->ket - z->bra; + + if (CAPACITY(p) < len) + p = increase_size(p, len); + memmove(p, z->p + z->bra, len * sizeof(symbol)); + SET_SIZE(p, len); + } + return p; } -extern void debug(struct SN_env * z, int number, int line_count) -{ int i; - int limit = SIZE(z->p); - /*if (number >= 0) printf("%3d (line %4d): '", number, line_count);*/ - if (number >= 0) printf("%3d (line %4d): [%d]'", number, line_count,limit); - for (i = 0; i <= limit; i++) - { if (z->lb == i) printf("{"); - if (z->bra == i) printf("["); - if (z->c == i) printf("|"); - if (z->ket == i) printf("]"); - if (z->l == i) printf("}"); - if (i < limit) - { int ch = z->p[i]; - if (ch == 0) ch = '#'; - printf("%c", ch); - } - } - printf("'\n"); +extern symbol * +assign_to(struct SN_env * z, symbol * p) +{ + int len = z->l; + + if (CAPACITY(p) < len) + p = increase_size(p, len); + memmove(p, z->p, len * sizeof(symbol)); + SET_SIZE(p, len); + return p; +} + +extern void +debug(struct SN_env * z, int number, int line_count) +{ + int i; + int limit = SIZE(z->p); + + /* if (number >= 0) printf("%3d (line %4d): '", number, line_count); */ + if (number >= 0) + printf("%3d (line %4d): [%d]'", number, line_count, limit); + for (i = 0; i <= limit; i++) + { + if (z->lb == i) + printf("{"); + if (z->bra == i) + printf("["); + if (z->c == i) + printf("|"); + if (z->ket == i) + printf("]"); + if (z->l == i) + printf("}"); + if (i < limit) + { + int ch = z->p[i]; + + if (ch == 0) + ch = '#'; + printf("%c", ch); + } + } + printf("'\n"); } diff --git a/contrib/tsearch2/stopword.c b/contrib/tsearch2/stopword.c index 2c2874b7f8..f91abeb460 100644 --- a/contrib/tsearch2/stopword.c +++ b/contrib/tsearch2/stopword.c @@ -1,4 +1,4 @@ -/* +/* * stopword library * Teodor Sigaev */ @@ -13,97 +13,114 @@ #define STOPBUFLEN 4096 -char* -lowerstr(char *str) { - char *ptr=str; - while(*ptr) { - *ptr = tolower(*(unsigned char*)ptr); +char * +lowerstr(char *str) +{ + char *ptr = str; + + while (*ptr) + { + *ptr = tolower(*(unsigned char *) ptr); ptr++; } return str; } void -freestoplist(StopList *s) { - char **ptr=s->stop; - if ( ptr ) - while( *ptr && s->len >0 ) { +freestoplist(StopList * s) +{ + char **ptr = s->stop; + + if (ptr) + while (*ptr && s->len > 0) + { free(*ptr); - ptr++; s->len--; - free(s->stop); - } - memset(s,0,sizeof(StopList)); + ptr++; + s->len--; + free(s->stop); + } + memset(s, 0, sizeof(StopList)); } void -readstoplist(text *in, StopList *s) { - char **stop=NULL; - s->len=0; - if ( in && VARSIZE(in) - VARHDRSZ > 0 ) { - char *filename=text2char(in); - FILE *hin=NULL; - char buf[STOPBUFLEN]; - int reallen=0; +readstoplist(text *in, StopList * s) +{ + char **stop = NULL; - if ( (hin=fopen(filename,"r")) == NULL ) + s->len = 0; + if (in && VARSIZE(in) - VARHDRSZ > 0) + { + char *filename = text2char(in); + FILE *hin = NULL; + char buf[STOPBUFLEN]; + int reallen = 0; + + if ((hin = fopen(filename, "r")) == NULL) ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("could not open file \"%s\": %m", - filename))); + filename))); - while( fgets(buf,STOPBUFLEN,hin) ) { - buf[strlen(buf)-1] = '\0'; - if ( *buf=='\0' ) continue; + while (fgets(buf, STOPBUFLEN, hin)) + { + buf[strlen(buf) - 1] = '\0'; + if (*buf == '\0') + continue; - if ( s->len>= reallen ) { - char **tmp; - reallen=(reallen) ? reallen*2 : 16; - tmp=(char**)realloc((void*)stop, sizeof(char*)*reallen); - if (!tmp) { + if (s->len >= reallen) + { + char **tmp; + + reallen = (reallen) ? reallen * 2 : 16; + tmp = (char **) realloc((void *) stop, sizeof(char *) * reallen); + if (!tmp) + { freestoplist(s); - fclose(hin); + fclose(hin); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - stop=tmp; + stop = tmp; } - - stop[s->len]=strdup(buf); - if ( !stop[s->len] ) { + + stop[s->len] = strdup(buf); + if (!stop[s->len]) + { freestoplist(s); - fclose(hin); + fclose(hin); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } - if ( s->wordop ) - stop[s->len]=(s->wordop)(stop[s->len]); + if (s->wordop) + stop[s->len] = (s->wordop) (stop[s->len]); - (s->len)++; + (s->len)++; } fclose(hin); - pfree(filename); + pfree(filename); } - s->stop=stop; -} + s->stop = stop; +} static int -comparestr(const void *a, const void *b) { - return strcmp( *(char**)a, *(char**)b ); +comparestr(const void *a, const void *b) +{ + return strcmp(*(char **) a, *(char **) b); } void -sortstoplist(StopList *s) { - if (s->stop && s->len>0) - qsort(s->stop, s->len, sizeof(char*), comparestr); +sortstoplist(StopList * s) +{ + if (s->stop && s->len > 0) + qsort(s->stop, s->len, sizeof(char *), comparestr); } bool -searchstoplist(StopList *s, char *key) { - if ( s->wordop ) - key=(*(s->wordop))(key); - return ( s->stop && s->len>0 && bsearch(&key, s->stop, s->len, sizeof(char*), comparestr) ) ? true : false; +searchstoplist(StopList * s, char *key) +{ + if (s->wordop) + key = (*(s->wordop)) (key); + return (s->stop && s->len > 0 && bsearch(&key, s->stop, s->len, sizeof(char *), comparestr)) ? true : false; } - - diff --git a/contrib/tsearch2/ts_cfg.c b/contrib/tsearch2/ts_cfg.c index d964aae573..ad06d90d9a 100644 --- a/contrib/tsearch2/ts_cfg.c +++ b/contrib/tsearch2/ts_cfg.c @@ -1,5 +1,5 @@ -/* - * interface functions to tscfg +/* + * interface functions to tscfg * Teodor Sigaev */ #include @@ -23,263 +23,299 @@ /*********top interface**********/ -static void *plan_getcfg_bylocale=NULL; -static void *plan_getcfg=NULL; -static void *plan_getmap=NULL; -static void *plan_name2id=NULL; -static Oid current_cfg_id=0; +static void *plan_getcfg_bylocale = NULL; +static void *plan_getcfg = NULL; +static void *plan_getmap = NULL; +static void *plan_name2id = NULL; +static Oid current_cfg_id = 0; void -init_cfg(Oid id, TSCfgInfo *cfg) { - Oid arg[2]={ OIDOID, OIDOID }; - bool isnull; - Datum pars[2]={ ObjectIdGetDatum(id), ObjectIdGetDatum(id) } ; - int stat,i,j; - text *ptr; - text *prsname=NULL; - MemoryContext oldcontext; +init_cfg(Oid id, TSCfgInfo * cfg) +{ + Oid arg[2] = {OIDOID, OIDOID}; + bool isnull; + Datum pars[2] = {ObjectIdGetDatum(id), ObjectIdGetDatum(id)}; + int stat, + i, + j; + text *ptr; + text *prsname = NULL; + MemoryContext oldcontext; - memset(cfg,0,sizeof(TSCfgInfo)); + memset(cfg, 0, sizeof(TSCfgInfo)); SPI_connect(); - if ( !plan_getcfg ) { - plan_getcfg = SPI_saveplan( SPI_prepare( "select prs_name from pg_ts_cfg where oid = $1" , 1, arg ) ); - if ( !plan_getcfg ) + if (!plan_getcfg) + { + plan_getcfg = SPI_saveplan(SPI_prepare("select prs_name from pg_ts_cfg where oid = $1", 1, arg)); + if (!plan_getcfg) ts_error(ERROR, "SPI_prepare() failed"); } stat = SPI_execp(plan_getcfg, pars, " ", 1); - if ( stat < 0 ) - ts_error (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed > 0 ) { - prsname = (text*) DatumGetPointer( - SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) - ); + if (stat < 0) + ts_error(ERROR, "SPI_execp return %d", stat); + if (SPI_processed > 0) + { + prsname = (text *) DatumGetPointer( + SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) + ); oldcontext = MemoryContextSwitchTo(TopMemoryContext); - prsname = ptextdup( prsname ); + prsname = ptextdup(prsname); MemoryContextSwitchTo(oldcontext); - - cfg->id=id; - } else + + cfg->id = id; + } + else ts_error(ERROR, "No tsearch cfg with id %d", id); - arg[0]=TEXTOID; - if ( !plan_getmap ) { - plan_getmap = SPI_saveplan( SPI_prepare( "select lt.tokid, pg_ts_cfgmap.dict_name from pg_ts_cfgmap, pg_ts_cfg, token_type( $1 ) as lt where lt.alias = pg_ts_cfgmap.tok_alias and pg_ts_cfgmap.ts_name = pg_ts_cfg.ts_name and pg_ts_cfg.oid= $2 order by lt.tokid desc;" , 2, arg ) ); - if ( !plan_getmap ) + arg[0] = TEXTOID; + if (!plan_getmap) + { + plan_getmap = SPI_saveplan(SPI_prepare("select lt.tokid, pg_ts_cfgmap.dict_name from pg_ts_cfgmap, pg_ts_cfg, token_type( $1 ) as lt where lt.alias = pg_ts_cfgmap.tok_alias and pg_ts_cfgmap.ts_name = pg_ts_cfg.ts_name and pg_ts_cfg.oid= $2 order by lt.tokid desc;", 2, arg)); + if (!plan_getmap) ts_error(ERROR, "SPI_prepare() failed"); } - pars[0]=PointerGetDatum( prsname ); + pars[0] = PointerGetDatum(prsname); stat = SPI_execp(plan_getmap, pars, " ", 0); - if ( stat < 0 ) - ts_error (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed <= 0 ) + if (stat < 0) + ts_error(ERROR, "SPI_execp return %d", stat); + if (SPI_processed <= 0) ts_error(ERROR, "No parser with id %d", id); - for(i=0;ivals[i], SPI_tuptable->tupdesc, 1, &isnull)); - ArrayType *toasted_a = (ArrayType*)PointerGetDatum(SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2, &isnull)); - ArrayType *a; + for (i = 0; i < SPI_processed; i++) + { + int lexid = DatumGetInt32(SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull)); + ArrayType *toasted_a = (ArrayType *) PointerGetDatum(SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2, &isnull)); + ArrayType *a; - if ( !cfg->map ) { - cfg->len=lexid+1; - cfg->map = (ListDictionary*)malloc( sizeof(ListDictionary)*cfg->len ); - if ( !cfg->map ) + if (!cfg->map) + { + cfg->len = lexid + 1; + cfg->map = (ListDictionary *) malloc(sizeof(ListDictionary) * cfg->len); + if (!cfg->map) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); - memset( cfg->map, 0, sizeof(ListDictionary)*cfg->len ); + memset(cfg->map, 0, sizeof(ListDictionary) * cfg->len); } if (isnull) continue; - a=(ArrayType*)PointerGetDatum( PG_DETOAST_DATUM( DatumGetPointer(toasted_a) ) ); - - if ( ARR_NDIM(a) != 1 ) - ts_error(ERROR,"Wrong dimension"); - if ( ARRNELEMS(a) < 1 ) + a = (ArrayType *) PointerGetDatum(PG_DETOAST_DATUM(DatumGetPointer(toasted_a))); + + if (ARR_NDIM(a) != 1) + ts_error(ERROR, "Wrong dimension"); + if (ARRNELEMS(a) < 1) continue; - cfg->map[lexid].len=ARRNELEMS(a); - cfg->map[lexid].dict_id=(Datum*)malloc( sizeof(Datum)*cfg->map[lexid].len ); - memset(cfg->map[lexid].dict_id,0,sizeof(Datum)*cfg->map[lexid].len ); - ptr=(text*)ARR_DATA_PTR(a); + cfg->map[lexid].len = ARRNELEMS(a); + cfg->map[lexid].dict_id = (Datum *) malloc(sizeof(Datum) * cfg->map[lexid].len); + memset(cfg->map[lexid].dict_id, 0, sizeof(Datum) * cfg->map[lexid].len); + ptr = (text *) ARR_DATA_PTR(a); oldcontext = MemoryContextSwitchTo(TopMemoryContext); - for(j=0;jmap[lexid].len;j++) { + for (j = 0; j < cfg->map[lexid].len; j++) + { cfg->map[lexid].dict_id[j] = PointerGetDatum(ptextdup(ptr)); - ptr=NEXTVAL(ptr); - } + ptr = NEXTVAL(ptr); + } MemoryContextSwitchTo(oldcontext); - if ( a != toasted_a ) + if (a != toasted_a) pfree(a); } - + SPI_finish(); - cfg->prs_id = name2id_prs( prsname ); + cfg->prs_id = name2id_prs(prsname); pfree(prsname); - for(i=0;ilen;i++) { - for(j=0;jmap[i].len;j++) { - ptr = (text*)DatumGetPointer( cfg->map[i].dict_id[j] ); - cfg->map[i].dict_id[j] = ObjectIdGetDatum( name2id_dict(ptr) ); + for (i = 0; i < cfg->len; i++) + { + for (j = 0; j < cfg->map[i].len; j++) + { + ptr = (text *) DatumGetPointer(cfg->map[i].dict_id[j]); + cfg->map[i].dict_id[j] = ObjectIdGetDatum(name2id_dict(ptr)); pfree(ptr); } } } -typedef struct { - TSCfgInfo *last_cfg; - int len; - int reallen; - TSCfgInfo *list; +typedef struct +{ + TSCfgInfo *last_cfg; + int len; + int reallen; + TSCfgInfo *list; SNMap name2id_map; -} CFGList; +} CFGList; -static CFGList CList = {NULL,0,0,NULL,{0,0,NULL}}; +static CFGList CList = {NULL, 0, 0, NULL, {0, 0, NULL}}; void -reset_cfg(void) { - freeSNMap( &(CList.name2id_map) ); - if ( CList.list ) { - int i,j; - for(i=0;iid - ((TSCfgInfo*)b)->id; +comparecfg(const void *a, const void *b) +{ + return ((TSCfgInfo *) a)->id - ((TSCfgInfo *) b)->id; } TSCfgInfo * -findcfg(Oid id) { +findcfg(Oid id) +{ /* last used cfg */ - if ( CList.last_cfg && CList.last_cfg->id==id ) + if (CList.last_cfg && CList.last_cfg->id == id) return CList.last_cfg; /* already used cfg */ - if ( CList.len != 0 ) { - TSCfgInfo key; - key.id=id; + if (CList.len != 0) + { + TSCfgInfo key; + + key.id = id; CList.last_cfg = bsearch(&key, CList.list, CList.len, sizeof(TSCfgInfo), comparecfg); - if ( CList.last_cfg != NULL ) + if (CList.last_cfg != NULL) return CList.last_cfg; } /* last chance */ - if ( CList.len==CList.reallen ) { - TSCfgInfo *tmp; - int reallen = ( CList.reallen ) ? 2*CList.reallen : 16; - tmp=(TSCfgInfo*)realloc(CList.list,sizeof(TSCfgInfo)*reallen); - if ( !tmp ) - ts_error(ERROR,"No memory"); - CList.reallen=reallen; - CList.list=tmp; + if (CList.len == CList.reallen) + { + TSCfgInfo *tmp; + int reallen = (CList.reallen) ? 2 * CList.reallen : 16; + + tmp = (TSCfgInfo *) realloc(CList.list, sizeof(TSCfgInfo) * reallen); + if (!tmp) + ts_error(ERROR, "No memory"); + CList.reallen = reallen; + CList.list = tmp; } - CList.last_cfg=&(CList.list[CList.len]); + CList.last_cfg = &(CList.list[CList.len]); init_cfg(id, CList.last_cfg); CList.len++; qsort(CList.list, CList.len, sizeof(TSCfgInfo), comparecfg); - return findcfg(id); /* qsort changed order!! */; + return findcfg(id); /* qsort changed order!! */ ; } Oid -name2id_cfg(text *name) { - Oid arg[1]={ TEXTOID }; - bool isnull; - Datum pars[1]={ PointerGetDatum(name) }; - int stat; - Oid id=findSNMap_t( &(CList.name2id_map), name ); - - if ( id ) +name2id_cfg(text *name) +{ + Oid arg[1] = {TEXTOID}; + bool isnull; + Datum pars[1] = {PointerGetDatum(name)}; + int stat; + Oid id = findSNMap_t(&(CList.name2id_map), name); + + if (id) return id; - + SPI_connect(); - if ( !plan_name2id ) { - plan_name2id = SPI_saveplan( SPI_prepare( "select oid from pg_ts_cfg where ts_name = $1" , 1, arg ) ); - if ( !plan_name2id ) + if (!plan_name2id) + { + plan_name2id = SPI_saveplan(SPI_prepare("select oid from pg_ts_cfg where ts_name = $1", 1, arg)); + if (!plan_name2id) /* internal error */ elog(ERROR, "SPI_prepare() failed"); } stat = SPI_execp(plan_name2id, pars, " ", 1); - if ( stat < 0 ) + if (stat < 0) /* internal error */ - elog (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed > 0 ) { - id=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) ); - if ( isnull ) + elog(ERROR, "SPI_execp return %d", stat); + if (SPI_processed > 0) + { + id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); + if (isnull) ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("null id for tsearch config"))); - } else + } + else ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("no tsearch config"))); SPI_finish(); - addSNMap_t( &(CList.name2id_map), name, id ); + addSNMap_t(&(CList.name2id_map), name, id); return id; } -void -parsetext_v2(TSCfgInfo *cfg, PRSTEXT * prs, char *buf, int4 buflen) { - int type, lenlemm, i; - char *lemm=NULL; +void +parsetext_v2(TSCfgInfo * cfg, PRSTEXT * prs, char *buf, int4 buflen) +{ + int type, + lenlemm, + i; + char *lemm = NULL; WParserInfo *prsobj = findprs(cfg->prs_id); - prsobj->prs=(void*)DatumGetPointer( - FunctionCall2( - &(prsobj->start_info), - PointerGetDatum(buf), - Int32GetDatum(buflen) - ) - ); + prsobj->prs = (void *) DatumGetPointer( + FunctionCall2( + &(prsobj->start_info), + PointerGetDatum(buf), + Int32GetDatum(buflen) + ) + ); - while( ( type=DatumGetInt32(FunctionCall3( - &(prsobj->getlexeme_info), - PointerGetDatum(prsobj->prs), - PointerGetDatum(&lemm), - PointerGetDatum(&lenlemm))) ) != 0 ) { + while ((type = DatumGetInt32(FunctionCall3( + &(prsobj->getlexeme_info), + PointerGetDatum(prsobj->prs), + PointerGetDatum(&lemm), + PointerGetDatum(&lenlemm)))) != 0) + { - if ( lenlemm >= MAXSTRLEN ) + if (lenlemm >= MAXSTRLEN) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("word is too long"))); - if ( type >= cfg->len ) /* skip this type of lexem */ - continue; + if (type >= cfg->len) /* skip this type of lexem */ + continue; - for(i=0;imap[type].len;i++) { - DictInfo *dict=finddict( DatumGetObjectId(cfg->map[type].dict_id[i]) ); - char **norms, **ptr; - - norms = ptr = (char**)DatumGetPointer( - FunctionCall3( - &(dict->lexize_info), - PointerGetDatum(dict->dictionary), - PointerGetDatum(lemm), - PointerGetDatum(lenlemm) - ) - ); - if ( !norms ) /* dictionary doesn't know this lexem */ + for (i = 0; i < cfg->map[type].len; i++) + { + DictInfo *dict = finddict(DatumGetObjectId(cfg->map[type].dict_id[i])); + char **norms, + **ptr; + + norms = ptr = (char **) DatumGetPointer( + FunctionCall3( + &(dict->lexize_info), + PointerGetDatum(dict->dictionary), + PointerGetDatum(lemm), + PointerGetDatum(lenlemm) + ) + ); + if (!norms) /* dictionary doesn't know this lexem */ continue; - prs->pos++; /*set pos*/ + prs->pos++; /* set pos */ - while( *ptr ) { - if (prs->curwords == prs->lenwords) { + while (*ptr) + { + if (prs->curwords == prs->lenwords) + { prs->lenwords *= 2; prs->words = (WORD *) repalloc((void *) prs->words, prs->lenwords * sizeof(WORD)); } @@ -292,191 +328,220 @@ parsetext_v2(TSCfgInfo *cfg, PRSTEXT * prs, char *buf, int4 buflen) { prs->curwords++; } pfree(norms); - break; /* lexem already normalized or is stop word*/ + break; /* lexem already normalized or is stop + * word */ } } FunctionCall1( - &(prsobj->end_info), - PointerGetDatum(prsobj->prs) - ); + &(prsobj->end_info), + PointerGetDatum(prsobj->prs) + ); } static void -hladdword(HLPRSTEXT * prs, char *buf, int4 buflen, int type) { - while (prs->curwords >= prs->lenwords) { +hladdword(HLPRSTEXT * prs, char *buf, int4 buflen, int type) +{ + while (prs->curwords >= prs->lenwords) + { prs->lenwords *= 2; prs->words = (HLWORD *) repalloc((void *) prs->words, prs->lenwords * sizeof(HLWORD)); } - memset( &(prs->words[prs->curwords]), 0, sizeof(HLWORD) ); - prs->words[prs->curwords].type = (uint8)type; - prs->words[prs->curwords].len = buflen; + memset(&(prs->words[prs->curwords]), 0, sizeof(HLWORD)); + prs->words[prs->curwords].type = (uint8) type; + prs->words[prs->curwords].len = buflen; prs->words[prs->curwords].word = palloc(buflen); memcpy(prs->words[prs->curwords].word, buf, buflen); - prs->curwords++; + prs->curwords++; } static void -hlfinditem(HLPRSTEXT * prs, QUERYTYPE *query, char *buf, int buflen ) { - int i; - ITEM *item=GETQUERY(query); - HLWORD *word=&( prs->words[prs->curwords-1] ); +hlfinditem(HLPRSTEXT * prs, QUERYTYPE * query, char *buf, int buflen) +{ + int i; + ITEM *item = GETQUERY(query); + HLWORD *word = &(prs->words[prs->curwords - 1]); - while (prs->curwords + query->size >= prs->lenwords) { + while (prs->curwords + query->size >= prs->lenwords) + { prs->lenwords *= 2; prs->words = (HLWORD *) repalloc((void *) prs->words, prs->lenwords * sizeof(HLWORD)); } - for(i=0; isize; i++) { - if ( item->type == VAL && item->length == buflen && strncmp( GETOPERAND(query) + item->distance, buf, buflen )==0 ) { - if ( word->item ) { - memcpy( &(prs->words[prs->curwords]), word, sizeof(HLWORD) ); - prs->words[prs->curwords].item=item; - prs->words[prs->curwords].repeated=1; + for (i = 0; i < query->size; i++) + { + if (item->type == VAL && item->length == buflen && strncmp(GETOPERAND(query) + item->distance, buf, buflen) == 0) + { + if (word->item) + { + memcpy(&(prs->words[prs->curwords]), word, sizeof(HLWORD)); + prs->words[prs->curwords].item = item; + prs->words[prs->curwords].repeated = 1; prs->curwords++; - } else - word->item=item; + } + else + word->item = item; } item++; } } -void -hlparsetext(TSCfgInfo *cfg, HLPRSTEXT * prs, QUERYTYPE *query, char *buf, int4 buflen) { - int type, lenlemm, i; - char *lemm=NULL; +void +hlparsetext(TSCfgInfo * cfg, HLPRSTEXT * prs, QUERYTYPE * query, char *buf, int4 buflen) +{ + int type, + lenlemm, + i; + char *lemm = NULL; WParserInfo *prsobj = findprs(cfg->prs_id); - prsobj->prs=(void*)DatumGetPointer( - FunctionCall2( - &(prsobj->start_info), - PointerGetDatum(buf), - Int32GetDatum(buflen) - ) - ); + prsobj->prs = (void *) DatumGetPointer( + FunctionCall2( + &(prsobj->start_info), + PointerGetDatum(buf), + Int32GetDatum(buflen) + ) + ); - while( ( type=DatumGetInt32(FunctionCall3( - &(prsobj->getlexeme_info), - PointerGetDatum(prsobj->prs), - PointerGetDatum(&lemm), - PointerGetDatum(&lenlemm))) ) != 0 ) { + while ((type = DatumGetInt32(FunctionCall3( + &(prsobj->getlexeme_info), + PointerGetDatum(prsobj->prs), + PointerGetDatum(&lemm), + PointerGetDatum(&lenlemm)))) != 0) + { - if ( lenlemm >= MAXSTRLEN ) + if (lenlemm >= MAXSTRLEN) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("word is too long"))); - hladdword(prs,lemm,lenlemm,type); + hladdword(prs, lemm, lenlemm, type); - if ( type >= cfg->len ) - continue; + if (type >= cfg->len) + continue; - for(i=0;imap[type].len;i++) { - DictInfo *dict=finddict( DatumGetObjectId(cfg->map[type].dict_id[i]) ); - char **norms, **ptr; - - norms = ptr = (char**)DatumGetPointer( - FunctionCall3( - &(dict->lexize_info), - PointerGetDatum(dict->dictionary), - PointerGetDatum(lemm), - PointerGetDatum(lenlemm) - ) - ); - if ( !norms ) /* dictionary doesn't know this lexem */ + for (i = 0; i < cfg->map[type].len; i++) + { + DictInfo *dict = finddict(DatumGetObjectId(cfg->map[type].dict_id[i])); + char **norms, + **ptr; + + norms = ptr = (char **) DatumGetPointer( + FunctionCall3( + &(dict->lexize_info), + PointerGetDatum(dict->dictionary), + PointerGetDatum(lemm), + PointerGetDatum(lenlemm) + ) + ); + if (!norms) /* dictionary doesn't know this lexem */ continue; - while( *ptr ) { - hlfinditem(prs,query,*ptr,strlen(*ptr)); + while (*ptr) + { + hlfinditem(prs, query, *ptr, strlen(*ptr)); pfree(*ptr); ptr++; } pfree(norms); - break; /* lexem already normalized or is stop word*/ + break; /* lexem already normalized or is stop + * word */ } } FunctionCall1( - &(prsobj->end_info), - PointerGetDatum(prsobj->prs) - ); + &(prsobj->end_info), + PointerGetDatum(prsobj->prs) + ); } -text* -genhl(HLPRSTEXT * prs) { - text *out; - int len=128; - char *ptr; - HLWORD *wrd=prs->words; +text * +genhl(HLPRSTEXT * prs) +{ + text *out; + int len = 128; + char *ptr; + HLWORD *wrd = prs->words; - out = (text*)palloc( len ); - ptr=((char*)out) + VARHDRSZ; + out = (text *) palloc(len); + ptr = ((char *) out) + VARHDRSZ; - while( wrd - prs->words < prs->curwords ) { - while ( wrd->len + prs->stopsellen + prs->startsellen + (ptr - ((char*)out)) >= len ) { - int dist = ptr - ((char*)out); - len*= 2; + while (wrd - prs->words < prs->curwords) + { + while (wrd->len + prs->stopsellen + prs->startsellen + (ptr - ((char *) out)) >= len) + { + int dist = ptr - ((char *) out); + + len *= 2; out = (text *) repalloc(out, len); - ptr=((char*)out) + dist; + ptr = ((char *) out) + dist; } - if ( wrd->in && !wrd->skip && !wrd->repeated ) { - if ( wrd->replace ) { - *ptr=' '; + if (wrd->in && !wrd->skip && !wrd->repeated) + { + if (wrd->replace) + { + *ptr = ' '; ptr++; - } else { - if (wrd->selected) { - memcpy(ptr,prs->startsel,prs->startsellen); - ptr+=prs->startsellen; + } + else + { + if (wrd->selected) + { + memcpy(ptr, prs->startsel, prs->startsellen); + ptr += prs->startsellen; } - memcpy(ptr,wrd->word,wrd->len); - ptr+=wrd->len; - if (wrd->selected) { - memcpy(ptr,prs->stopsel,prs->stopsellen); - ptr+=prs->stopsellen; + memcpy(ptr, wrd->word, wrd->len); + ptr += wrd->len; + if (wrd->selected) + { + memcpy(ptr, prs->stopsel, prs->stopsellen); + ptr += prs->stopsellen; } } } - if ( !wrd->repeated ) + if (!wrd->repeated) pfree(wrd->word); wrd++; } - VARATT_SIZEP(out)=ptr - ((char*)out); - return out; + VARATT_SIZEP(out) = ptr - ((char *) out); + return out; } -int -get_currcfg(void) { - Oid arg[1]={ TEXTOID }; +int +get_currcfg(void) +{ + Oid arg[1] = {TEXTOID}; const char *curlocale; - Datum pars[1]; - bool isnull; - int stat; + Datum pars[1]; + bool isnull; + int stat; - if ( current_cfg_id > 0 ) + if (current_cfg_id > 0) return current_cfg_id; SPI_connect(); - if ( !plan_getcfg_bylocale ) { - plan_getcfg_bylocale=SPI_saveplan( SPI_prepare( "select oid from pg_ts_cfg where locale = $1 ", 1, arg ) ); - if ( !plan_getcfg_bylocale ) + if (!plan_getcfg_bylocale) + { + plan_getcfg_bylocale = SPI_saveplan(SPI_prepare("select oid from pg_ts_cfg where locale = $1 ", 1, arg)); + if (!plan_getcfg_bylocale) /* internal error */ elog(ERROR, "SPI_prepare() failed"); } curlocale = setlocale(LC_CTYPE, NULL); - pars[0] = PointerGetDatum( char2text((char*)curlocale) ); + pars[0] = PointerGetDatum(char2text((char *) curlocale)); stat = SPI_execp(plan_getcfg_bylocale, pars, " ", 1); - if ( stat < 0 ) + if (stat < 0) /* internal error */ - elog (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed > 0 ) - current_cfg_id = DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) ); - else + elog(ERROR, "SPI_execp return %d", stat); + if (SPI_processed > 0) + current_cfg_id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); + else ereport(ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("could not find tsearch config by locale"))); @@ -487,39 +552,43 @@ get_currcfg(void) { } PG_FUNCTION_INFO_V1(set_curcfg); -Datum set_curcfg(PG_FUNCTION_ARGS); +Datum set_curcfg(PG_FUNCTION_ARGS); Datum -set_curcfg(PG_FUNCTION_ARGS) { - findcfg(PG_GETARG_OID(0)); - current_cfg_id=PG_GETARG_OID(0); - PG_RETURN_VOID(); +set_curcfg(PG_FUNCTION_ARGS) +{ + findcfg(PG_GETARG_OID(0)); + current_cfg_id = PG_GETARG_OID(0); + PG_RETURN_VOID(); } - + PG_FUNCTION_INFO_V1(set_curcfg_byname); -Datum set_curcfg_byname(PG_FUNCTION_ARGS); +Datum set_curcfg_byname(PG_FUNCTION_ARGS); Datum -set_curcfg_byname(PG_FUNCTION_ARGS) { - text *name=PG_GETARG_TEXT_P(0); - - DirectFunctionCall1( - set_curcfg, - ObjectIdGetDatum( name2id_cfg(name) ) - ); - PG_FREE_IF_COPY(name, 0); - PG_RETURN_VOID(); -} +set_curcfg_byname(PG_FUNCTION_ARGS) +{ + text *name = PG_GETARG_TEXT_P(0); + + DirectFunctionCall1( + set_curcfg, + ObjectIdGetDatum(name2id_cfg(name)) + ); + PG_FREE_IF_COPY(name, 0); + PG_RETURN_VOID(); +} PG_FUNCTION_INFO_V1(show_curcfg); -Datum show_curcfg(PG_FUNCTION_ARGS); +Datum show_curcfg(PG_FUNCTION_ARGS); Datum -show_curcfg(PG_FUNCTION_ARGS) { - PG_RETURN_OID( get_currcfg() ); +show_curcfg(PG_FUNCTION_ARGS) +{ + PG_RETURN_OID(get_currcfg()); } PG_FUNCTION_INFO_V1(reset_tsearch); -Datum reset_tsearch(PG_FUNCTION_ARGS); +Datum reset_tsearch(PG_FUNCTION_ARGS); Datum -reset_tsearch(PG_FUNCTION_ARGS) { - ts_error(NOTICE,"TSearch cache cleaned"); - PG_RETURN_VOID(); +reset_tsearch(PG_FUNCTION_ARGS) +{ + ts_error(NOTICE, "TSearch cache cleaned"); + PG_RETURN_VOID(); } diff --git a/contrib/tsearch2/ts_cfg.h b/contrib/tsearch2/ts_cfg.h index 01006c1f93..cde35ca2a6 100644 --- a/contrib/tsearch2/ts_cfg.h +++ b/contrib/tsearch2/ts_cfg.h @@ -3,66 +3,73 @@ #include "postgres.h" #include "query.h" -typedef struct { - int len; - Datum *dict_id; -} ListDictionary; +typedef struct +{ + int len; + Datum *dict_id; +} ListDictionary; -typedef struct { - Oid id; - Oid prs_id; - int len; - ListDictionary *map; +typedef struct +{ + Oid id; + Oid prs_id; + int len; + ListDictionary *map; } TSCfgInfo; -Oid name2id_cfg(text *name); -TSCfgInfo * findcfg(Oid id); -void init_cfg(Oid id, TSCfgInfo *cfg); -void reset_cfg(void); +Oid name2id_cfg(text *name); +TSCfgInfo *findcfg(Oid id); +void init_cfg(Oid id, TSCfgInfo * cfg); +void reset_cfg(void); -typedef struct { - uint16 len; - union { +typedef struct +{ + uint16 len; + union + { uint16 pos; - uint16 *apos; - } pos; - char *word; - uint32 alen; -} WORD; - -typedef struct { - WORD *words; - int4 lenwords; - int4 curwords; + uint16 *apos; + } pos; + char *word; + uint32 alen; +} WORD; + +typedef struct +{ + WORD *words; + int4 lenwords; + int4 curwords; int4 pos; -} PRSTEXT; +} PRSTEXT; -typedef struct { - uint16 len; - uint8 selected:1, - in:1, - skip:1, - replace:1, - repeated:1; - uint8 type; - char *word; - ITEM *item; -} HLWORD; - -typedef struct { - HLWORD *words; - int4 lenwords; - int4 curwords; - char *startsel; - char *stopsel; - int2 startsellen; - int2 stopsellen; -} HLPRSTEXT; +typedef struct +{ + uint16 len; + uint8 selected:1, + in:1, + skip:1, + replace:1, + repeated:1; + uint8 type; + char *word; + ITEM *item; +} HLWORD; -void hlparsetext(TSCfgInfo *cfg, HLPRSTEXT * prs, QUERYTYPE *query, char *buf, int4 buflen); -text* genhl(HLPRSTEXT * prs); +typedef struct +{ + HLWORD *words; + int4 lenwords; + int4 curwords; + char *startsel; + char *stopsel; + int2 startsellen; + int2 stopsellen; +} HLPRSTEXT; -void parsetext_v2(TSCfgInfo *cfg, PRSTEXT * prs, char *buf, int4 buflen); -int get_currcfg(void); +void hlparsetext(TSCfgInfo * cfg, HLPRSTEXT * prs, QUERYTYPE * query, char *buf, int4 buflen); +text *genhl(HLPRSTEXT * prs); + +void parsetext_v2(TSCfgInfo * cfg, PRSTEXT * prs, char *buf, int4 buflen); +int get_currcfg(void); #endif diff --git a/contrib/tsearch2/ts_stat.c b/contrib/tsearch2/ts_stat.c index a09e057214..47353fc579 100644 --- a/contrib/tsearch2/ts_stat.c +++ b/contrib/tsearch2/ts_stat.c @@ -10,108 +10,128 @@ #include "common.h" PG_FUNCTION_INFO_V1(tsstat_in); -Datum tsstat_in(PG_FUNCTION_ARGS); -Datum -tsstat_in(PG_FUNCTION_ARGS) { - tsstat *stat=palloc(STATHDRSIZE); - stat->len=STATHDRSIZE; - stat->size=0; +Datum tsstat_in(PG_FUNCTION_ARGS); +Datum +tsstat_in(PG_FUNCTION_ARGS) +{ + tsstat *stat = palloc(STATHDRSIZE); + + stat->len = STATHDRSIZE; + stat->size = 0; PG_RETURN_POINTER(stat); } PG_FUNCTION_INFO_V1(tsstat_out); -Datum tsstat_out(PG_FUNCTION_ARGS); -Datum -tsstat_out(PG_FUNCTION_ARGS) { +Datum tsstat_out(PG_FUNCTION_ARGS); +Datum +tsstat_out(PG_FUNCTION_ARGS) +{ ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("tsstat_out not implemented"))); PG_RETURN_NULL(); } -static WordEntry** -SEI_realloc( WordEntry** in, uint32 *len ) { - if ( *len==0 || in==NULL ) { - *len=8; - in=palloc( sizeof(WordEntry*)* (*len) ); - } else { +static WordEntry ** +SEI_realloc(WordEntry ** in, uint32 *len) +{ + if (*len == 0 || in == NULL) + { + *len = 8; + in = palloc(sizeof(WordEntry *) * (*len)); + } + else + { *len *= 2; - in=repalloc( in, sizeof(WordEntry*)* (*len) ); + in = repalloc(in, sizeof(WordEntry *) * (*len)); } return in; } static int -compareStatWord(StatEntry *a, WordEntry *b, tsstat *stat, tsvector *txt) { - if ( a->len == b->len ) +compareStatWord(StatEntry * a, WordEntry * b, tsstat * stat, tsvector * txt) +{ + if (a->len == b->len) return strncmp( - STATSTRPTR(stat) + a->pos, - STRPTR(txt) + b->pos, - a->len + STATSTRPTR(stat) + a->pos, + STRPTR(txt) + b->pos, + a->len ); - return ( a->len > b->len ) ? 1 : -1; + return (a->len > b->len) ? 1 : -1; } -static tsstat* -formstat(tsstat *stat, tsvector *txt, WordEntry** entry, uint32 len) { - tsstat *newstat; - uint32 totallen, nentry; - uint32 slen=0; - WordEntry **ptr=entry; - char *curptr; - StatEntry *sptr,*nptr; +static tsstat * +formstat(tsstat * stat, tsvector * txt, WordEntry ** entry, uint32 len) +{ + tsstat *newstat; + uint32 totallen, + nentry; + uint32 slen = 0; + WordEntry **ptr = entry; + char *curptr; + StatEntry *sptr, + *nptr; - while(ptr-entrylen; ptr++; } - nentry=stat->size + len; - slen+=STATSTRSIZE(stat); - totallen=CALCSTATSIZE(nentry,slen); - newstat=palloc(totallen); - newstat->len=totallen; - newstat->size=nentry; + nentry = stat->size + len; + slen += STATSTRSIZE(stat); + totallen = CALCSTATSIZE(nentry, slen); + newstat = palloc(totallen); + newstat->len = totallen; + newstat->size = nentry; memcpy(STATSTRPTR(newstat), STATSTRPTR(stat), STATSTRSIZE(stat)); - curptr=STATSTRPTR(newstat) + STATSTRSIZE(stat); + curptr = STATSTRPTR(newstat) + STATSTRSIZE(stat); - ptr=entry; - sptr=STATPTR(stat); - nptr=STATPTR(newstat); + ptr = entry; + sptr = STATPTR(stat); + nptr = STATPTR(newstat); - if ( len == 1 ) { - StatEntry *StopLow = STATPTR(stat); - StatEntry *StopHigh = (StatEntry*)STATSTRPTR(stat); + if (len == 1) + { + StatEntry *StopLow = STATPTR(stat); + StatEntry *StopHigh = (StatEntry *) STATSTRPTR(stat); - while (StopLow < StopHigh) { - sptr=StopLow + (StopHigh - StopLow) / 2; - if ( compareStatWord(sptr,*ptr,stat,txt) < 0 ) + while (StopLow < StopHigh) + { + sptr = StopLow + (StopHigh - StopLow) / 2; + if (compareStatWord(sptr, *ptr, stat, txt) < 0) StopLow = sptr + 1; else - StopHigh = sptr; + StopHigh = sptr; } - nptr =STATPTR(newstat) + (StopLow-STATPTR(stat)); - memcpy( STATPTR(newstat), STATPTR(stat), sizeof(StatEntry) * (StopLow-STATPTR(stat)) ); - nptr->nentry=POSDATALEN(txt,*ptr); - if ( nptr->nentry==0 ) - nptr->nentry=1; - nptr->ndoc=1; - nptr->len=(*ptr)->len; + nptr = STATPTR(newstat) + (StopLow - STATPTR(stat)); + memcpy(STATPTR(newstat), STATPTR(stat), sizeof(StatEntry) * (StopLow - STATPTR(stat))); + nptr->nentry = POSDATALEN(txt, *ptr); + if (nptr->nentry == 0) + nptr->nentry = 1; + nptr->ndoc = 1; + nptr->len = (*ptr)->len; memcpy(curptr, STRPTR(txt) + (*ptr)->pos, nptr->len); nptr->pos = curptr - STATSTRPTR(newstat); - memcpy( nptr+1, StopLow, sizeof(StatEntry) * ( ((StatEntry*)STATSTRPTR(stat))-StopLow ) ); - } else { - while( sptr-STATPTR(stat) < stat->size && ptr-entrysize && ptr - entry < len) + { + if (compareStatWord(sptr, *ptr, stat, txt) < 0) + { memcpy(nptr, sptr, sizeof(StatEntry)); sptr++; - } else { - nptr->nentry=POSDATALEN(txt,*ptr); - if ( nptr->nentry==0 ) - nptr->nentry=1; - nptr->ndoc=1; - nptr->len=(*ptr)->len; + } + else + { + nptr->nentry = POSDATALEN(txt, *ptr); + if (nptr->nentry == 0) + nptr->nentry = 1; + nptr->ndoc = 1; + nptr->len = (*ptr)->len; memcpy(curptr, STRPTR(txt) + (*ptr)->pos, nptr->len); nptr->pos = curptr - STATSTRPTR(newstat); curptr += nptr->len; @@ -120,138 +140,168 @@ formstat(tsstat *stat, tsvector *txt, WordEntry** entry, uint32 len) { nptr++; } - memcpy( nptr, sptr, sizeof(StatEntry)*( stat->size - (sptr-STATPTR(stat)) ) ); - - while(ptr-entrynentry=POSDATALEN(txt,*ptr); - if ( nptr->nentry==0 ) - nptr->nentry=1; - nptr->ndoc=1; - nptr->len=(*ptr)->len; + memcpy(nptr, sptr, sizeof(StatEntry) * (stat->size - (sptr - STATPTR(stat)))); + + while (ptr - entry < len) + { + nptr->nentry = POSDATALEN(txt, *ptr); + if (nptr->nentry == 0) + nptr->nentry = 1; + nptr->ndoc = 1; + nptr->len = (*ptr)->len; memcpy(curptr, STRPTR(txt) + (*ptr)->pos, nptr->len); nptr->pos = curptr - STATSTRPTR(newstat); curptr += nptr->len; - ptr++; nptr++; + ptr++; + nptr++; } } return newstat; -} +} PG_FUNCTION_INFO_V1(ts_accum); -Datum ts_accum(PG_FUNCTION_ARGS); -Datum -ts_accum(PG_FUNCTION_ARGS) { - tsstat *newstat,*stat= (tsstat*)PG_GETARG_POINTER(0); - tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); - WordEntry **newentry=NULL; - uint32 len=0, cur=0; - StatEntry *sptr; - WordEntry *wptr; +Datum ts_accum(PG_FUNCTION_ARGS); +Datum +ts_accum(PG_FUNCTION_ARGS) +{ + tsstat *newstat, + *stat = (tsstat *) PG_GETARG_POINTER(0); + tsvector *txt = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); + WordEntry **newentry = NULL; + uint32 len = 0, + cur = 0; + StatEntry *sptr; + WordEntry *wptr; - if ( stat==NULL || PG_ARGISNULL(0) ) { /* Init in first */ - stat=palloc(STATHDRSIZE); - stat->len=STATHDRSIZE; - stat->size=0; + if (stat == NULL || PG_ARGISNULL(0)) + { /* Init in first */ + stat = palloc(STATHDRSIZE); + stat->len = STATHDRSIZE; + stat->size = 0; } /* simple check of correctness */ - if ( txt==NULL || PG_ARGISNULL(1) || txt->size==0 ) { - PG_FREE_IF_COPY(txt,1); + if (txt == NULL || PG_ARGISNULL(1) || txt->size == 0) + { + PG_FREE_IF_COPY(txt, 1); PG_RETURN_POINTER(stat); } - sptr=STATPTR(stat); - wptr=ARRPTR(txt); + sptr = STATPTR(stat); + wptr = ARRPTR(txt); - if ( stat->size < 100*txt->size ) { /* merge */ - while( sptr-STATPTR(stat) < stat->size && wptr-ARRPTR(txt) < txt->size ) { - int cmp = compareStatWord(sptr,wptr,stat,txt); - if ( cmp<0 ) { + if (stat->size < 100 * txt->size) + { /* merge */ + while (sptr - STATPTR(stat) < stat->size && wptr - ARRPTR(txt) < txt->size) + { + int cmp = compareStatWord(sptr, wptr, stat, txt); + + if (cmp < 0) sptr++; - } else if ( cmp==0 ) { - int n=POSDATALEN(txt,wptr); - - if (n==0) n=1; + else if (cmp == 0) + { + int n = POSDATALEN(txt, wptr); + + if (n == 0) + n = 1; sptr->ndoc++; - sptr->nentry +=n ; - sptr++; wptr++; - } else { - if ( cur==len ) - newentry=SEI_realloc(newentry, &len); - newentry[cur]=wptr; - wptr++; cur++; + sptr->nentry += n; + sptr++; + wptr++; + } + else + { + if (cur == len) + newentry = SEI_realloc(newentry, &len); + newentry[cur] = wptr; + wptr++; + cur++; } } - while( wptr-ARRPTR(txt) < txt->size ) { - if ( cur==len ) - newentry=SEI_realloc(newentry, &len); - newentry[cur]=wptr; - wptr++; cur++; + while (wptr - ARRPTR(txt) < txt->size) + { + if (cur == len) + newentry = SEI_realloc(newentry, &len); + newentry[cur] = wptr; + wptr++; + cur++; } - } else { /* search */ - while( wptr-ARRPTR(txt) < txt->size ) { - StatEntry *StopLow = STATPTR(stat); - StatEntry *StopHigh = (StatEntry*)STATSTRPTR(stat); - int cmp; + } + else + { /* search */ + while (wptr - ARRPTR(txt) < txt->size) + { + StatEntry *StopLow = STATPTR(stat); + StatEntry *StopHigh = (StatEntry *) STATSTRPTR(stat); + int cmp; - while (StopLow < StopHigh) { - sptr=StopLow + (StopHigh - StopLow) / 2; - cmp = compareStatWord(sptr,wptr,stat,txt); - if (cmp==0) { - int n=POSDATALEN(txt,wptr); - if (n==0) n=1; + while (StopLow < StopHigh) + { + sptr = StopLow + (StopHigh - StopLow) / 2; + cmp = compareStatWord(sptr, wptr, stat, txt); + if (cmp == 0) + { + int n = POSDATALEN(txt, wptr); + + if (n == 0) + n = 1; sptr->ndoc++; - sptr->nentry +=n ; + sptr->nentry += n; break; - } else if ( cmp < 0 ) + } + else if (cmp < 0) StopLow = sptr + 1; else - StopHigh = sptr; + StopHigh = sptr; } - - if ( StopLow >= StopHigh ) { /* not found */ - if ( cur==len ) - newentry=SEI_realloc(newentry, &len); - newentry[cur]=wptr; + + if (StopLow >= StopHigh) + { /* not found */ + if (cur == len) + newentry = SEI_realloc(newentry, &len); + newentry[cur] = wptr; cur++; } wptr++; - } + } } - - if ( cur==0 ) { /* no new words */ - PG_FREE_IF_COPY(txt,1); + + if (cur == 0) + { /* no new words */ + PG_FREE_IF_COPY(txt, 1); PG_RETURN_POINTER(stat); } newstat = formstat(stat, txt, newentry, cur); pfree(newentry); - PG_FREE_IF_COPY(txt,1); + PG_FREE_IF_COPY(txt, 1); /* pfree(stat); */ PG_RETURN_POINTER(newstat); } -typedef struct { - uint32 cur; - tsvector *stat; -} StatStorage; +typedef struct +{ + uint32 cur; + tsvector *stat; +} StatStorage; static void -ts_setup_firstcall(FuncCallContext *funcctx, tsstat *stat) { - TupleDesc tupdesc; - MemoryContext oldcontext; - StatStorage *st; - +ts_setup_firstcall(FuncCallContext *funcctx, tsstat * stat) +{ + TupleDesc tupdesc; + MemoryContext oldcontext; + StatStorage *st; + oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); - st=palloc( sizeof(StatStorage) ); - st->cur=0; - st->stat=palloc( stat->len ); + st = palloc(sizeof(StatStorage)); + st->cur = 0; + st->stat = palloc(stat->len); memcpy(st->stat, stat, stat->len); - funcctx->user_fctx = (void*)st; + funcctx->user_fctx = (void *) st; tupdesc = RelationNameGetTupleDesc("statinfo"); funcctx->slot = TupleDescGetSlot(tupdesc); funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc); @@ -260,162 +310,175 @@ ts_setup_firstcall(FuncCallContext *funcctx, tsstat *stat) { static Datum -ts_process_call(FuncCallContext *funcctx) { - StatStorage *st; - st=(StatStorage*)funcctx->user_fctx; +ts_process_call(FuncCallContext *funcctx) +{ + StatStorage *st; - if ( st->cur < st->stat->size ) { - Datum result; - char* values[3]; - char ndoc[16]; - char nentry[16]; - StatEntry *entry=STATPTR(st->stat) + st->cur; - HeapTuple tuple; + st = (StatStorage *) funcctx->user_fctx; - values[1]=ndoc; - sprintf(ndoc,"%d",entry->ndoc); - values[2]=nentry; - sprintf(nentry,"%d",entry->nentry); - values[0]=palloc( entry->len+1 ); - memcpy( values[0], STATSTRPTR(st->stat)+entry->pos, entry->len); - (values[0])[entry->len]='\0'; + if (st->cur < st->stat->size) + { + Datum result; + char *values[3]; + char ndoc[16]; + char nentry[16]; + StatEntry *entry = STATPTR(st->stat) + st->cur; + HeapTuple tuple; + + values[1] = ndoc; + sprintf(ndoc, "%d", entry->ndoc); + values[2] = nentry; + sprintf(nentry, "%d", entry->nentry); + values[0] = palloc(entry->len + 1); + memcpy(values[0], STATSTRPTR(st->stat) + entry->pos, entry->len); + (values[0])[entry->len] = '\0'; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = TupleGetDatum(funcctx->slot, tuple); pfree(values[0]); st->cur++; - return result; - } else { + return result; + } + else + { pfree(st->stat); pfree(st); } - - return (Datum)0; + + return (Datum) 0; } PG_FUNCTION_INFO_V1(ts_accum_finish); -Datum ts_accum_finish(PG_FUNCTION_ARGS); -Datum -ts_accum_finish(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +Datum ts_accum_finish(PG_FUNCTION_ARGS); +Datum +ts_accum_finish(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; - if (SRF_IS_FIRSTCALL()) { + if (SRF_IS_FIRSTCALL()) + { funcctx = SRF_FIRSTCALL_INIT(); - ts_setup_firstcall(funcctx, (tsstat*)PG_GETARG_POINTER(0) ); + ts_setup_firstcall(funcctx, (tsstat *) PG_GETARG_POINTER(0)); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=ts_process_call(funcctx)) != (Datum)0 ) + if ((result = ts_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } -static Oid tiOid=InvalidOid; -static void -get_ti_Oid(void) { - int ret; - bool isnull; +static Oid tiOid = InvalidOid; +static void +get_ti_Oid(void) +{ + int ret; + bool isnull; - if ( (ret = SPI_exec("select oid from pg_type where typname='tsvector'",1)) < 0 ) + if ((ret = SPI_exec("select oid from pg_type where typname='tsvector'", 1)) < 0) /* internal error */ elog(ERROR, "SPI_exec to get tsvector oid returns %d", ret); - if ( SPI_processed<0 ) + if (SPI_processed < 0) /* internal error */ elog(ERROR, "There is no tsvector type"); - tiOid = DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) ); - if ( tiOid==InvalidOid ) + tiOid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); + if (tiOid == InvalidOid) /* internal error */ elog(ERROR, "tsvector type has InvalidOid"); } -static tsstat* -ts_stat_sql(text *txt) { - char *query=text2char(txt); - int i; - tsstat *newstat,*stat; - bool isnull; - Portal portal; - void *plan; +static tsstat * +ts_stat_sql(text *txt) +{ + char *query = text2char(txt); + int i; + tsstat *newstat, + *stat; + bool isnull; + Portal portal; + void *plan; - if ( tiOid==InvalidOid ) + if (tiOid == InvalidOid) get_ti_Oid(); - if ( (plan = SPI_prepare(query,0,NULL))==NULL ) + if ((plan = SPI_prepare(query, 0, NULL)) == NULL) /* internal error */ - elog(ERROR, "SPI_prepare('%s') returns NULL",query); + elog(ERROR, "SPI_prepare('%s') returns NULL", query); - if ( (portal = SPI_cursor_open(NULL, plan, NULL, NULL)) == NULL ) + if ((portal = SPI_cursor_open(NULL, plan, NULL, NULL)) == NULL) /* internal error */ - elog(ERROR, "SPI_cursor_open('%s') returns NULL",query); + elog(ERROR, "SPI_cursor_open('%s') returns NULL", query); SPI_cursor_fetch(portal, true, 100); - if ( SPI_tuptable->tupdesc->natts != 1 ) + if (SPI_tuptable->tupdesc->natts != 1) /* internal error */ elog(ERROR, "number of fields doesn't equal to 1"); - if ( SPI_gettypeid(SPI_tuptable->tupdesc, 1) != tiOid ) + if (SPI_gettypeid(SPI_tuptable->tupdesc, 1) != tiOid) /* internal error */ elog(ERROR, "column isn't of tsvector type"); - stat=palloc(STATHDRSIZE); - stat->len=STATHDRSIZE; - stat->size=0; + stat = palloc(STATHDRSIZE); + stat->len = STATHDRSIZE; + stat->size = 0; - while(SPI_processed>0) { - for(i=0;ivals[i], SPI_tuptable->tupdesc, 1, &isnull); + while (SPI_processed > 0) + { + for (i = 0; i < SPI_processed; i++) + { + Datum data = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); - if ( !isnull ) { - newstat = (tsstat*)DatumGetPointer(DirectFunctionCall2( - ts_accum, - PointerGetDatum(stat), - data - )); - if ( stat!=newstat && stat ) + if (!isnull) + { + newstat = (tsstat *) DatumGetPointer(DirectFunctionCall2( + ts_accum, + PointerGetDatum(stat), + data + )); + if (stat != newstat && stat) pfree(stat); - stat=newstat; + stat = newstat; } - } + } SPI_freetuptable(SPI_tuptable); - SPI_cursor_fetch(portal, true, 100); - } + SPI_cursor_fetch(portal, true, 100); + } SPI_freetuptable(SPI_tuptable); SPI_cursor_close(portal); SPI_freeplan(plan); pfree(query); - return stat; + return stat; } PG_FUNCTION_INFO_V1(ts_stat); -Datum ts_stat(PG_FUNCTION_ARGS); -Datum -ts_stat(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +Datum ts_stat(PG_FUNCTION_ARGS); +Datum +ts_stat(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; + + if (SRF_IS_FIRSTCALL()) + { + tsstat *stat; + text *txt = PG_GETARG_TEXT_P(0); - if (SRF_IS_FIRSTCALL()) { - tsstat *stat; - text *txt=PG_GETARG_TEXT_P(0); - funcctx = SRF_FIRSTCALL_INIT(); SPI_connect(); stat = ts_stat_sql(txt); - PG_FREE_IF_COPY(txt,0); - ts_setup_firstcall(funcctx, stat ); + PG_FREE_IF_COPY(txt, 0); + ts_setup_firstcall(funcctx, stat); SPI_finish(); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=ts_process_call(funcctx)) != (Datum)0 ) + if ((result = ts_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } - - diff --git a/contrib/tsearch2/ts_stat.h b/contrib/tsearch2/ts_stat.h index 023a83346c..37d1e7b660 100644 --- a/contrib/tsearch2/ts_stat.h +++ b/contrib/tsearch2/ts_stat.h @@ -8,14 +8,16 @@ #include "utils/builtins.h" #include "storage/bufpage.h" -typedef struct { - uint32 len; - uint32 pos; - uint32 ndoc; - uint32 nentry; +typedef struct +{ + uint32 len; + uint32 pos; + uint32 ndoc; + uint32 nentry; } StatEntry; -typedef struct { +typedef struct +{ int4 len; int4 size; char data[1]; diff --git a/contrib/tsearch2/tsvector.c b/contrib/tsearch2/tsvector.c index 7c258f1305..c8002c0ab3 100644 --- a/contrib/tsearch2/tsvector.c +++ b/contrib/tsearch2/tsvector.c @@ -31,8 +31,10 @@ Datum tsvector_out(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(to_tsvector); Datum to_tsvector(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(to_tsvector_current); Datum to_tsvector_current(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(to_tsvector_name); Datum to_tsvector_name(PG_FUNCTION_ARGS); @@ -45,32 +47,38 @@ Datum tsvector_length(PG_FUNCTION_ARGS); /* * in/out text index type */ -static int -comparePos(const void *a, const void *b) { - if ( ((WordEntryPos *) a)->pos == ((WordEntryPos *) b)->pos ) +static int +comparePos(const void *a, const void *b) +{ + if (((WordEntryPos *) a)->pos == ((WordEntryPos *) b)->pos) return 1; - return ( ((WordEntryPos *) a)->pos > ((WordEntryPos *) b)->pos ) ? 1 : -1; + return (((WordEntryPos *) a)->pos > ((WordEntryPos *) b)->pos) ? 1 : -1; } static int -uniquePos(WordEntryPos *a, int4 l) { - WordEntryPos *ptr, *res; +uniquePos(WordEntryPos * a, int4 l) +{ + WordEntryPos *ptr, + *res; - res=a; - if (l==1) + res = a; + if (l == 1) return l; qsort((void *) a, l, sizeof(WordEntryPos), comparePos); ptr = a + 1; - while (ptr - a < l) { - if ( ptr->pos != res->pos ) { + while (ptr - a < l) + { + if (ptr->pos != res->pos) + { res++; res->pos = ptr->pos; res->weight = ptr->weight; - if ( res-a >= MAXNUMPOS-1 || res->pos == MAXENTRYPOS-1 ) + if (res - a >= MAXNUMPOS - 1 || res->pos == MAXENTRYPOS - 1) break; - } else if ( ptr->weight > res->weight ) + } + else if (ptr->weight > res->weight) res->weight = ptr->weight; ptr++; } @@ -81,27 +89,29 @@ static char *BufferStr; static int compareentry(const void *a, const void *b) { - if ( ((WordEntryIN *) a)->entry.len == ((WordEntryIN *) b)->entry.len) + if (((WordEntryIN *) a)->entry.len == ((WordEntryIN *) b)->entry.len) { return strncmp( &BufferStr[((WordEntryIN *) a)->entry.pos], &BufferStr[((WordEntryIN *) b)->entry.pos], ((WordEntryIN *) a)->entry.len); } - return ( ((WordEntryIN *) a)->entry.len > ((WordEntryIN *) b)->entry.len ) ? 1 : -1; + return (((WordEntryIN *) a)->entry.len > ((WordEntryIN *) b)->entry.len) ? 1 : -1; } static int uniqueentry(WordEntryIN * a, int4 l, char *buf, int4 *outbuflen) { - WordEntryIN *ptr, + WordEntryIN *ptr, *res; res = a; - if (l == 1) { - if ( a->entry.haspos ) { - *(uint16*)(a->pos) = uniquePos( &(a->pos[1]), *(uint16*)(a->pos)); - *outbuflen = SHORTALIGN(res->entry.len) + (*(uint16*)(a->pos) +1 )*sizeof(WordEntryPos); + if (l == 1) + { + if (a->entry.haspos) + { + *(uint16 *) (a->pos) = uniquePos(&(a->pos[1]), *(uint16 *) (a->pos)); + *outbuflen = SHORTALIGN(res->entry.len) + (*(uint16 *) (a->pos) + 1) * sizeof(WordEntryPos); } return l; } @@ -115,31 +125,39 @@ uniqueentry(WordEntryIN * a, int4 l, char *buf, int4 *outbuflen) if (!(ptr->entry.len == res->entry.len && strncmp(&buf[ptr->entry.pos], &buf[res->entry.pos], res->entry.len) == 0)) { - if ( res->entry.haspos ) { - *(uint16*)(res->pos) = uniquePos( &(res->pos[1]), *(uint16*)(res->pos)); - *outbuflen += *(uint16*)(res->pos) * sizeof(WordEntryPos); + if (res->entry.haspos) + { + *(uint16 *) (res->pos) = uniquePos(&(res->pos[1]), *(uint16 *) (res->pos)); + *outbuflen += *(uint16 *) (res->pos) * sizeof(WordEntryPos); } *outbuflen += SHORTALIGN(res->entry.len); res++; - memcpy(res,ptr,sizeof(WordEntryIN)); - } else if ( ptr->entry.haspos ){ - if ( res->entry.haspos ) { - int4 len=*(uint16*)(ptr->pos) + 1 + *(uint16*)(res->pos); - res->pos=(WordEntryPos*)repalloc( res->pos, len*sizeof(WordEntryPos)); - memcpy( &(res->pos[ *(uint16*)(res->pos) + 1 ]), - &(ptr->pos[1]), *(uint16*)(ptr->pos) * sizeof(WordEntryPos)); - *(uint16*)(res->pos) += *(uint16*)(ptr->pos); - pfree( ptr->pos ); - } else { - res->entry.haspos=1; + memcpy(res, ptr, sizeof(WordEntryIN)); + } + else if (ptr->entry.haspos) + { + if (res->entry.haspos) + { + int4 len = *(uint16 *) (ptr->pos) + 1 + *(uint16 *) (res->pos); + + res->pos = (WordEntryPos *) repalloc(res->pos, len * sizeof(WordEntryPos)); + memcpy(&(res->pos[*(uint16 *) (res->pos) + 1]), + &(ptr->pos[1]), *(uint16 *) (ptr->pos) * sizeof(WordEntryPos)); + *(uint16 *) (res->pos) += *(uint16 *) (ptr->pos); + pfree(ptr->pos); + } + else + { + res->entry.haspos = 1; res->pos = ptr->pos; } } ptr++; } - if ( res->entry.haspos ) { - *(uint16*)(res->pos) = uniquePos( &(res->pos[1]), *(uint16*)(res->pos)); - *outbuflen += *(uint16*)(res->pos) * sizeof(WordEntryPos); + if (res->entry.haspos) + { + *(uint16 *) (res->pos) = uniquePos(&(res->pos[1]), *(uint16 *) (res->pos)); + *outbuflen += *(uint16 *) (res->pos) * sizeof(WordEntryPos); } *outbuflen += SHORTALIGN(res->entry.len); @@ -150,7 +168,7 @@ uniqueentry(WordEntryIN * a, int4 l, char *buf, int4 *outbuflen) #define WAITENDWORD 2 #define WAITNEXTCHAR 3 #define WAITENDCMPLX 4 -#define WAITPOSINFO 5 +#define WAITPOSINFO 5 #define INPOSINFO 6 #define WAITPOSDELIM 7 @@ -172,7 +190,7 @@ gettoken_tsvector(TI_IN_STATE * state) state->curpos = state->word; state->state = WAITWORD; - state->alen=0; + state->alen = 0; while (1) { @@ -228,14 +246,16 @@ gettoken_tsvector(TI_IN_STATE * state) (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); *(state->curpos) = '\0'; - return 1; - } else if ( *(state->prsbuf) == ':' ) { + return 1; + } + else if (*(state->prsbuf) == ':') + { if (state->curpos == state->word) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); *(state->curpos) = '\0'; - if ( state->oprisdelim ) + if (state->oprisdelim) return 1; else state->state = INPOSINFO; @@ -257,10 +277,12 @@ gettoken_tsvector(TI_IN_STATE * state) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); - if ( state->oprisdelim ) { + if (state->oprisdelim) + { state->prsbuf++; return 1; - } else + } + else state->state = WAITPOSINFO; } else if (*(state->prsbuf) == '\\') @@ -278,67 +300,87 @@ gettoken_tsvector(TI_IN_STATE * state) *(state->curpos) = *(state->prsbuf); state->curpos++; } - } else if (state->state == WAITPOSINFO) { - if ( *(state->prsbuf) == ':' ) - state->state=INPOSINFO; + } + else if (state->state == WAITPOSINFO) + { + if (*(state->prsbuf) == ':') + state->state = INPOSINFO; else return 1; - } else if (state->state == INPOSINFO) { - if ( isdigit(*(state->prsbuf)) ) { - if ( state->alen==0 ) { - state->alen=4; - state->pos = (WordEntryPos*)palloc( sizeof(WordEntryPos)*state->alen ); - *(uint16*)(state->pos)=0; - } else if ( *(uint16*)(state->pos) +1 >= state->alen ) { - state->alen *= 2; - state->pos = (WordEntryPos*)repalloc( state->pos, sizeof(WordEntryPos)*state->alen ); + } + else if (state->state == INPOSINFO) + { + if (isdigit(*(state->prsbuf))) + { + if (state->alen == 0) + { + state->alen = 4; + state->pos = (WordEntryPos *) palloc(sizeof(WordEntryPos) * state->alen); + *(uint16 *) (state->pos) = 0; } - ( *(uint16*)(state->pos) )++; - state->pos[ *(uint16*)(state->pos) ].pos = LIMITPOS(atoi(state->prsbuf)); - if ( state->pos[ *(uint16*)(state->pos) ].pos == 0 ) + else if (*(uint16 *) (state->pos) + 1 >= state->alen) + { + state->alen *= 2; + state->pos = (WordEntryPos *) repalloc(state->pos, sizeof(WordEntryPos) * state->alen); + } + (*(uint16 *) (state->pos))++; + state->pos[*(uint16 *) (state->pos)].pos = LIMITPOS(atoi(state->prsbuf)); + if (state->pos[*(uint16 *) (state->pos)].pos == 0) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("wrong position info"))); - state->pos[ *(uint16*)(state->pos) ].weight = 0; + state->pos[*(uint16 *) (state->pos)].weight = 0; state->state = WAITPOSDELIM; - } else + } + else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); - } else if (state->state == WAITPOSDELIM) { - if ( *(state->prsbuf) == ',' ) { + } + else if (state->state == WAITPOSDELIM) + { + if (*(state->prsbuf) == ',') state->state = INPOSINFO; - } else if ( tolower(*(state->prsbuf)) == 'a' || *(state->prsbuf)=='*' ) { - if ( state->pos[ *(uint16*)(state->pos) ].weight ) + else if (tolower(*(state->prsbuf)) == 'a' || *(state->prsbuf) == '*') + { + if (state->pos[*(uint16 *) (state->pos)].weight) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); - state->pos[ *(uint16*)(state->pos) ].weight = 3; - } else if ( tolower(*(state->prsbuf)) == 'b' ) { - if ( state->pos[ *(uint16*)(state->pos) ].weight ) + state->pos[*(uint16 *) (state->pos)].weight = 3; + } + else if (tolower(*(state->prsbuf)) == 'b') + { + if (state->pos[*(uint16 *) (state->pos)].weight) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); - state->pos[ *(uint16*)(state->pos) ].weight = 2; - } else if ( tolower(*(state->prsbuf)) == 'c' ) { - if ( state->pos[ *(uint16*)(state->pos) ].weight ) + state->pos[*(uint16 *) (state->pos)].weight = 2; + } + else if (tolower(*(state->prsbuf)) == 'c') + { + if (state->pos[*(uint16 *) (state->pos)].weight) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); - state->pos[ *(uint16*)(state->pos) ].weight = 1; - } else if ( tolower(*(state->prsbuf)) == 'd' ) { - if ( state->pos[ *(uint16*)(state->pos) ].weight ) + state->pos[*(uint16 *) (state->pos)].weight = 1; + } + else if (tolower(*(state->prsbuf)) == 'd') + { + if (state->pos[*(uint16 *) (state->pos)].weight) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); - state->pos[ *(uint16*)(state->pos) ].weight = 0; - } else if ( isspace(*(state->prsbuf)) || *(state->prsbuf) == '\0' ) { + state->pos[*(uint16 *) (state->pos)].weight = 0; + } + else if (isspace(*(state->prsbuf)) || *(state->prsbuf) == '\0') return 1; - } else if ( !isdigit(*(state->prsbuf)) ) + else if (!isdigit(*(state->prsbuf))) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); - } else + } + else /* internal error */ elog(ERROR, "internal error"); state->prsbuf++; @@ -352,11 +394,11 @@ tsvector_in(PG_FUNCTION_ARGS) { char *buf = PG_GETARG_CSTRING(0); TI_IN_STATE state; - WordEntryIN *arr; + WordEntryIN *arr; WordEntry *inarr; int4 len = 0, totallen = 64; - tsvector *in; + tsvector *in; char *tmpbuf, *cur; int4 i, @@ -388,28 +430,30 @@ tsvector_in(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("word is too long"))); - arr[len].entry.len= state.curpos - state.word; + arr[len].entry.len = state.curpos - state.word; if (cur - tmpbuf > MAXSTRPOS) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("too long value"))); - arr[len].entry.pos=cur - tmpbuf; + arr[len].entry.pos = cur - tmpbuf; memcpy((void *) cur, (void *) state.word, arr[len].entry.len); cur += arr[len].entry.len; - if ( state.alen ) { - arr[len].entry.haspos=1; + if (state.alen) + { + arr[len].entry.haspos = 1; arr[len].pos = state.pos; - } else - arr[len].entry.haspos=0; + } + else + arr[len].entry.haspos = 0; len++; } pfree(state.word); - if ( len > 0 ) + if (len > 0) len = uniqueentry(arr, len, tmpbuf, &buflen); totallen = CALCDATASIZE(len, buflen); in = (tsvector *) palloc(totallen); - memset(in,0,totallen); + memset(in, 0, totallen); in->len = totallen; in->size = len; cur = STRPTR(in); @@ -417,14 +461,15 @@ tsvector_in(PG_FUNCTION_ARGS) for (i = 0; i < len; i++) { memcpy((void *) cur, (void *) &tmpbuf[arr[i].entry.pos], arr[i].entry.len); - arr[i].entry.pos=cur - STRPTR(in); + arr[i].entry.pos = cur - STRPTR(in); cur += SHORTALIGN(arr[i].entry.len); - if ( arr[i].entry.haspos ) { - memcpy( cur, arr[i].pos, (*(uint16*)arr[i].pos + 1) * sizeof(WordEntryPos)); - cur += (*(uint16*)arr[i].pos + 1) * sizeof(WordEntryPos); - pfree( arr[i].pos ); + if (arr[i].entry.haspos) + { + memcpy(cur, arr[i].pos, (*(uint16 *) arr[i].pos + 1) * sizeof(WordEntryPos)); + cur += (*(uint16 *) arr[i].pos + 1) * sizeof(WordEntryPos); + pfree(arr[i].pos); } - memcpy( &(inarr[i]), &(arr[i].entry), sizeof(WordEntry) ); + memcpy(&(inarr[i]), &(arr[i].entry), sizeof(WordEntry)); } pfree(tmpbuf); pfree(arr); @@ -434,7 +479,7 @@ tsvector_in(PG_FUNCTION_ARGS) Datum tsvector_length(PG_FUNCTION_ARGS) { - tsvector *in = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); + tsvector *in = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); int4 ret = in->size; PG_FREE_IF_COPY(in, 0); @@ -444,26 +489,28 @@ tsvector_length(PG_FUNCTION_ARGS) Datum tsvector_out(PG_FUNCTION_ARGS) { - tsvector *out = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); + tsvector *out = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); char *outbuf; int4 i, j, - lenbuf = 0, pp; + lenbuf = 0, + pp; WordEntry *ptr = ARRPTR(out); char *curin, *curout; - lenbuf=out->size * 2 /* '' */ + out->size - 1 /* space */ + 2 /*\0*/; - for (i = 0; i < out->size; i++) { - lenbuf += ptr[i].len*2 /*for escape */; - if ( ptr[i].haspos ) - lenbuf += 7*POSDATALEN(out, &(ptr[i])); - } + lenbuf = out->size * 2 /* '' */ + out->size - 1 /* space */ + 2 /* \0 */ ; + for (i = 0; i < out->size; i++) + { + lenbuf += ptr[i].len * 2 /* for escape */ ; + if (ptr[i].haspos) + lenbuf += 7 * POSDATALEN(out, &(ptr[i])); + } curout = outbuf = (char *) palloc(lenbuf); for (i = 0; i < out->size; i++) { - curin = STRPTR(out)+ptr->pos; + curin = STRPTR(out) + ptr->pos; if (i != 0) *curout++ = ' '; *curout++ = '\''; @@ -481,27 +528,40 @@ tsvector_out(PG_FUNCTION_ARGS) *curout++ = *curin++; } *curout++ = '\''; - if ( (pp=POSDATALEN(out,ptr)) != 0 ) { + if ((pp = POSDATALEN(out, ptr)) != 0) + { WordEntryPos *wptr; + *curout++ = ':'; - wptr=POSDATAPTR(out,ptr); - while(pp) { - sprintf(curout,"%d",wptr->pos); - curout=strchr(curout,'\0'); - switch( wptr->weight ) { - case 3: *curout++ = 'A'; break; - case 2: *curout++ = 'B'; break; - case 1: *curout++ = 'C'; break; - case 0: - default: break; + wptr = POSDATAPTR(out, ptr); + while (pp) + { + sprintf(curout, "%d", wptr->pos); + curout = strchr(curout, '\0'); + switch (wptr->weight) + { + case 3: + *curout++ = 'A'; + break; + case 2: + *curout++ = 'B'; + break; + case 1: + *curout++ = 'C'; + break; + case 0: + default: + break; } - if ( pp>1 ) *curout++ = ','; - pp--; wptr++; + if (pp > 1) + *curout++ = ','; + pp--; + wptr++; } } ptr++; } - *curout='\0'; + *curout = '\0'; outbuf[lenbuf - 1] = '\0'; PG_FREE_IF_COPY(out, 0); PG_RETURN_POINTER(outbuf); @@ -510,13 +570,15 @@ tsvector_out(PG_FUNCTION_ARGS) static int compareWORD(const void *a, const void *b) { - if (((WORD *) a)->len == ((WORD *) b)->len) { - int res = strncmp( - ((WORD *) a)->word, - ((WORD *) b)->word, - ((WORD *) b)->len); - if ( res==0 ) - return ( ((WORD *) a)->pos.pos > ((WORD *) b)->pos.pos ) ? 1 : -1; + if (((WORD *) a)->len == ((WORD *) b)->len) + { + int res = strncmp( + ((WORD *) a)->word, + ((WORD *) b)->word, + ((WORD *) b)->len); + + if (res == 0) + return (((WORD *) a)->pos.pos > ((WORD *) b)->pos.pos) ? 1 : -1; return res; } return (((WORD *) a)->len > ((WORD *) b)->len) ? 1 : -1; @@ -527,14 +589,15 @@ uniqueWORD(WORD * a, int4 l) { WORD *ptr, *res; - int tmppos; + int tmppos; - if (l == 1) { - tmppos=LIMITPOS(a->pos.pos); - a->alen=2; - a->pos.apos=(uint16*)palloc( sizeof(uint16)*a->alen ); - a->pos.apos[0]=1; - a->pos.apos[1]=tmppos; + if (l == 1) + { + tmppos = LIMITPOS(a->pos.pos); + a->alen = 2; + a->pos.apos = (uint16 *) palloc(sizeof(uint16) * a->alen); + a->pos.apos[0] = 1; + a->pos.apos[1] = tmppos; return l; } @@ -542,11 +605,11 @@ uniqueWORD(WORD * a, int4 l) ptr = a + 1; qsort((void *) a, l, sizeof(WORD), compareWORD); - tmppos=LIMITPOS(a->pos.pos); - a->alen=2; - a->pos.apos=(uint16*)palloc( sizeof(uint16)*a->alen ); - a->pos.apos[0]=1; - a->pos.apos[1]=tmppos; + tmppos = LIMITPOS(a->pos.pos); + a->alen = 2; + a->pos.apos = (uint16 *) palloc(sizeof(uint16) * a->alen); + a->pos.apos[0] = 1; + a->pos.apos[1] = tmppos; while (ptr - a < l) { @@ -556,20 +619,24 @@ uniqueWORD(WORD * a, int4 l) res++; res->len = ptr->len; res->word = ptr->word; - tmppos=LIMITPOS(ptr->pos.pos); - res->alen=2; - res->pos.apos=(uint16*)palloc( sizeof(uint16)*res->alen ); - res->pos.apos[0]=1; - res->pos.apos[1]=tmppos; - } else { + tmppos = LIMITPOS(ptr->pos.pos); + res->alen = 2; + res->pos.apos = (uint16 *) palloc(sizeof(uint16) * res->alen); + res->pos.apos[0] = 1; + res->pos.apos[1] = tmppos; + } + else + { pfree(ptr->word); - if ( res->pos.apos[0] < MAXNUMPOS-1 && res->pos.apos[ res->pos.apos[0] ] != MAXENTRYPOS-1 ) { - if ( res->pos.apos[0]+1 >= res->alen ) { - res->alen*=2; - res->pos.apos=(uint16*)repalloc( res->pos.apos, sizeof(uint16)*res->alen ); + if (res->pos.apos[0] < MAXNUMPOS - 1 && res->pos.apos[res->pos.apos[0]] != MAXENTRYPOS - 1) + { + if (res->pos.apos[0] + 1 >= res->alen) + { + res->alen *= 2; + res->pos.apos = (uint16 *) repalloc(res->pos.apos, sizeof(uint16) * res->alen); } - res->pos.apos[ res->pos.apos[0]+1 ] = LIMITPOS(ptr->pos.pos); - res->pos.apos[0]++; + res->pos.apos[res->pos.apos[0] + 1] = LIMITPOS(ptr->pos.pos); + res->pos.apos[0]++; } } ptr++; @@ -584,25 +651,27 @@ uniqueWORD(WORD * a, int4 l) static tsvector * makevalue(PRSTEXT * prs) { - int4 i,j, + int4 i, + j, lenstr = 0, totallen; - tsvector *in; + tsvector *in; WordEntry *ptr; char *str, *cur; prs->curwords = uniqueWORD(prs->words, prs->curwords); - for (i = 0; i < prs->curwords; i++) { + for (i = 0; i < prs->curwords; i++) + { lenstr += SHORTALIGN(prs->words[i].len); - if ( prs->words[i].alen ) + if (prs->words[i].alen) lenstr += sizeof(uint16) + prs->words[i].pos.apos[0] * sizeof(WordEntryPos); } totallen = CALCDATASIZE(prs->curwords, lenstr); in = (tsvector *) palloc(totallen); - memset(in,0,totallen); + memset(in, 0, totallen); in->len = totallen; in->size = prs->curwords; @@ -615,24 +684,27 @@ makevalue(PRSTEXT * prs) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("value is too big"))); - ptr->pos= cur - str; + ptr->pos = cur - str; memcpy((void *) cur, (void *) prs->words[i].word, prs->words[i].len); pfree(prs->words[i].word); cur += SHORTALIGN(prs->words[i].len); - if ( prs->words[i].alen ) { + if (prs->words[i].alen) + { WordEntryPos *wptr; - - ptr->haspos=1; - *(uint16*)cur = prs->words[i].pos.apos[0]; - wptr=POSDATAPTR(in,ptr); - for(j=0;j<*(uint16*)cur;j++) { - wptr[j].weight=0; - wptr[j].pos=prs->words[i].pos.apos[j+1]; + + ptr->haspos = 1; + *(uint16 *) cur = prs->words[i].pos.apos[0]; + wptr = POSDATAPTR(in, ptr); + for (j = 0; j < *(uint16 *) cur; j++) + { + wptr[j].weight = 0; + wptr[j].pos = prs->words[i].pos.apos[j + 1]; } cur += sizeof(uint16) + prs->words[i].pos.apos[0] * sizeof(WordEntryPos); pfree(prs->words[i].pos.apos); - } else - ptr->haspos=0; + } + else + ptr->haspos = 0; ptr++; } pfree(prs->words); @@ -645,70 +717,78 @@ to_tsvector(PG_FUNCTION_ARGS) { text *in = PG_GETARG_TEXT_P(1); PRSTEXT prs; - tsvector *out = NULL; - TSCfgInfo *cfg=findcfg(PG_GETARG_INT32(0)); + tsvector *out = NULL; + TSCfgInfo *cfg = findcfg(PG_GETARG_INT32(0)); prs.lenwords = 32; prs.curwords = 0; prs.pos = 0; prs.words = (WORD *) palloc(sizeof(WORD) * prs.lenwords); - + parsetext_v2(cfg, &prs, VARDATA(in), VARSIZE(in) - VARHDRSZ); PG_FREE_IF_COPY(in, 1); if (prs.curwords) out = makevalue(&prs); - else { + else + { pfree(prs.words); - out = palloc(CALCDATASIZE(0,0)); - out->len = CALCDATASIZE(0,0); + out = palloc(CALCDATASIZE(0, 0)); + out->len = CALCDATASIZE(0, 0); out->size = 0; - } + } PG_RETURN_POINTER(out); } Datum -to_tsvector_name(PG_FUNCTION_ARGS) { - text *cfg=PG_GETARG_TEXT_P(0); - Datum res = DirectFunctionCall3( - to_tsvector, - Int32GetDatum( name2id_cfg( cfg ) ), - PG_GETARG_DATUM(1), - (Datum)0 +to_tsvector_name(PG_FUNCTION_ARGS) +{ + text *cfg = PG_GETARG_TEXT_P(0); + Datum res = DirectFunctionCall3( + to_tsvector, + Int32GetDatum(name2id_cfg(cfg)), + PG_GETARG_DATUM(1), + (Datum) 0 ); - PG_FREE_IF_COPY(cfg,0); - PG_RETURN_DATUM(res); + + PG_FREE_IF_COPY(cfg, 0); + PG_RETURN_DATUM(res); } Datum -to_tsvector_current(PG_FUNCTION_ARGS) { - Datum res = DirectFunctionCall3( - to_tsvector, - Int32GetDatum( get_currcfg() ), - PG_GETARG_DATUM(0), - (Datum)0 +to_tsvector_current(PG_FUNCTION_ARGS) +{ + Datum res = DirectFunctionCall3( + to_tsvector, + Int32GetDatum(get_currcfg()), + PG_GETARG_DATUM(0), + (Datum) 0 ); - PG_RETURN_DATUM(res); + + PG_RETURN_DATUM(res); } static Oid -findFunc(char *fname) { - FuncCandidateList clist,ptr; - Oid funcid = InvalidOid; - List *names=makeList1(makeString(fname)); +findFunc(char *fname) +{ + FuncCandidateList clist, + ptr; + Oid funcid = InvalidOid; + List *names = makeList1(makeString(fname)); ptr = clist = FuncnameGetCandidates(names, 1); freeList(names); - if ( !ptr ) + if (!ptr) return funcid; - while(ptr) { - if ( ptr->args[0] == TEXTOID && funcid == InvalidOid ) - funcid=ptr->oid; - clist=ptr->next; + while (ptr) + { + if (ptr->args[0] == TEXTOID && funcid == InvalidOid) + funcid = ptr->oid; + clist = ptr->next; pfree(ptr); - ptr=clist; + ptr = clist; } return funcid; @@ -724,12 +804,12 @@ tsearch2(PG_FUNCTION_ARGS) Trigger *trigger; Relation rel; HeapTuple rettuple = NULL; - TSCfgInfo *cfg=findcfg(get_currcfg()); + TSCfgInfo *cfg = findcfg(get_currcfg()); int numidxattr, i; PRSTEXT prs; Datum datum = (Datum) 0; - Oid funcoid = InvalidOid; + Oid funcoid = InvalidOid; if (!CALLED_AS_TRIGGER(fcinfo)) /* internal error */ @@ -782,8 +862,8 @@ tsearch2(PG_FUNCTION_ARGS) numattr = SPI_fnumber(rel->rd_att, trigger->tgargs[i]); if (numattr == SPI_ERROR_NOATTRIBUTE) { - funcoid=findFunc(trigger->tgargs[i]); - if ( funcoid==InvalidOid ) + funcoid = findFunc(trigger->tgargs[i]); + if (funcoid == InvalidOid) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("could not find function or field \"%s\"", @@ -805,19 +885,22 @@ tsearch2(PG_FUNCTION_ARGS) if (isnull) continue; - if ( funcoid!=InvalidOid ) { - text *txttmp = (text *) DatumGetPointer( OidFunctionCall1( - funcoid, - PointerGetDatum(txt_toasted) - )); + if (funcoid != InvalidOid) + { + text *txttmp = (text *) DatumGetPointer(OidFunctionCall1( + funcoid, + PointerGetDatum(txt_toasted) + )); + txt = (text *) DatumGetPointer(PG_DETOAST_DATUM(PointerGetDatum(txttmp))); - if ( txt == txttmp ) + if (txt == txttmp) txt_toasted = PointerGetDatum(txt); - } else - txt = (text *) DatumGetPointer(PG_DETOAST_DATUM(PointerGetDatum(txt_toasted))); + } + else + txt = (text *) DatumGetPointer(PG_DETOAST_DATUM(PointerGetDatum(txt_toasted))); parsetext_v2(cfg, &prs, VARDATA(txt), VARSIZE(txt) - VARHDRSZ); - if (txt != (text*)DatumGetPointer(txt_toasted) ) + if (txt != (text *) DatumGetPointer(txt_toasted)) pfree(txt); } @@ -831,8 +914,9 @@ tsearch2(PG_FUNCTION_ARGS) } else { - tsvector *out = palloc(CALCDATASIZE(0,0)); - out->len = CALCDATASIZE(0,0); + tsvector *out = palloc(CALCDATASIZE(0, 0)); + + out->len = CALCDATASIZE(0, 0); out->size = 0; datum = PointerGetDatum(out); pfree(prs.words); diff --git a/contrib/tsearch2/tsvector.h b/contrib/tsearch2/tsvector.h index af06e3cf52..bb69524746 100644 --- a/contrib/tsearch2/tsvector.h +++ b/contrib/tsearch2/tsvector.h @@ -12,23 +12,27 @@ #include "utils/builtins.h" #include "storage/bufpage.h" -typedef struct { +typedef struct +{ uint32 - haspos:1, - len:11, /* MAX 2Kb */ - pos:20; /* MAX 1Mb */ + haspos:1, + len:11, /* MAX 2Kb */ + pos:20; /* MAX 1Mb */ } WordEntry; + #define MAXSTRLEN ( 1<<11 ) #define MAXSTRPOS ( 1<<20 ) -typedef struct { +typedef struct +{ uint16 - weight:2, - pos:14; -} WordEntryPos; -#define MAXENTRYPOS (1<<14) + weight:2, + pos:14; +} WordEntryPos; + +#define MAXENTRYPOS (1<<14) #define MAXNUMPOS 256 -#define LIMITPOS(x) ( ( (x) >= MAXENTRYPOS ) ? (MAXENTRYPOS-1) : (x) ) +#define LIMITPOS(x) ( ( (x) >= MAXENTRYPOS ) ? (MAXENTRYPOS-1) : (x) ) typedef struct { @@ -43,13 +47,14 @@ typedef struct #define STRPTR(x) ( (char*)x + DATAHDRSIZE + ( sizeof(WordEntry) * ((tsvector*)x)->size ) ) #define STRSIZE(x) ( ((tsvector*)x)->len - DATAHDRSIZE - ( sizeof(WordEntry) * ((tsvector*)x)->size ) ) #define _POSDATAPTR(x,e) (STRPTR(x)+((WordEntry*)(e))->pos+SHORTALIGN(((WordEntry*)(e))->len)) -#define POSDATALEN(x,e) ( ( ((WordEntry*)(e))->haspos ) ? (*(uint16*)_POSDATAPTR(x,e)) : 0 ) -#define POSDATAPTR(x,e) ( (WordEntryPos*)( _POSDATAPTR(x,e)+sizeof(uint16) ) ) +#define POSDATALEN(x,e) ( ( ((WordEntry*)(e))->haspos ) ? (*(uint16*)_POSDATAPTR(x,e)) : 0 ) +#define POSDATAPTR(x,e) ( (WordEntryPos*)( _POSDATAPTR(x,e)+sizeof(uint16) ) ) -typedef struct { - WordEntry entry; - WordEntryPos *pos; +typedef struct +{ + WordEntry entry; + WordEntryPos *pos; } WordEntryIN; typedef struct @@ -60,7 +65,7 @@ typedef struct int4 len; int4 state; int4 alen; - WordEntryPos *pos; + WordEntryPos *pos; bool oprisdelim; } TI_IN_STATE; diff --git a/contrib/tsearch2/tsvector_op.c b/contrib/tsearch2/tsvector_op.c index cfef02db85..2ffd4ca584 100644 --- a/contrib/tsearch2/tsvector_op.c +++ b/contrib/tsearch2/tsvector_op.c @@ -33,30 +33,33 @@ Datum concat(PG_FUNCTION_ARGS); Datum strip(PG_FUNCTION_ARGS) { - tsvector *in = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); - tsvector *out; - int i,len=0; - WordEntry *arrin=ARRPTR(in), *arrout; - char *cur; + tsvector *in = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); + tsvector *out; + int i, + len = 0; + WordEntry *arrin = ARRPTR(in), + *arrout; + char *cur; - for(i=0;isize;i++) - len += SHORTALIGN( arrin[i].len ); + for (i = 0; i < in->size; i++) + len += SHORTALIGN(arrin[i].len); len = CALCDATASIZE(in->size, len); - out=(tsvector*)palloc(len); - memset(out,0,len); - out->len=len; - out->size=in->size; - arrout=ARRPTR(out); - cur=STRPTR(out); - for(i=0;isize;i++) { - memcpy(cur, STRPTR(in)+arrin[i].pos, arrin[i].len); + out = (tsvector *) palloc(len); + memset(out, 0, len); + out->len = len; + out->size = in->size; + arrout = ARRPTR(out); + cur = STRPTR(out); + for (i = 0; i < in->size; i++) + { + memcpy(cur, STRPTR(in) + arrin[i].pos, arrin[i].len); arrout[i].haspos = 0; arrout[i].len = arrin[i].len; arrout[i].pos = cur - STRPTR(out); - cur += SHORTALIGN( arrout[i].len ); + cur += SHORTALIGN(arrout[i].len); } - + PG_FREE_IF_COPY(in, 0); PG_RETURN_POINTER(out); } @@ -64,200 +67,263 @@ strip(PG_FUNCTION_ARGS) Datum setweight(PG_FUNCTION_ARGS) { - tsvector *in = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); - char cw = PG_GETARG_CHAR(1); - tsvector *out; - int i,j; - WordEntry *entry; + tsvector *in = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); + char cw = PG_GETARG_CHAR(1); + tsvector *out; + int i, + j; + WordEntry *entry; WordEntryPos *p; - int w=0; + int w = 0; - switch(tolower(cw)) { - case 'a': w=3; break; - case 'b': w=2; break; - case 'c': w=1; break; - case 'd': w=0; break; - /* internal error */ - default: elog(ERROR,"unrecognized weight"); + switch (tolower(cw)) + { + case 'a': + w = 3; + break; + case 'b': + w = 2; + break; + case 'c': + w = 1; + break; + case 'd': + w = 0; + break; + /* internal error */ + default: + elog(ERROR, "unrecognized weight"); } - out=(tsvector*)palloc(in->len); - memcpy(out,in,in->len); - entry=ARRPTR(out); - i=out->size; - while(i--) { - if ( (j=POSDATALEN(out,entry)) != 0 ) { - p=POSDATAPTR(out,entry); - while(j--) { - p->weight=w; + out = (tsvector *) palloc(in->len); + memcpy(out, in, in->len); + entry = ARRPTR(out); + i = out->size; + while (i--) + { + if ((j = POSDATALEN(out, entry)) != 0) + { + p = POSDATAPTR(out, entry); + while (j--) + { + p->weight = w; p++; } } entry++; } - + PG_FREE_IF_COPY(in, 0); PG_RETURN_POINTER(out); } static int -compareEntry(char *ptra, WordEntry* a, char *ptrb, WordEntry* b) +compareEntry(char *ptra, WordEntry * a, char *ptrb, WordEntry * b) { - if ( a->len == b->len) - { - return strncmp( - ptra + a->pos, - ptrb + b->pos, - a->len); - } - return ( a->len > b->len ) ? 1 : -1; + if (a->len == b->len) + { + return strncmp( + ptra + a->pos, + ptrb + b->pos, + a->len); + } + return (a->len > b->len) ? 1 : -1; } static int4 -add_pos(tsvector *src, WordEntry *srcptr, tsvector *dest, WordEntry *destptr, int4 maxpos ) { - uint16 *clen = (uint16*)_POSDATAPTR(dest,destptr); - int i; - uint16 slen = POSDATALEN(src, srcptr), startlen; - WordEntryPos *spos=POSDATAPTR(src, srcptr), *dpos=POSDATAPTR(dest,destptr); +add_pos(tsvector * src, WordEntry * srcptr, tsvector * dest, WordEntry * destptr, int4 maxpos) +{ + uint16 *clen = (uint16 *) _POSDATAPTR(dest, destptr); + int i; + uint16 slen = POSDATALEN(src, srcptr), + startlen; + WordEntryPos *spos = POSDATAPTR(src, srcptr), + *dpos = POSDATAPTR(dest, destptr); - if ( ! destptr->haspos ) - *clen=0; + if (!destptr->haspos) + *clen = 0; startlen = *clen; - for(i=0; ihaspos=1; - return *clen - startlen; + if (*clen != startlen) + destptr->haspos = 1; + return *clen - startlen; } Datum -concat(PG_FUNCTION_ARGS) { - tsvector *in1 = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); - tsvector *in2 = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); - tsvector *out; - WordEntry *ptr; - WordEntry *ptr1,*ptr2; +concat(PG_FUNCTION_ARGS) +{ + tsvector *in1 = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); + tsvector *in2 = (tsvector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); + tsvector *out; + WordEntry *ptr; + WordEntry *ptr1, + *ptr2; WordEntryPos *p; - int maxpos=0,i,j,i1,i2; - char *cur; - char *data,*data1,*data2; + int maxpos = 0, + i, + j, + i1, + i2; + char *cur; + char *data, + *data1, + *data2; - ptr=ARRPTR(in1); - i=in1->size; - while(i--) { - if ( (j=POSDATALEN(in1,ptr)) != 0 ) { - p=POSDATAPTR(in1,ptr); - while(j--) { - if ( p->pos > maxpos ) + ptr = ARRPTR(in1); + i = in1->size; + while (i--) + { + if ((j = POSDATALEN(in1, ptr)) != 0) + { + p = POSDATAPTR(in1, ptr); + while (j--) + { + if (p->pos > maxpos) maxpos = p->pos; p++; } } ptr++; } - - ptr1=ARRPTR(in1); ptr2=ARRPTR(in2); - data1=STRPTR(in1); data2=STRPTR(in2); - i1=in1->size; i2=in2->size; - out=(tsvector*)palloc( in1->len + in2->len ); - memset(out,0,in1->len + in2->len); + + ptr1 = ARRPTR(in1); + ptr2 = ARRPTR(in2); + data1 = STRPTR(in1); + data2 = STRPTR(in2); + i1 = in1->size; + i2 = in2->size; + out = (tsvector *) palloc(in1->len + in2->len); + memset(out, 0, in1->len + in2->len); out->len = in1->len + in2->len; out->size = in1->size + in2->size; - data=cur=STRPTR(out); - ptr=ARRPTR(out); - while( i1 && i2 ) { - int cmp=compareEntry(data1,ptr1,data2,ptr2); - if ( cmp < 0 ) { /* in1 first */ + data = cur = STRPTR(out); + ptr = ARRPTR(out); + while (i1 && i2) + { + int cmp = compareEntry(data1, ptr1, data2, ptr2); + + if (cmp < 0) + { /* in1 first */ ptr->haspos = ptr1->haspos; ptr->len = ptr1->len; - memcpy( cur, data1 + ptr1->pos, ptr1->len ); - ptr->pos = cur - data; - cur+=SHORTALIGN(ptr1->len); - if ( ptr->haspos ) { - memcpy(cur, _POSDATAPTR(in1, ptr1), POSDATALEN(in1, ptr1)*sizeof(WordEntryPos) + sizeof(uint16)); - cur+=POSDATALEN(in1, ptr1)*sizeof(WordEntryPos) + sizeof(uint16); + memcpy(cur, data1 + ptr1->pos, ptr1->len); + ptr->pos = cur - data; + cur += SHORTALIGN(ptr1->len); + if (ptr->haspos) + { + memcpy(cur, _POSDATAPTR(in1, ptr1), POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16)); + cur += POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16); } - ptr++; ptr1++; i1--; - } else if ( cmp>0 ) { /* in2 first */ + ptr++; + ptr1++; + i1--; + } + else if (cmp > 0) + { /* in2 first */ ptr->haspos = ptr2->haspos; ptr->len = ptr2->len; - memcpy( cur, data2 + ptr2->pos, ptr2->len ); - ptr->pos = cur - data; - cur+=SHORTALIGN(ptr2->len); - if ( ptr->haspos ) { - int addlen = add_pos(in2, ptr2, out, ptr, maxpos ); - if ( addlen == 0 ) - ptr->haspos=0; + memcpy(cur, data2 + ptr2->pos, ptr2->len); + ptr->pos = cur - data; + cur += SHORTALIGN(ptr2->len); + if (ptr->haspos) + { + int addlen = add_pos(in2, ptr2, out, ptr, maxpos); + + if (addlen == 0) + ptr->haspos = 0; else - cur += addlen*sizeof(WordEntryPos) + sizeof(uint16); + cur += addlen * sizeof(WordEntryPos) + sizeof(uint16); } - ptr++; ptr2++; i2--; - } else { + ptr++; + ptr2++; + i2--; + } + else + { ptr->haspos = ptr1->haspos | ptr2->haspos; ptr->len = ptr1->len; - memcpy( cur, data1 + ptr1->pos, ptr1->len ); - ptr->pos = cur - data; - cur+=SHORTALIGN(ptr1->len); - if ( ptr->haspos ) { - if ( ptr1->haspos ) { - memcpy(cur, _POSDATAPTR(in1, ptr1), POSDATALEN(in1, ptr1)*sizeof(WordEntryPos) + sizeof(uint16)); - cur+=POSDATALEN(in1, ptr1)*sizeof(WordEntryPos) + sizeof(uint16); - if ( ptr2->haspos ) - cur += add_pos(in2, ptr2, out, ptr, maxpos )*sizeof(WordEntryPos); - } else if ( ptr2->haspos ) { - int addlen = add_pos(in2, ptr2, out, ptr, maxpos ); - if ( addlen == 0 ) - ptr->haspos=0; + memcpy(cur, data1 + ptr1->pos, ptr1->len); + ptr->pos = cur - data; + cur += SHORTALIGN(ptr1->len); + if (ptr->haspos) + { + if (ptr1->haspos) + { + memcpy(cur, _POSDATAPTR(in1, ptr1), POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16)); + cur += POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16); + if (ptr2->haspos) + cur += add_pos(in2, ptr2, out, ptr, maxpos) * sizeof(WordEntryPos); + } + else if (ptr2->haspos) + { + int addlen = add_pos(in2, ptr2, out, ptr, maxpos); + + if (addlen == 0) + ptr->haspos = 0; else - cur += addlen*sizeof(WordEntryPos) + sizeof(uint16); + cur += addlen * sizeof(WordEntryPos) + sizeof(uint16); } } - ptr++; ptr1++; ptr2++; i1--; i2--; + ptr++; + ptr1++; + ptr2++; + i1--; + i2--; } } - while(i1) { + while (i1) + { ptr->haspos = ptr1->haspos; ptr->len = ptr1->len; - memcpy( cur, data1 + ptr1->pos, ptr1->len ); - ptr->pos = cur - data; - cur+=SHORTALIGN(ptr1->len); - if ( ptr->haspos ) { - memcpy(cur, _POSDATAPTR(in1, ptr1), POSDATALEN(in1, ptr1)*sizeof(WordEntryPos) + sizeof(uint16)); - cur+=POSDATALEN(in1, ptr1)*sizeof(WordEntryPos) + sizeof(uint16); + memcpy(cur, data1 + ptr1->pos, ptr1->len); + ptr->pos = cur - data; + cur += SHORTALIGN(ptr1->len); + if (ptr->haspos) + { + memcpy(cur, _POSDATAPTR(in1, ptr1), POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16)); + cur += POSDATALEN(in1, ptr1) * sizeof(WordEntryPos) + sizeof(uint16); } - ptr++; ptr1++; i1--; + ptr++; + ptr1++; + i1--; } - while(i2) { + while (i2) + { ptr->haspos = ptr2->haspos; ptr->len = ptr2->len; - memcpy( cur, data2 + ptr2->pos, ptr2->len ); - ptr->pos = cur - data; - cur+=SHORTALIGN(ptr2->len); - if ( ptr->haspos ) { - int addlen = add_pos(in2, ptr2, out, ptr, maxpos ); - if ( addlen == 0 ) - ptr->haspos=0; + memcpy(cur, data2 + ptr2->pos, ptr2->len); + ptr->pos = cur - data; + cur += SHORTALIGN(ptr2->len); + if (ptr->haspos) + { + int addlen = add_pos(in2, ptr2, out, ptr, maxpos); + + if (addlen == 0) + ptr->haspos = 0; else - cur += addlen*sizeof(WordEntryPos) + sizeof(uint16); + cur += addlen * sizeof(WordEntryPos) + sizeof(uint16); } - ptr++; ptr2++; i2--; + ptr++; + ptr2++; + i2--; } - - out->size=ptr-ARRPTR(out); - out->len = CALCDATASIZE( out->size, cur-data ); - if ( data != STRPTR(out) ) - memmove( STRPTR(out), data, cur-data ); + + out->size = ptr - ARRPTR(out); + out->len = CALCDATASIZE(out->size, cur - data); + if (data != STRPTR(out)) + memmove(STRPTR(out), data, cur - data); PG_FREE_IF_COPY(in1, 0); PG_FREE_IF_COPY(in2, 1); PG_RETURN_POINTER(out); } - diff --git a/contrib/tsearch2/wordparser/deflex.c b/contrib/tsearch2/wordparser/deflex.c index ea596c507c..bbf3271b66 100644 --- a/contrib/tsearch2/wordparser/deflex.c +++ b/contrib/tsearch2/wordparser/deflex.c @@ -1,6 +1,6 @@ #include "deflex.h" -const char *lex_descr[]={ +const char *lex_descr[] = { "", "Latin word", "Non-latin word", @@ -27,7 +27,7 @@ const char *lex_descr[]={ "HTML Entity" }; -const char *tok_alias[]={ +const char *tok_alias[] = { "", "lword", "nlword", @@ -53,4 +53,3 @@ const char *tok_alias[]={ "uint", "entity" }; - diff --git a/contrib/tsearch2/wparser.c b/contrib/tsearch2/wparser.c index deff94ce90..b7e45e5188 100644 --- a/contrib/tsearch2/wparser.c +++ b/contrib/tsearch2/wparser.c @@ -1,5 +1,5 @@ -/* - * interface functions to parser +/* + * interface functions to parser * Teodor Sigaev */ #include @@ -21,154 +21,171 @@ /*********top interface**********/ -static void *plan_getparser=NULL; -static Oid current_parser_id=InvalidOid; +static void *plan_getparser = NULL; +static Oid current_parser_id = InvalidOid; void -init_prs(Oid id, WParserInfo *prs) { - Oid arg[1]={ OIDOID }; - bool isnull; - Datum pars[1]={ ObjectIdGetDatum(id) }; - int stat; +init_prs(Oid id, WParserInfo * prs) +{ + Oid arg[1] = {OIDOID}; + bool isnull; + Datum pars[1] = {ObjectIdGetDatum(id)}; + int stat; - memset(prs,0,sizeof(WParserInfo)); + memset(prs, 0, sizeof(WParserInfo)); SPI_connect(); - if ( !plan_getparser ) { - plan_getparser = SPI_saveplan( SPI_prepare( "select prs_start, prs_nexttoken, prs_end, prs_lextype, prs_headline from pg_ts_parser where oid = $1" , 1, arg ) ); - if ( !plan_getparser ) + if (!plan_getparser) + { + plan_getparser = SPI_saveplan(SPI_prepare("select prs_start, prs_nexttoken, prs_end, prs_lextype, prs_headline from pg_ts_parser where oid = $1", 1, arg)); + if (!plan_getparser) ts_error(ERROR, "SPI_prepare() failed"); } stat = SPI_execp(plan_getparser, pars, " ", 1); - if ( stat < 0 ) - ts_error (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed > 0 ) { - Oid oid=InvalidOid; - oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) ); + if (stat < 0) + ts_error(ERROR, "SPI_execp return %d", stat); + if (SPI_processed > 0) + { + Oid oid = InvalidOid; + + oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); fmgr_info_cxt(oid, &(prs->start_info), TopMemoryContext); - oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull) ); + oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull)); fmgr_info_cxt(oid, &(prs->getlexeme_info), TopMemoryContext); - oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull) ); + oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull)); fmgr_info_cxt(oid, &(prs->end_info), TopMemoryContext); - prs->lextype=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 4, &isnull) ); - oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 5, &isnull) ); + prs->lextype = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 4, &isnull)); + oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 5, &isnull)); fmgr_info_cxt(oid, &(prs->headline_info), TopMemoryContext); - prs->prs_id=id; - } else + prs->prs_id = id; + } + else ts_error(ERROR, "No parser with id %d", id); SPI_finish(); } -typedef struct { - WParserInfo *last_prs; - int len; - int reallen; - WParserInfo *list; +typedef struct +{ + WParserInfo *last_prs; + int len; + int reallen; + WParserInfo *list; SNMap name2id_map; -} PrsList; +} PrsList; -static PrsList PList = {NULL,0,0,NULL,{0,0,NULL}}; +static PrsList PList = {NULL, 0, 0, NULL, {0, 0, NULL}}; -void -reset_prs(void) { - freeSNMap( &(PList.name2id_map) ); - if ( PList.list ) +void +reset_prs(void) +{ + freeSNMap(&(PList.name2id_map)); + if (PList.list) free(PList.list); - memset(&PList,0,sizeof(PrsList)); + memset(&PList, 0, sizeof(PrsList)); } static int -compareprs(const void *a, const void *b) { - return ((WParserInfo*)a)->prs_id - ((WParserInfo*)b)->prs_id; +compareprs(const void *a, const void *b) +{ + return ((WParserInfo *) a)->prs_id - ((WParserInfo *) b)->prs_id; } WParserInfo * -findprs(Oid id) { +findprs(Oid id) +{ /* last used prs */ - if ( PList.last_prs && PList.last_prs->prs_id==id ) + if (PList.last_prs && PList.last_prs->prs_id == id) return PList.last_prs; /* already used prs */ - if ( PList.len != 0 ) { + if (PList.len != 0) + { WParserInfo key; - key.prs_id=id; + + key.prs_id = id; PList.last_prs = bsearch(&key, PList.list, PList.len, sizeof(WParserInfo), compareprs); - if ( PList.last_prs != NULL ) + if (PList.last_prs != NULL) return PList.last_prs; } /* last chance */ - if ( PList.len==PList.reallen ) { + if (PList.len == PList.reallen) + { WParserInfo *tmp; - int reallen = ( PList.reallen ) ? 2*PList.reallen : 16; - tmp=(WParserInfo*)realloc(PList.list,sizeof(WParserInfo)*reallen); - if ( !tmp ) - ts_error(ERROR,"No memory"); - PList.reallen=reallen; - PList.list=tmp; + int reallen = (PList.reallen) ? 2 * PList.reallen : 16; + + tmp = (WParserInfo *) realloc(PList.list, sizeof(WParserInfo) * reallen); + if (!tmp) + ts_error(ERROR, "No memory"); + PList.reallen = reallen; + PList.list = tmp; } - PList.last_prs=&(PList.list[PList.len]); + PList.last_prs = &(PList.list[PList.len]); init_prs(id, PList.last_prs); PList.len++; qsort(PList.list, PList.len, sizeof(WParserInfo), compareprs); - return findprs(id); /* qsort changed order!! */; + return findprs(id); /* qsort changed order!! */ ; } -static void *plan_name2id=NULL; +static void *plan_name2id = NULL; Oid -name2id_prs(text *name) { - Oid arg[1]={ TEXTOID }; - bool isnull; - Datum pars[1]={ PointerGetDatum(name) }; - int stat; - Oid id=findSNMap_t( &(PList.name2id_map), name ); - - if ( id ) +name2id_prs(text *name) +{ + Oid arg[1] = {TEXTOID}; + bool isnull; + Datum pars[1] = {PointerGetDatum(name)}; + int stat; + Oid id = findSNMap_t(&(PList.name2id_map), name); + + if (id) return id; - + SPI_connect(); - if ( !plan_name2id ) { - plan_name2id = SPI_saveplan( SPI_prepare( "select oid from pg_ts_parser where prs_name = $1" , 1, arg ) ); - if ( !plan_name2id ) + if (!plan_name2id) + { + plan_name2id = SPI_saveplan(SPI_prepare("select oid from pg_ts_parser where prs_name = $1", 1, arg)); + if (!plan_name2id) ts_error(ERROR, "SPI_prepare() failed"); } stat = SPI_execp(plan_name2id, pars, " ", 1); - if ( stat < 0 ) - ts_error (ERROR, "SPI_execp return %d", stat); - if ( SPI_processed > 0 ) - id=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) ); - else + if (stat < 0) + ts_error(ERROR, "SPI_execp return %d", stat); + if (SPI_processed > 0) + id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); + else ts_error(ERROR, "No parser '%s'", text2char(name)); SPI_finish(); - addSNMap_t( &(PList.name2id_map), name, id ); + addSNMap_t(&(PList.name2id_map), name, id); return id; } /******sql-level interface******/ -typedef struct { - int cur; - LexDescr *list; -} TypeStorage; +typedef struct +{ + int cur; + LexDescr *list; +} TypeStorage; static void -setup_firstcall(FuncCallContext *funcctx, Oid prsid) { - TupleDesc tupdesc; - MemoryContext oldcontext; - TypeStorage *st; - WParserInfo *prs = findprs(prsid); +setup_firstcall(FuncCallContext *funcctx, Oid prsid) +{ + TupleDesc tupdesc; + MemoryContext oldcontext; + TypeStorage *st; + WParserInfo *prs = findprs(prsid); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); - st=(TypeStorage*)palloc( sizeof(TypeStorage) ); - st->cur=0; - st->list = (LexDescr*)DatumGetPointer( - OidFunctionCall1( prs->lextype, PointerGetDatum(prs->prs) ) - ); - funcctx->user_fctx = (void*)st; + st = (TypeStorage *) palloc(sizeof(TypeStorage)); + st->cur = 0; + st->list = (LexDescr *) DatumGetPointer( + OidFunctionCall1(prs->lextype, PointerGetDatum(prs->prs)) + ); + funcctx->user_fctx = (void *) st; tupdesc = RelationNameGetTupleDesc("tokentype"); funcctx->slot = TupleDescGetSlot(tupdesc); funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc); @@ -176,20 +193,22 @@ setup_firstcall(FuncCallContext *funcctx, Oid prsid) { } static Datum -process_call(FuncCallContext *funcctx) { - TypeStorage *st; +process_call(FuncCallContext *funcctx) +{ + TypeStorage *st; - st=(TypeStorage*)funcctx->user_fctx; - if ( st->list && st->list[st->cur].lexid ) { - Datum result; - char* values[3]; - char txtid[16]; - HeapTuple tuple; + st = (TypeStorage *) funcctx->user_fctx; + if (st->list && st->list[st->cur].lexid) + { + Datum result; + char *values[3]; + char txtid[16]; + HeapTuple tuple; - values[0]=txtid; - sprintf(txtid,"%d",st->list[st->cur].lexid); - values[1]=st->list[st->cur].alias; - values[2]=st->list[st->cur].descr; + values[0] = txtid; + sprintf(txtid, "%d", st->list[st->cur].lexid); + values[1] = st->list[st->cur].alias; + values[2] = st->list[st->cur].descr; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = TupleGetDatum(funcctx->slot, tuple); @@ -198,161 +217,179 @@ process_call(FuncCallContext *funcctx) { pfree(values[2]); st->cur++; return result; - } else { - if ( st->list ) pfree(st->list); + } + else + { + if (st->list) + pfree(st->list); pfree(st); } - return (Datum)0; + return (Datum) 0; } PG_FUNCTION_INFO_V1(token_type); -Datum token_type(PG_FUNCTION_ARGS); +Datum token_type(PG_FUNCTION_ARGS); Datum -token_type(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +token_type(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; - if (SRF_IS_FIRSTCALL()) { + if (SRF_IS_FIRSTCALL()) + { funcctx = SRF_FIRSTCALL_INIT(); - setup_firstcall(funcctx, PG_GETARG_OID(0) ); + setup_firstcall(funcctx, PG_GETARG_OID(0)); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=process_call(funcctx)) != (Datum)0 ) + if ((result = process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } PG_FUNCTION_INFO_V1(token_type_byname); -Datum token_type_byname(PG_FUNCTION_ARGS); +Datum token_type_byname(PG_FUNCTION_ARGS); Datum -token_type_byname(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +token_type_byname(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; + + if (SRF_IS_FIRSTCALL()) + { + text *name = PG_GETARG_TEXT_P(0); - if (SRF_IS_FIRSTCALL()) { - text *name = PG_GETARG_TEXT_P(0); funcctx = SRF_FIRSTCALL_INIT(); - setup_firstcall(funcctx, name2id_prs( name ) ); - PG_FREE_IF_COPY(name,0); + setup_firstcall(funcctx, name2id_prs(name)); + PG_FREE_IF_COPY(name, 0); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=process_call(funcctx)) != (Datum)0 ) + if ((result = process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } PG_FUNCTION_INFO_V1(token_type_current); -Datum token_type_current(PG_FUNCTION_ARGS); +Datum token_type_current(PG_FUNCTION_ARGS); Datum -token_type_current(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +token_type_current(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; - if (SRF_IS_FIRSTCALL()) { + if (SRF_IS_FIRSTCALL()) + { funcctx = SRF_FIRSTCALL_INIT(); - if ( current_parser_id==InvalidOid ) - current_parser_id = name2id_prs( char2text("default") ); - setup_firstcall(funcctx, current_parser_id ); + if (current_parser_id == InvalidOid) + current_parser_id = name2id_prs(char2text("default")); + setup_firstcall(funcctx, current_parser_id); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=process_call(funcctx)) != (Datum)0 ) + if ((result = process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } PG_FUNCTION_INFO_V1(set_curprs); -Datum set_curprs(PG_FUNCTION_ARGS); +Datum set_curprs(PG_FUNCTION_ARGS); Datum -set_curprs(PG_FUNCTION_ARGS) { - findprs(PG_GETARG_OID(0)); - current_parser_id=PG_GETARG_OID(0); - PG_RETURN_VOID(); +set_curprs(PG_FUNCTION_ARGS) +{ + findprs(PG_GETARG_OID(0)); + current_parser_id = PG_GETARG_OID(0); + PG_RETURN_VOID(); } PG_FUNCTION_INFO_V1(set_curprs_byname); -Datum set_curprs_byname(PG_FUNCTION_ARGS); +Datum set_curprs_byname(PG_FUNCTION_ARGS); Datum -set_curprs_byname(PG_FUNCTION_ARGS) { - text *name=PG_GETARG_TEXT_P(0); - - DirectFunctionCall1( - set_curprs, - ObjectIdGetDatum( name2id_prs(name) ) - ); - PG_FREE_IF_COPY(name, 0); - PG_RETURN_VOID(); +set_curprs_byname(PG_FUNCTION_ARGS) +{ + text *name = PG_GETARG_TEXT_P(0); + + DirectFunctionCall1( + set_curprs, + ObjectIdGetDatum(name2id_prs(name)) + ); + PG_FREE_IF_COPY(name, 0); + PG_RETURN_VOID(); } -typedef struct { - int type; - char *lexem; -} LexemEntry; +typedef struct +{ + int type; + char *lexem; +} LexemEntry; + +typedef struct +{ + int cur; + int len; + LexemEntry *list; +} PrsStorage; -typedef struct { - int cur; - int len; - LexemEntry *list; -} PrsStorage; - static void -prs_setup_firstcall(FuncCallContext *funcctx, int prsid, text *txt) { - TupleDesc tupdesc; - MemoryContext oldcontext; - PrsStorage *st; - WParserInfo *prs = findprs(prsid); - char *lex=NULL; - int llen=0, type=0; +prs_setup_firstcall(FuncCallContext *funcctx, int prsid, text *txt) +{ + TupleDesc tupdesc; + MemoryContext oldcontext; + PrsStorage *st; + WParserInfo *prs = findprs(prsid); + char *lex = NULL; + int llen = 0, + type = 0; oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); - st=(PrsStorage*)palloc( sizeof(PrsStorage) ); - st->cur=0; - st->len=16; - st->list=(LexemEntry*)palloc( sizeof(LexemEntry)*st->len ); + st = (PrsStorage *) palloc(sizeof(PrsStorage)); + st->cur = 0; + st->len = 16; + st->list = (LexemEntry *) palloc(sizeof(LexemEntry) * st->len); - prs->prs = (void*)DatumGetPointer( - FunctionCall2( - &(prs->start_info), - PointerGetDatum(VARDATA(txt)), - Int32GetDatum(VARSIZE(txt)-VARHDRSZ) - ) - ); + prs->prs = (void *) DatumGetPointer( + FunctionCall2( + &(prs->start_info), + PointerGetDatum(VARDATA(txt)), + Int32GetDatum(VARSIZE(txt) - VARHDRSZ) + ) + ); - while( ( type=DatumGetInt32(FunctionCall3( - &(prs->getlexeme_info), - PointerGetDatum(prs->prs), - PointerGetDatum(&lex), - PointerGetDatum(&llen))) ) != 0 ) { + while ((type = DatumGetInt32(FunctionCall3( + &(prs->getlexeme_info), + PointerGetDatum(prs->prs), + PointerGetDatum(&lex), + PointerGetDatum(&llen)))) != 0) + { - if ( st->cur>=st->len ) { - st->len=2*st->len; - st->list=(LexemEntry*)repalloc(st->list, sizeof(LexemEntry)*st->len); + if (st->cur >= st->len) + { + st->len = 2 * st->len; + st->list = (LexemEntry *) repalloc(st->list, sizeof(LexemEntry) * st->len); } - st->list[st->cur].lexem = palloc(llen+1); - memcpy( st->list[st->cur].lexem, lex, llen); - st->list[st->cur].lexem[llen]='\0'; - st->list[st->cur].type=type; + st->list[st->cur].lexem = palloc(llen + 1); + memcpy(st->list[st->cur].lexem, lex, llen); + st->list[st->cur].lexem[llen] = '\0'; + st->list[st->cur].type = type; st->cur++; } - - FunctionCall1( - &(prs->end_info), - PointerGetDatum(prs->prs) - ); - st->len=st->cur; - st->cur=0; - - funcctx->user_fctx = (void*)st; + FunctionCall1( + &(prs->end_info), + PointerGetDatum(prs->prs) + ); + + st->len = st->cur; + st->cur = 0; + + funcctx->user_fctx = (void *) st; tupdesc = RelationNameGetTupleDesc("tokenout"); funcctx->slot = TupleDescGetSlot(tupdesc); funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc); @@ -360,132 +397,148 @@ prs_setup_firstcall(FuncCallContext *funcctx, int prsid, text *txt) { } static Datum -prs_process_call(FuncCallContext *funcctx) { - PrsStorage *st; +prs_process_call(FuncCallContext *funcctx) +{ + PrsStorage *st; - st=(PrsStorage*)funcctx->user_fctx; - if ( st->cur < st->len ) { - Datum result; - char* values[2]; - char tid[16]; - HeapTuple tuple; + st = (PrsStorage *) funcctx->user_fctx; + if (st->cur < st->len) + { + Datum result; + char *values[2]; + char tid[16]; + HeapTuple tuple; - values[0]=tid; - sprintf(tid,"%d",st->list[st->cur].type); - values[1]=st->list[st->cur].lexem; + values[0] = tid; + sprintf(tid, "%d", st->list[st->cur].type); + values[1] = st->list[st->cur].lexem; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = TupleGetDatum(funcctx->slot, tuple); pfree(values[1]); st->cur++; return result; - } else { - if ( st->list ) pfree(st->list); + } + else + { + if (st->list) + pfree(st->list); pfree(st); } - return (Datum)0; + return (Datum) 0; } - + PG_FUNCTION_INFO_V1(parse); -Datum parse(PG_FUNCTION_ARGS); +Datum parse(PG_FUNCTION_ARGS); Datum -parse(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +parse(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; + + if (SRF_IS_FIRSTCALL()) + { + text *txt = PG_GETARG_TEXT_P(1); - if (SRF_IS_FIRSTCALL()) { - text *txt = PG_GETARG_TEXT_P(1); funcctx = SRF_FIRSTCALL_INIT(); - prs_setup_firstcall(funcctx, PG_GETARG_OID(0),txt ); - PG_FREE_IF_COPY(txt,1); + prs_setup_firstcall(funcctx, PG_GETARG_OID(0), txt); + PG_FREE_IF_COPY(txt, 1); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=prs_process_call(funcctx)) != (Datum)0 ) + if ((result = prs_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } PG_FUNCTION_INFO_V1(parse_byname); -Datum parse_byname(PG_FUNCTION_ARGS); +Datum parse_byname(PG_FUNCTION_ARGS); Datum -parse_byname(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +parse_byname(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; + + if (SRF_IS_FIRSTCALL()) + { + text *name = PG_GETARG_TEXT_P(0); + text *txt = PG_GETARG_TEXT_P(1); - if (SRF_IS_FIRSTCALL()) { - text *name = PG_GETARG_TEXT_P(0); - text *txt = PG_GETARG_TEXT_P(1); funcctx = SRF_FIRSTCALL_INIT(); - prs_setup_firstcall(funcctx, name2id_prs( name ),txt ); - PG_FREE_IF_COPY(name,0); - PG_FREE_IF_COPY(txt,1); + prs_setup_firstcall(funcctx, name2id_prs(name), txt); + PG_FREE_IF_COPY(name, 0); + PG_FREE_IF_COPY(txt, 1); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=prs_process_call(funcctx)) != (Datum)0 ) + if ((result = prs_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } PG_FUNCTION_INFO_V1(parse_current); -Datum parse_current(PG_FUNCTION_ARGS); +Datum parse_current(PG_FUNCTION_ARGS); Datum -parse_current(PG_FUNCTION_ARGS) { - FuncCallContext *funcctx; - Datum result; +parse_current(PG_FUNCTION_ARGS) +{ + FuncCallContext *funcctx; + Datum result; + + if (SRF_IS_FIRSTCALL()) + { + text *txt = PG_GETARG_TEXT_P(0); - if (SRF_IS_FIRSTCALL()) { - text *txt = PG_GETARG_TEXT_P(0); funcctx = SRF_FIRSTCALL_INIT(); - if ( current_parser_id==InvalidOid ) - current_parser_id = name2id_prs( char2text("default") ); - prs_setup_firstcall(funcctx, current_parser_id,txt ); - PG_FREE_IF_COPY(txt,0); + if (current_parser_id == InvalidOid) + current_parser_id = name2id_prs(char2text("default")); + prs_setup_firstcall(funcctx, current_parser_id, txt); + PG_FREE_IF_COPY(txt, 0); } funcctx = SRF_PERCALL_SETUP(); - if ( (result=prs_process_call(funcctx)) != (Datum)0 ) + if ((result = prs_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } PG_FUNCTION_INFO_V1(headline); -Datum headline(PG_FUNCTION_ARGS); +Datum headline(PG_FUNCTION_ARGS); Datum -headline(PG_FUNCTION_ARGS) { - TSCfgInfo *cfg=findcfg(PG_GETARG_OID(0)); - text *in = PG_GETARG_TEXT_P(1); +headline(PG_FUNCTION_ARGS) +{ + TSCfgInfo *cfg = findcfg(PG_GETARG_OID(0)); + text *in = PG_GETARG_TEXT_P(1); QUERYTYPE *query = (QUERYTYPE *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(2))); - text *opt=( PG_NARGS()>3 && PG_GETARG_POINTER(3) ) ? PG_GETARG_TEXT_P(3) : NULL; + text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL; HLPRSTEXT prs; - text *out; + text *out; WParserInfo *prsobj = findprs(cfg->prs_id); - memset(&prs,0,sizeof(HLPRSTEXT)); + memset(&prs, 0, sizeof(HLPRSTEXT)); prs.lenwords = 32; prs.words = (HLWORD *) palloc(sizeof(HLWORD) * prs.lenwords); hlparsetext(cfg, &prs, query, VARDATA(in), VARSIZE(in) - VARHDRSZ); FunctionCall3( - &(prsobj->headline_info), - PointerGetDatum(&prs), - PointerGetDatum(opt), - PointerGetDatum(query) - ); + &(prsobj->headline_info), + PointerGetDatum(&prs), + PointerGetDatum(opt), + PointerGetDatum(query) + ); out = genhl(&prs); - PG_FREE_IF_COPY(in,1); - PG_FREE_IF_COPY(query,2); - if ( opt ) PG_FREE_IF_COPY(opt,3); + PG_FREE_IF_COPY(in, 1); + PG_FREE_IF_COPY(query, 2); + if (opt) + PG_FREE_IF_COPY(opt, 3); pfree(prs.words); pfree(prs.startsel); pfree(prs.stopsel); @@ -495,35 +548,34 @@ headline(PG_FUNCTION_ARGS) { PG_FUNCTION_INFO_V1(headline_byname); -Datum headline_byname(PG_FUNCTION_ARGS); +Datum headline_byname(PG_FUNCTION_ARGS); Datum -headline_byname(PG_FUNCTION_ARGS) { - text *cfg=PG_GETARG_TEXT_P(0); +headline_byname(PG_FUNCTION_ARGS) +{ + text *cfg = PG_GETARG_TEXT_P(0); - Datum out=DirectFunctionCall4( - headline, - ObjectIdGetDatum(name2id_cfg( cfg ) ), - PG_GETARG_DATUM(1), - PG_GETARG_DATUM(2), - ( PG_NARGS()>3 ) ? PG_GETARG_DATUM(3) : PointerGetDatum(NULL) + Datum out = DirectFunctionCall4( + headline, + ObjectIdGetDatum(name2id_cfg(cfg)), + PG_GETARG_DATUM(1), + PG_GETARG_DATUM(2), + (PG_NARGS() > 3) ? PG_GETARG_DATUM(3) : PointerGetDatum(NULL) ); - PG_FREE_IF_COPY(cfg,0); - PG_RETURN_DATUM(out); + PG_FREE_IF_COPY(cfg, 0); + PG_RETURN_DATUM(out); } PG_FUNCTION_INFO_V1(headline_current); -Datum headline_current(PG_FUNCTION_ARGS); +Datum headline_current(PG_FUNCTION_ARGS); Datum -headline_current(PG_FUNCTION_ARGS) { +headline_current(PG_FUNCTION_ARGS) +{ PG_RETURN_DATUM(DirectFunctionCall4( - headline, - ObjectIdGetDatum(get_currcfg()), - PG_GETARG_DATUM(0), - PG_GETARG_DATUM(1), - ( PG_NARGS()>2 ) ? PG_GETARG_DATUM(2) : PointerGetDatum(NULL) - )); + headline, + ObjectIdGetDatum(get_currcfg()), + PG_GETARG_DATUM(0), + PG_GETARG_DATUM(1), + (PG_NARGS() > 2) ? PG_GETARG_DATUM(2) : PointerGetDatum(NULL) + )); } - - - diff --git a/contrib/tsearch2/wparser.h b/contrib/tsearch2/wparser.h index a8afc564a1..c3c44151f0 100644 --- a/contrib/tsearch2/wparser.h +++ b/contrib/tsearch2/wparser.h @@ -3,26 +3,28 @@ #include "postgres.h" #include "fmgr.h" -typedef struct { - Oid prs_id; - FmgrInfo start_info; - FmgrInfo getlexeme_info; - FmgrInfo end_info; - FmgrInfo headline_info; - Oid lextype; - void *prs; -} WParserInfo; +typedef struct +{ + Oid prs_id; + FmgrInfo start_info; + FmgrInfo getlexeme_info; + FmgrInfo end_info; + FmgrInfo headline_info; + Oid lextype; + void *prs; +} WParserInfo; -void init_prs(Oid id, WParserInfo *prs); -WParserInfo* findprs(Oid id); -Oid name2id_prs(text *name); -void reset_prs(void); +void init_prs(Oid id, WParserInfo * prs); +WParserInfo *findprs(Oid id); +Oid name2id_prs(text *name); +void reset_prs(void); -typedef struct { - int lexid; - char *alias; - char *descr; -} LexDescr; +typedef struct +{ + int lexid; + char *alias; + char *descr; +} LexDescr; #endif diff --git a/contrib/tsearch2/wparser_def.c b/contrib/tsearch2/wparser_def.c index c3b0306760..4680d746b3 100644 --- a/contrib/tsearch2/wparser_def.c +++ b/contrib/tsearch2/wparser_def.c @@ -1,5 +1,5 @@ -/* - * default word parser +/* + * default word parser * Teodor Sigaev */ #include @@ -17,40 +17,44 @@ #include "wordparser/deflex.h" PG_FUNCTION_INFO_V1(prsd_lextype); -Datum prsd_lextype(PG_FUNCTION_ARGS); +Datum prsd_lextype(PG_FUNCTION_ARGS); -Datum -prsd_lextype(PG_FUNCTION_ARGS) { - LexDescr *descr=(LexDescr*)palloc(sizeof(LexDescr)*(LASTNUM+1)); - int i; +Datum +prsd_lextype(PG_FUNCTION_ARGS) +{ + LexDescr *descr = (LexDescr *) palloc(sizeof(LexDescr) * (LASTNUM + 1)); + int i; - for(i=1;i<=LASTNUM;i++) { - descr[i-1].lexid = i; - descr[i-1].alias = pstrdup(tok_alias[i]); - descr[i-1].descr = pstrdup(lex_descr[i]); + for (i = 1; i <= LASTNUM; i++) + { + descr[i - 1].lexid = i; + descr[i - 1].alias = pstrdup(tok_alias[i]); + descr[i - 1].descr = pstrdup(lex_descr[i]); } - - descr[LASTNUM].lexid=0; - + + descr[LASTNUM].lexid = 0; + PG_RETURN_POINTER(descr); } PG_FUNCTION_INFO_V1(prsd_start); -Datum prsd_start(PG_FUNCTION_ARGS); -Datum -prsd_start(PG_FUNCTION_ARGS) { - start_parse_str( (char*)PG_GETARG_POINTER(0), PG_GETARG_INT32(1) ); +Datum prsd_start(PG_FUNCTION_ARGS); +Datum +prsd_start(PG_FUNCTION_ARGS) +{ + start_parse_str((char *) PG_GETARG_POINTER(0), PG_GETARG_INT32(1)); PG_RETURN_POINTER(NULL); } PG_FUNCTION_INFO_V1(prsd_getlexeme); -Datum prsd_getlexeme(PG_FUNCTION_ARGS); -Datum -prsd_getlexeme(PG_FUNCTION_ARGS) { +Datum prsd_getlexeme(PG_FUNCTION_ARGS); +Datum +prsd_getlexeme(PG_FUNCTION_ARGS) +{ /* ParserState *p=(ParserState*)PG_GETARG_POINTER(0); */ - char **t=(char**)PG_GETARG_POINTER(1); - int *tlen=(int*)PG_GETARG_POINTER(2); - int type=tsearch2_yylex(); + char **t = (char **) PG_GETARG_POINTER(1); + int *tlen = (int *) PG_GETARG_POINTER(2); + int type = tsearch2_yylex(); *t = token; *tlen = tokenlen; @@ -58,34 +62,39 @@ prsd_getlexeme(PG_FUNCTION_ARGS) { } PG_FUNCTION_INFO_V1(prsd_end); -Datum prsd_end(PG_FUNCTION_ARGS); -Datum -prsd_end(PG_FUNCTION_ARGS) { +Datum prsd_end(PG_FUNCTION_ARGS); +Datum +prsd_end(PG_FUNCTION_ARGS) +{ /* ParserState *p=(ParserState*)PG_GETARG_POINTER(0); */ end_parse(); PG_RETURN_VOID(); } #define LEAVETOKEN(x) ( (x)==12 ) -#define COMPLEXTOKEN(x) ( (x)==5 || (x)==15 || (x)==16 || (x)==17 ) -#define ENDPUNCTOKEN(x) ( (x)==12 ) +#define COMPLEXTOKEN(x) ( (x)==5 || (x)==15 || (x)==16 || (x)==17 ) +#define ENDPUNCTOKEN(x) ( (x)==12 ) #define IDIGNORE(x) ( (x)==13 || (x)==14 || (x)==12 || (x)==23 ) #define HLIDIGNORE(x) ( (x)==5 || (x)==13 || (x)==15 || (x)==16 || (x)==17 ) -#define NONWORDTOKEN(x) ( (x)==12 || HLIDIGNORE(x) ) +#define NONWORDTOKEN(x) ( (x)==12 || HLIDIGNORE(x) ) #define NOENDTOKEN(x) ( NONWORDTOKEN(x) || (x)==7 || (x)==8 || (x)==20 || (x)==21 || (x)==22 || IDIGNORE(x) ) -typedef struct { - HLWORD *words; - int len; -} hlCheck; +typedef struct +{ + HLWORD *words; + int len; +} hlCheck; static bool -checkcondition_HL(void *checkval, ITEM *val) { - int i; - for(i=0;i<((hlCheck*)checkval)->len;i++) { - if ( ((hlCheck*)checkval)->words[i].item==val ) +checkcondition_HL(void *checkval, ITEM * val) +{ + int i; + + for (i = 0; i < ((hlCheck *) checkval)->len; i++) + { + if (((hlCheck *) checkval)->words[i].item == val) return true; } return false; @@ -93,21 +102,28 @@ checkcondition_HL(void *checkval, ITEM *val) { static bool -hlCover(HLPRSTEXT *prs, QUERYTYPE *query, int *p, int *q) { - int i,j; - ITEM *item=GETQUERY(query); - int pos=*p; - *q=0; - *p=0x7fffffff; +hlCover(HLPRSTEXT * prs, QUERYTYPE * query, int *p, int *q) +{ + int i, + j; + ITEM *item = GETQUERY(query); + int pos = *p; - for(j=0;jsize;j++) { - if ( item->type != VAL ) { + *q = 0; + *p = 0x7fffffff; + + for (j = 0; j < query->size; j++) + { + if (item->type != VAL) + { item++; continue; } - for(i=pos;icurwords;i++) { - if ( prs->words[i].item == item ) { - if ( i>*q) + for (i = pos; i < prs->curwords; i++) + { + if (prs->words[i].item == item) + { + if (i > *q) *q = i; break; } @@ -115,32 +131,39 @@ hlCover(HLPRSTEXT *prs, QUERYTYPE *query, int *p, int *q) { item++; } - if ( *q==0 ) + if (*q == 0) return false; - item=GETQUERY(query); - for(j=0;jsize;j++) { - if ( item->type != VAL ) { + item = GETQUERY(query); + for (j = 0; j < query->size; j++) + { + if (item->type != VAL) + { item++; continue; } - for(i=*q;i>=pos;i--) { - if ( prs->words[i].item == item ) { - if ( i<*p ) - *p=i; + for (i = *q; i >= pos; i--) + { + if (prs->words[i].item == item) + { + if (i < *p) + *p = i; break; } } item++; - } + } - if ( *p<=*q ) { - hlCheck ch={ &(prs->words[*p]), *q-*p+1 }; - if ( TS_execute(GETQUERY(query), &ch, false, checkcondition_HL) ) { + if (*p <= *q) + { + hlCheck ch = {&(prs->words[*p]), *q - *p + 1}; + + if (TS_execute(GETQUERY(query), &ch, false, checkcondition_HL)) return true; - } else { + else + { (*p)++; - return hlCover(prs,query,p,q); + return hlCover(prs, query, p, q); } } @@ -148,45 +171,54 @@ hlCover(HLPRSTEXT *prs, QUERYTYPE *query, int *p, int *q) { } PG_FUNCTION_INFO_V1(prsd_headline); -Datum prsd_headline(PG_FUNCTION_ARGS); -Datum -prsd_headline(PG_FUNCTION_ARGS) { - HLPRSTEXT *prs=(HLPRSTEXT*)PG_GETARG_POINTER(0); - text *opt=(text*)PG_GETARG_POINTER(1); /* can't be toasted */ - QUERYTYPE *query=(QUERYTYPE*)PG_GETARG_POINTER(2); /* can't be toasted */ +Datum prsd_headline(PG_FUNCTION_ARGS); +Datum +prsd_headline(PG_FUNCTION_ARGS) +{ + HLPRSTEXT *prs = (HLPRSTEXT *) PG_GETARG_POINTER(0); + text *opt = (text *) PG_GETARG_POINTER(1); /* can't be toasted */ + QUERYTYPE *query = (QUERYTYPE *) PG_GETARG_POINTER(2); /* can't be toasted */ + /* from opt + start and and tag */ - int min_words=15; - int max_words=35; - int shortword=3; + int min_words = 15; + int max_words = 35; + int shortword = 3; - int p=0,q=0; - int bestb=-1,beste=-1; - int bestlen=-1; - int pose=0, poslen, curlen; + int p = 0, + q = 0; + int bestb = -1, + beste = -1; + int bestlen = -1; + int pose = 0, + poslen, + curlen; - int i; + int i; - /*config*/ - prs->startsel=NULL; - prs->stopsel=NULL; - if ( opt ) { - Map *map,*mptr; - - parse_cfgdict(opt,&map); - mptr=map; + /* config */ + prs->startsel = NULL; + prs->stopsel = NULL; + if (opt) + { + Map *map, + *mptr; + + parse_cfgdict(opt, &map); + mptr = map; + + while (mptr && mptr->key) + { + if (strcasecmp(mptr->key, "MaxWords") == 0) + max_words = pg_atoi(mptr->value, 4, 1); + else if (strcasecmp(mptr->key, "MinWords") == 0) + min_words = pg_atoi(mptr->value, 4, 1); + else if (strcasecmp(mptr->key, "ShortWord") == 0) + shortword = pg_atoi(mptr->value, 4, 1); + else if (strcasecmp(mptr->key, "StartSel") == 0) + prs->startsel = pstrdup(mptr->value); + else if (strcasecmp(mptr->key, "StopSel") == 0) + prs->stopsel = pstrdup(mptr->value); - while(mptr && mptr->key) { - if ( strcasecmp(mptr->key,"MaxWords")==0 ) - max_words=pg_atoi(mptr->value,4,1); - else if ( strcasecmp(mptr->key,"MinWords")==0 ) - min_words=pg_atoi(mptr->value,4,1); - else if ( strcasecmp(mptr->key,"ShortWord")==0 ) - shortword=pg_atoi(mptr->value,4,1); - else if ( strcasecmp(mptr->key,"StartSel")==0 ) - prs->startsel=pstrdup(mptr->value); - else if ( strcasecmp(mptr->key,"StopSel")==0 ) - prs->stopsel=pstrdup(mptr->value); - pfree(mptr->key); pfree(mptr->value); @@ -194,104 +226,118 @@ prsd_headline(PG_FUNCTION_ARGS) { } pfree(map); - if ( min_words >= max_words ) + if (min_words >= max_words) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("must be MinWords < MaxWords"))); - if ( min_words<=0 ) + if (min_words <= 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("must be MinWords > 0"))); - if ( shortword<0 ) + if (shortword < 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("must be ShortWord >= 0"))); } - while( hlCover(prs,query,&p,&q) ) { + while (hlCover(prs, query, &p, &q)) + { /* find cover len in words */ - curlen=0; - poslen=0; - for(i=p;i<=q && curlen < max_words ; i++) { - if ( !NONWORDTOKEN(prs->words[i].type) ) + curlen = 0; + poslen = 0; + for (i = p; i <= q && curlen < max_words; i++) + { + if (!NONWORDTOKEN(prs->words[i].type)) curlen++; - if ( prs->words[i].item && !prs->words[i].repeated ) - poslen++; - pose=i; + if (prs->words[i].item && !prs->words[i].repeated) + poslen++; + pose = i; } - if ( poslenwords[beste].type) || prs->words[beste].len <= shortword) ) { + if (poslen < bestlen && !(NOENDTOKEN(prs->words[beste].type) || prs->words[beste].len <= shortword)) + { /* best already finded, so try one more cover */ p++; continue; } - if ( curlen < max_words ) { /* find good end */ - for(i=i-1 ;icurwords && curlenwords[i].type) ) + if (curlen < max_words) + { /* find good end */ + for (i = i - 1; i < prs->curwords && curlen < max_words; i++) + { + if (i != q) + { + if (!NONWORDTOKEN(prs->words[i].type)) curlen++; - if ( prs->words[i].item && !prs->words[i].repeated ) + if (prs->words[i].item && !prs->words[i].repeated) poslen++; } - pose=i; - if ( NOENDTOKEN(prs->words[i].type) || prs->words[i].len <= shortword ) + pose = i; + if (NOENDTOKEN(prs->words[i].type) || prs->words[i].len <= shortword) continue; - if ( curlen>=min_words ) + if (curlen >= min_words) break; } - } else { /* shorter cover :((( */ - for(;curlen>min_words;i--) { - if ( !NONWORDTOKEN(prs->words[i].type) ) + } + else + { /* shorter cover :((( */ + for (; curlen > min_words; i--) + { + if (!NONWORDTOKEN(prs->words[i].type)) curlen--; - if ( prs->words[i].item && !prs->words[i].repeated ) + if (prs->words[i].item && !prs->words[i].repeated) poslen--; - pose=i; - if ( NOENDTOKEN(prs->words[i].type) || prs->words[i].len <= shortword ) + pose = i; + if (NOENDTOKEN(prs->words[i].type) || prs->words[i].len <= shortword) continue; break; } } - if ( bestlen <0 || (poslen>bestlen && !(NOENDTOKEN(prs->words[pose].type) || prs->words[pose].len <= shortword)) || - ( bestlen>=0 && !(NOENDTOKEN(prs->words[pose].type) || prs->words[pose].len <= shortword) && - (NOENDTOKEN(prs->words[beste].type) || prs->words[beste].len <= shortword) ) ) { - bestb=p; beste=pose; - bestlen=poslen; - } + if (bestlen < 0 || (poslen > bestlen && !(NOENDTOKEN(prs->words[pose].type) || prs->words[pose].len <= shortword)) || + (bestlen >= 0 && !(NOENDTOKEN(prs->words[pose].type) || prs->words[pose].len <= shortword) && + (NOENDTOKEN(prs->words[beste].type) || prs->words[beste].len <= shortword))) + { + bestb = p; + beste = pose; + bestlen = poslen; + } p++; } - if ( bestlen<0 ) { - curlen=0; - poslen=0; - for(i=0;icurwords && curlenwords[i].type) ) + if (bestlen < 0) + { + curlen = 0; + poslen = 0; + for (i = 0; i < prs->curwords && curlen < min_words; i++) + { + if (!NONWORDTOKEN(prs->words[i].type)) curlen++; - pose=i; + pose = i; } - bestb=0; beste=pose; + bestb = 0; + beste = pose; } - for(i=bestb;i<=beste;i++) { - if ( prs->words[i].item ) - prs->words[i].selected=1; - if ( prs->words[i].repeated ) - prs->words[i].skip=1; - if ( HLIDIGNORE(prs->words[i].type) ) - prs->words[i].replace=1; + for (i = bestb; i <= beste; i++) + { + if (prs->words[i].item) + prs->words[i].selected = 1; + if (prs->words[i].repeated) + prs->words[i].skip = 1; + if (HLIDIGNORE(prs->words[i].type)) + prs->words[i].replace = 1; - prs->words[i].in=1; + prs->words[i].in = 1; } if (!prs->startsel) - prs->startsel=pstrdup(""); + prs->startsel = pstrdup(""); if (!prs->stopsel) - prs->stopsel=pstrdup(""); - prs->startsellen=strlen(prs->startsel); - prs->stopsellen=strlen(prs->stopsel); + prs->stopsel = pstrdup(""); + prs->startsellen = strlen(prs->startsel); + prs->stopsellen = strlen(prs->stopsel); PG_RETURN_POINTER(prs); } - diff --git a/contrib/xml/pgxml_dom.c b/contrib/xml/pgxml_dom.c index f79183824e..2b11b1d646 100644 --- a/contrib/xml/pgxml_dom.c +++ b/contrib/xml/pgxml_dom.c @@ -87,10 +87,10 @@ pgxml_parse(PG_FUNCTION_ARGS) doctree = xmlParseMemory((char *) VARDATA(t), docsize); if (doctree == NULL) { - xmlCleanupParser(); + xmlCleanupParser(); PG_RETURN_BOOL(false); /* i.e. not well-formed */ } - xmlCleanupParser(); + xmlCleanupParser(); xmlFreeDoc(doctree); PG_RETURN_BOOL(true); } @@ -202,8 +202,8 @@ pgxml_xpath(PG_FUNCTION_ARGS) doctree = xmlParseMemory((char *) VARDATA(t), docsize); if (doctree == NULL) - { /* not well-formed */ - xmlCleanupParser(); + { /* not well-formed */ + xmlCleanupParser(); PG_RETURN_NULL(); } diff --git a/src/backend/access/common/heaptuple.c b/src/backend/access/common/heaptuple.c index ae1df582b0..4f2fd0efd1 100644 --- a/src/backend/access/common/heaptuple.c +++ b/src/backend/access/common/heaptuple.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/common/heaptuple.c,v 1.84 2003/07/21 20:29:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/common/heaptuple.c,v 1.85 2003/08/04 00:43:11 momjian Exp $ * * NOTES * The old interface functions have been converted to macros @@ -617,7 +617,7 @@ heap_formtuple(TupleDesc tupleDescriptor, td->t_natts = numberOfAttributes; td->t_hoff = hoff; - if (tupleDescriptor->tdhasoid) /* else leave infomask = 0 */ + if (tupleDescriptor->tdhasoid) /* else leave infomask = 0 */ td->t_infomask = HEAP_HASOID; DataFill((char *) td + hoff, diff --git a/src/backend/access/common/indextuple.c b/src/backend/access/common/indextuple.c index abf25915ab..d0ee379808 100644 --- a/src/backend/access/common/indextuple.c +++ b/src/backend/access/common/indextuple.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/common/indextuple.c,v 1.65 2003/07/21 20:29:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/common/indextuple.c,v 1.66 2003/08/04 00:43:11 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -162,9 +162,9 @@ index_formtuple(TupleDesc tupleDescriptor, if ((size & INDEX_SIZE_MASK) != size) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), - errmsg("index tuple requires %lu bytes, maximum size is %lu", - (unsigned long) size, - (unsigned long) INDEX_SIZE_MASK))); + errmsg("index tuple requires %lu bytes, maximum size is %lu", + (unsigned long) size, + (unsigned long) INDEX_SIZE_MASK))); infomask |= size; diff --git a/src/backend/access/common/printtup.c b/src/backend/access/common/printtup.c index 61ecdcd7e5..ecee11718d 100644 --- a/src/backend/access/common/printtup.c +++ b/src/backend/access/common/printtup.c @@ -9,7 +9,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/common/printtup.c,v 1.75 2003/07/21 20:29:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/common/printtup.c,v 1.76 2003/08/04 00:43:12 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -24,13 +24,13 @@ static void printtup_startup(DestReceiver *self, int operation, - TupleDesc typeinfo); + TupleDesc typeinfo); static void printtup(HeapTuple tuple, TupleDesc typeinfo, - DestReceiver *self); + DestReceiver *self); static void printtup_20(HeapTuple tuple, TupleDesc typeinfo, - DestReceiver *self); + DestReceiver *self); static void printtup_internal_20(HeapTuple tuple, TupleDesc typeinfo, - DestReceiver *self); + DestReceiver *self); static void printtup_shutdown(DestReceiver *self); static void printtup_destroy(DestReceiver *self); @@ -81,8 +81,8 @@ printtup_create_DR(CommandDest dest, Portal portal) else { /* - * In protocol 2.0 the Bind message does not exist, so there is - * no way for the columns to have different print formats; it's + * In protocol 2.0 the Bind message does not exist, so there is no + * way for the columns to have different print formats; it's * sufficient to look at the first one. */ if (portal->formats && portal->formats[0] != 0) @@ -111,12 +111,13 @@ static void printtup_startup(DestReceiver *self, int operation, TupleDesc typeinfo) { DR_printtup *myState = (DR_printtup *) self; - Portal portal = myState->portal; + Portal portal = myState->portal; if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3) { /* - * Send portal name to frontend (obsolete cruft, gone in proto 3.0) + * Send portal name to frontend (obsolete cruft, gone in proto + * 3.0) * * If portal name not specified, use "blank" portal. */ @@ -129,8 +130,8 @@ printtup_startup(DestReceiver *self, int operation, TupleDesc typeinfo) } /* - * If this is a retrieve, and we are supposed to emit row descriptions, - * then we send back the tuple descriptor of the tuples. + * If this is a retrieve, and we are supposed to emit row + * descriptions, then we send back the tuple descriptor of the tuples. */ if (operation == CMD_SELECT && myState->sendDescrip) { @@ -163,7 +164,7 @@ printtup_startup(DestReceiver *self, int operation, TupleDesc typeinfo) * or some similar function; it does not contain a full set of fields. * The targetlist will be NIL when executing a utility function that does * not have a plan. If the targetlist isn't NIL then it is a Query node's - * targetlist; it is up to us to ignore resjunk columns in it. The formats[] + * targetlist; it is up to us to ignore resjunk columns in it. The formats[] * array pointer might be NULL (if we are doing Describe on a prepared stmt); * send zeroes for the format codes in that case. */ @@ -176,14 +177,14 @@ SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats) int i; StringInfoData buf; - pq_beginmessage(&buf, 'T'); /* tuple descriptor message type */ - pq_sendint(&buf, natts, 2); /* # of attrs in tuples */ + pq_beginmessage(&buf, 'T'); /* tuple descriptor message type */ + pq_sendint(&buf, natts, 2); /* # of attrs in tuples */ for (i = 0; i < natts; ++i) { - Oid atttypid = attrs[i]->atttypid; - int32 atttypmod = attrs[i]->atttypmod; - Oid basetype; + Oid atttypid = attrs[i]->atttypid; + int32 atttypmod = attrs[i]->atttypmod; + Oid basetype; pq_sendstring(&buf, NameStr(attrs[i]->attname)); /* column ID info appears in protocol 3.0 and up */ @@ -320,8 +321,8 @@ printtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) } /* - * If we have a toasted datum, forcibly detoast it here to - * avoid memory leakage inside the type's output routine. + * If we have a toasted datum, forcibly detoast it here to avoid + * memory leakage inside the type's output routine. */ if (thisState->typisvarlena) attr = PointerGetDatum(PG_DETOAST_DATUM(origattr)); @@ -347,7 +348,7 @@ printtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) outputbytes = DatumGetByteaP(FunctionCall2(&thisState->finfo, attr, - ObjectIdGetDatum(thisState->typelem))); + ObjectIdGetDatum(thisState->typelem))); /* We assume the result will not have been toasted */ pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4); pq_sendbytes(&buf, VARDATA(outputbytes), @@ -424,8 +425,8 @@ printtup_20(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) Assert(thisState->format == 0); /* - * If we have a toasted datum, forcibly detoast it here to - * avoid memory leakage inside the type's output routine. + * If we have a toasted datum, forcibly detoast it here to avoid + * memory leakage inside the type's output routine. */ if (thisState->typisvarlena) attr = PointerGetDatum(PG_DETOAST_DATUM(origattr)); @@ -536,9 +537,10 @@ debugtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) continue; getTypeOutputInfo(typeinfo->attrs[i]->atttypid, &typoutput, &typelem, &typisvarlena); + /* - * If we have a toasted datum, forcibly detoast it here to - * avoid memory leakage inside the type's output routine. + * If we have a toasted datum, forcibly detoast it here to avoid + * memory leakage inside the type's output routine. */ if (typisvarlena) attr = PointerGetDatum(PG_DETOAST_DATUM(origattr)); @@ -547,7 +549,7 @@ debugtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) value = DatumGetCString(OidFunctionCall3(typoutput, attr, - ObjectIdGetDatum(typelem), + ObjectIdGetDatum(typelem), Int32GetDatum(typeinfo->attrs[i]->atttypmod))); printatt((unsigned) i + 1, typeinfo->attrs[i], value); @@ -627,8 +629,8 @@ printtup_internal_20(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) Assert(thisState->format == 1); /* - * If we have a toasted datum, forcibly detoast it here to - * avoid memory leakage inside the type's output routine. + * If we have a toasted datum, forcibly detoast it here to avoid + * memory leakage inside the type's output routine. */ if (thisState->typisvarlena) attr = PointerGetDatum(PG_DETOAST_DATUM(origattr)); @@ -637,7 +639,7 @@ printtup_internal_20(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) outputbytes = DatumGetByteaP(FunctionCall2(&thisState->finfo, attr, - ObjectIdGetDatum(thisState->typelem))); + ObjectIdGetDatum(thisState->typelem))); /* We assume the result will not have been toasted */ pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4); pq_sendbytes(&buf, VARDATA(outputbytes), diff --git a/src/backend/access/gist/gistscan.c b/src/backend/access/gist/gistscan.c index d3208e248e..505fd76256 100644 --- a/src/backend/access/gist/gistscan.c +++ b/src/backend/access/gist/gistscan.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/gist/gistscan.c,v 1.45 2003/07/28 00:09:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/gist/gistscan.c,v 1.46 2003/08/04 00:43:12 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -104,11 +104,12 @@ gistrescan(PG_FUNCTION_ARGS) memmove(s->keyData, key, s->numberOfKeys * sizeof(ScanKeyData)); + /* * Play games here with the scan key to use the Consistent - * function for all comparisons: 1) the sk_procedure field - * will now be used to hold the strategy number 2) the - * sk_func field will point to the Consistent function + * function for all comparisons: 1) the sk_procedure field will + * now be used to hold the strategy number 2) the sk_func field + * will point to the Consistent function */ for (i = 0; i < s->numberOfKeys; i++) { diff --git a/src/backend/access/hash/hashfunc.c b/src/backend/access/hash/hashfunc.c index a82b8b32d5..4dd9d9df3e 100644 --- a/src/backend/access/hash/hashfunc.c +++ b/src/backend/access/hash/hashfunc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/hash/hashfunc.c,v 1.36 2003/06/22 22:04:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/hashfunc.c,v 1.37 2003/08/04 00:43:12 momjian Exp $ * * NOTES * These functions are stored in pg_amproc. For each operator class @@ -60,9 +60,9 @@ hashfloat4(PG_FUNCTION_ARGS) float4 key = PG_GETARG_FLOAT4(0); /* - * On IEEE-float machines, minus zero and zero have different bit patterns - * but should compare as equal. We must ensure that they have the same - * hash value, which is most easily done this way: + * On IEEE-float machines, minus zero and zero have different bit + * patterns but should compare as equal. We must ensure that they + * have the same hash value, which is most easily done this way: */ if (key == (float4) 0) PG_RETURN_UINT32(0); @@ -76,9 +76,9 @@ hashfloat8(PG_FUNCTION_ARGS) float8 key = PG_GETARG_FLOAT8(0); /* - * On IEEE-float machines, minus zero and zero have different bit patterns - * but should compare as equal. We must ensure that they have the same - * hash value, which is most easily done this way: + * On IEEE-float machines, minus zero and zero have different bit + * patterns but should compare as equal. We must ensure that they + * have the same hash value, which is most easily done this way: */ if (key == (float8) 0) PG_RETURN_UINT32(0); @@ -121,9 +121,9 @@ hashtext(PG_FUNCTION_ARGS) Datum result; /* - * Note: this is currently identical in behavior to hashvarlena, - * but it seems likely that we may need to do something different - * in non-C locales. (See also hashbpchar, if so.) + * Note: this is currently identical in behavior to hashvarlena, but + * it seems likely that we may need to do something different in non-C + * locales. (See also hashbpchar, if so.) */ result = hash_any((unsigned char *) VARDATA(key), VARSIZE(key) - VARHDRSZ); diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c index ed9459feb9..fd7fc15822 100644 --- a/src/backend/access/hash/hashovfl.c +++ b/src/backend/access/hash/hashovfl.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/hash/hashovfl.c,v 1.35 2003/07/21 20:29:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/hashovfl.c,v 1.36 2003/08/04 00:43:12 momjian Exp $ * * NOTES * Overflow pages look like ordinary relation pages. @@ -205,8 +205,8 @@ _hash_getovfladdr(Relation rel, Buffer *metabufp) if (++splitnum >= NCACHED) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), - errmsg("out of overflow pages in hash index \"%s\"", - RelationGetRelationName(rel)))); + errmsg("out of overflow pages in hash index \"%s\"", + RelationGetRelationName(rel)))); metap->hashm_ovflpoint = splitnum; metap->hashm_spares[splitnum] = metap->hashm_spares[splitnum - 1]; metap->hashm_spares[splitnum - 1]--; diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index a0d191f8a9..8b4b5590ca 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/heap/heapam.c,v 1.152 2003/07/21 20:29:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/heap/heapam.c,v 1.153 2003/08/04 00:43:14 momjian Exp $ * * * INTERFACE ROUTINES @@ -1132,6 +1132,7 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid) xlhdr.t_natts = tup->t_data->t_natts; xlhdr.t_infomask = tup->t_data->t_infomask; xlhdr.t_hoff = tup->t_data->t_hoff; + /* * note we mark rdata[1] as belonging to buffer; if XLogInsert * decides to write the whole page to the xlog, we don't need to @@ -1149,9 +1150,9 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid) rdata[2].next = NULL; /* - * If this is the single and first tuple on page, we can reinit the - * page instead of restoring the whole thing. Set flag, and hide - * buffer references from XLogInsert. + * If this is the single and first tuple on page, we can reinit + * the page instead of restoring the whole thing. Set flag, and + * hide buffer references from XLogInsert. */ if (ItemPointerGetOffsetNumber(&(tup->t_self)) == FirstOffsetNumber && PageGetMaxOffsetNumber(page) == FirstOffsetNumber) @@ -1912,7 +1913,7 @@ log_heap_clean(Relation reln, Buffer buffer, OffsetNumber *unused, int uncnt) /* * The unused-offsets array is not actually in the buffer, but pretend - * that it is. When XLogInsert stores the whole buffer, the offsets + * that it is. When XLogInsert stores the whole buffer, the offsets * array need not be stored too. */ rdata[1].buffer = buffer; @@ -1991,9 +1992,10 @@ log_heap_update(Relation reln, Buffer oldbuf, ItemPointerData from, 2 * sizeof(TransactionId)); hsize += 2 * sizeof(TransactionId); } + /* - * As with insert records, we need not store the rdata[2] segment - * if we decide to store the whole buffer instead. + * As with insert records, we need not store the rdata[2] segment if + * we decide to store the whole buffer instead. */ rdata[2].buffer = newbuf; rdata[2].data = (char *) &xlhdr; diff --git a/src/backend/access/index/indexam.c b/src/backend/access/index/indexam.c index 731c34b3ab..ee93e8a722 100644 --- a/src/backend/access/index/indexam.c +++ b/src/backend/access/index/indexam.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/index/indexam.c,v 1.67 2003/07/21 20:29:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/index/indexam.c,v 1.68 2003/08/04 00:43:15 momjian Exp $ * * INTERFACE ROUTINES * index_open - open an index relation by relation OID @@ -300,7 +300,7 @@ index_beginscan(Relation heapRelation, * index_rescan - (re)start a scan of an index * * The caller may specify a new set of scankeys (but the number of keys - * cannot change). To restart the scan without changing keys, pass NULL + * cannot change). To restart the scan without changing keys, pass NULL * for the key array. * * Note that this is also called when first starting an indexscan; @@ -394,8 +394,8 @@ index_restrpos(IndexScanDesc scan) /* * We do not reset got_tuple; so if the scan is actually being - * short-circuited by index_getnext, the effective position restoration - * is done by restoring unique_tuple_pos. + * short-circuited by index_getnext, the effective position + * restoration is done by restoring unique_tuple_pos. */ scan->unique_tuple_pos = scan->unique_tuple_mark; @@ -427,24 +427,24 @@ index_getnext(IndexScanDesc scan, ScanDirection direction) } /* - * If we already got a tuple and it must be unique, there's no need - * to make the index AM look through any additional tuples. (This can + * If we already got a tuple and it must be unique, there's no need to + * make the index AM look through any additional tuples. (This can * save a useful amount of work in scenarios where there are many dead * tuples due to heavy update activity.) * * To do this we must keep track of the logical scan position * (before/on/after tuple). Also, we have to be sure to release scan - * resources before returning NULL; if we fail to do so then a multi-index - * scan can easily run the system out of free buffers. We can release - * index-level resources fairly cheaply by calling index_rescan. This - * means there are two persistent states as far as the index AM is - * concerned: on-tuple and rescanned. If we are actually asked to - * re-fetch the single tuple, we have to go through a fresh indexscan - * startup, which penalizes that (infrequent) case. + * resources before returning NULL; if we fail to do so then a + * multi-index scan can easily run the system out of free buffers. We + * can release index-level resources fairly cheaply by calling + * index_rescan. This means there are two persistent states as far as + * the index AM is concerned: on-tuple and rescanned. If we are + * actually asked to re-fetch the single tuple, we have to go through + * a fresh indexscan startup, which penalizes that (infrequent) case. */ if (scan->keys_are_unique && scan->got_tuple) { - int new_tuple_pos = scan->unique_tuple_pos; + int new_tuple_pos = scan->unique_tuple_pos; if (ScanDirectionIsForward(direction)) { @@ -459,22 +459,23 @@ index_getnext(IndexScanDesc scan, ScanDirection direction) if (new_tuple_pos == 0) { /* - * We are moving onto the unique tuple from having been off it. - * We just fall through and let the index AM do the work. Note - * we should get the right answer regardless of scan direction. + * We are moving onto the unique tuple from having been off + * it. We just fall through and let the index AM do the work. + * Note we should get the right answer regardless of scan + * direction. */ - scan->unique_tuple_pos = 0; /* need to update position */ + scan->unique_tuple_pos = 0; /* need to update position */ } else { /* - * Moving off the tuple; must do amrescan to release index-level - * pins before we return NULL. Since index_rescan will reset - * my state, must save and restore... + * Moving off the tuple; must do amrescan to release + * index-level pins before we return NULL. Since index_rescan + * will reset my state, must save and restore... */ - int unique_tuple_mark = scan->unique_tuple_mark; + int unique_tuple_mark = scan->unique_tuple_mark; - index_rescan(scan, NULL /* no change to key */); + index_rescan(scan, NULL /* no change to key */ ); scan->keys_are_unique = true; scan->got_tuple = true; @@ -631,7 +632,7 @@ index_bulk_delete(Relation indexRelation, */ IndexBulkDeleteResult * index_vacuum_cleanup(Relation indexRelation, - IndexVacuumCleanupInfo *info, + IndexVacuumCleanupInfo * info, IndexBulkDeleteResult *stats) { RegProcedure procedure; @@ -649,7 +650,7 @@ index_vacuum_cleanup(Relation indexRelation, DatumGetPointer(OidFunctionCall3(procedure, PointerGetDatum(indexRelation), PointerGetDatum((Pointer) info), - PointerGetDatum((Pointer) stats))); + PointerGetDatum((Pointer) stats))); return result; } diff --git a/src/backend/access/nbtree/nbtinsert.c b/src/backend/access/nbtree/nbtinsert.c index dd8eda99b9..962d7a1822 100644 --- a/src/backend/access/nbtree/nbtinsert.c +++ b/src/backend/access/nbtree/nbtinsert.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtinsert.c,v 1.102 2003/07/28 00:09:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtinsert.c,v 1.103 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -432,9 +432,9 @@ _bt_insertonpg(Relation rel, * * must write-lock that page before releasing write lock on * current page; else someone else's _bt_check_unique scan - * could fail to see our insertion. write locks on intermediate - * dead pages won't do because we don't know when they will get - * de-linked from the tree. + * could fail to see our insertion. write locks on + * intermediate dead pages won't do because we don't know when + * they will get de-linked from the tree. */ Buffer rbuf = InvalidBuffer; @@ -523,9 +523,10 @@ _bt_insertonpg(Relation rel, /* * If we are doing this insert because we split a page that was * the only one on its tree level, but was not the root, it may - * have been the "fast root". We need to ensure that the fast root - * link points at or above the current page. We can safely acquire - * a lock on the metapage here --- see comments for _bt_newroot(). + * have been the "fast root". We need to ensure that the fast + * root link points at or above the current page. We can safely + * acquire a lock on the metapage here --- see comments for + * _bt_newroot(). */ if (split_only_page) { @@ -1135,7 +1136,7 @@ _bt_checksplitloc(FindSplitData *state, OffsetNumber firstright, * * On entry, buf and rbuf are the left and right split pages, which we * still hold write locks on per the L&Y algorithm. We release the - * write locks once we have write lock on the parent page. (Any sooner, + * write locks once we have write lock on the parent page. (Any sooner, * and it'd be possible for some other process to try to split or delete * one of these pages, and get confused because it cannot find the downlink.) * @@ -1155,19 +1156,19 @@ _bt_insert_parent(Relation rel, bool is_only) { /* - * Here we have to do something Lehman and Yao don't talk about: - * deal with a root split and construction of a new root. If our - * stack is empty then we have just split a node on what had been - * the root level when we descended the tree. If it was still the - * root then we perform a new-root construction. If it *wasn't* - * the root anymore, search to find the next higher level that - * someone constructed meanwhile, and find the right place to insert - * as for the normal case. + * Here we have to do something Lehman and Yao don't talk about: deal + * with a root split and construction of a new root. If our stack is + * empty then we have just split a node on what had been the root + * level when we descended the tree. If it was still the root then we + * perform a new-root construction. If it *wasn't* the root anymore, + * search to find the next higher level that someone constructed + * meanwhile, and find the right place to insert as for the normal + * case. * - * If we have to search for the parent level, we do so by - * re-descending from the root. This is not super-efficient, - * but it's rare enough not to matter. (This path is also taken - * when called from WAL recovery --- we have no stack in that case.) + * If we have to search for the parent level, we do so by re-descending + * from the root. This is not super-efficient, but it's rare enough + * not to matter. (This path is also taken when called from WAL + * recovery --- we have no stack in that case.) */ if (is_root) { @@ -1222,9 +1223,9 @@ _bt_insert_parent(Relation rel, /* * Find the parent buffer and get the parent page. * - * Oops - if we were moved right then we need to change stack - * item! We want to find parent pointing to where we are, - * right ? - vadim 05/27/97 + * Oops - if we were moved right then we need to change stack item! + * We want to find parent pointing to where we are, right ? - + * vadim 05/27/97 */ ItemPointerSet(&(stack->bts_btitem.bti_itup.t_tid), bknum, P_HIKEY); @@ -1296,16 +1297,16 @@ _bt_getstackbuf(Relation rel, BTStack stack, int access) /* * start = InvalidOffsetNumber means "search the whole page". - * We need this test anyway due to possibility that - * page has a high key now when it didn't before. + * We need this test anyway due to possibility that page has a + * high key now when it didn't before. */ if (start < minoff) start = minoff; /* * These loops will check every item on the page --- but in an - * order that's attuned to the probability of where it actually - * is. Scan to the right first, then to the left. + * order that's attuned to the probability of where it + * actually is. Scan to the right first, then to the left. */ for (offnum = start; offnum <= maxoff; diff --git a/src/backend/access/nbtree/nbtpage.c b/src/backend/access/nbtree/nbtpage.c index 33f85cd59a..ace06f0a25 100644 --- a/src/backend/access/nbtree/nbtpage.c +++ b/src/backend/access/nbtree/nbtpage.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtpage.c,v 1.66 2003/07/21 20:29:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtpage.c,v 1.67 2003/08/04 00:43:15 momjian Exp $ * * NOTES * Postgres btree pages look like ordinary relation pages. The opaque @@ -181,8 +181,8 @@ _bt_getroot(Relation rel, int access) /* * Metadata initialized by someone else. In order to * guarantee no deadlocks, we have to release the metadata - * page and start all over again. (Is that really true? - * But it's hardly worth trying to optimize this case.) + * page and start all over again. (Is that really true? But + * it's hardly worth trying to optimize this case.) */ _bt_relbuf(rel, metabuf); return _bt_getroot(rel, access); @@ -190,8 +190,8 @@ _bt_getroot(Relation rel, int access) /* * Get, initialize, write, and leave a lock of the appropriate - * type on the new root page. Since this is the first page in - * the tree, it's a leaf as well as the root. + * type on the new root page. Since this is the first page in the + * tree, it's a leaf as well as the root. */ rootbuf = _bt_getbuf(rel, P_NEW, BT_WRITE); rootblkno = BufferGetBlockNumber(rootbuf); @@ -240,7 +240,7 @@ _bt_getroot(Relation rel, int access) _bt_wrtnorelbuf(rel, rootbuf); /* - * swap root write lock for read lock. There is no danger of + * swap root write lock for read lock. There is no danger of * anyone else accessing the new root page while it's unlocked, * since no one else knows where it is yet. */ @@ -284,8 +284,8 @@ _bt_getroot(Relation rel, int access) } /* - * By here, we have a pin and read lock on the root page, and no - * lock set on the metadata page. Return the root page's buffer. + * By here, we have a pin and read lock on the root page, and no lock + * set on the metadata page. Return the root page's buffer. */ return rootbuf; } @@ -299,7 +299,7 @@ _bt_getroot(Relation rel, int access) * By the time we acquire lock on the root page, it might have been split and * not be the true root anymore. This is okay for the present uses of this * routine; we only really need to be able to move up at least one tree level - * from whatever non-root page we were at. If we ever do need to lock the + * from whatever non-root page we were at. If we ever do need to lock the * one true root page, we could loop here, re-reading the metapage on each * failure. (Note that it wouldn't do to hold the lock on the metapage while * moving to the root --- that'd deadlock against any concurrent root split.) @@ -406,9 +406,9 @@ _bt_getbuf(Relation rel, BlockNumber blkno, int access) * First see if the FSM knows of any free pages. * * We can't trust the FSM's report unreservedly; we have to check - * that the page is still free. (For example, an already-free page - * could have been re-used between the time the last VACUUM scanned - * it and the time the VACUUM made its FSM updates.) + * that the page is still free. (For example, an already-free + * page could have been re-used between the time the last VACUUM + * scanned it and the time the VACUUM made its FSM updates.) */ for (;;) { @@ -431,10 +431,10 @@ _bt_getbuf(Relation rel, BlockNumber blkno, int access) /* * Extend the relation by one page. * - * We have to use a lock to ensure no one else is extending the rel at - * the same time, else we will both try to initialize the same new - * page. We can skip locking for new or temp relations, however, - * since no one else could be accessing them. + * We have to use a lock to ensure no one else is extending the rel + * at the same time, else we will both try to initialize the same + * new page. We can skip locking for new or temp relations, + * however, since no one else could be accessing them. */ needLock = !(rel->rd_isnew || rel->rd_istemp); @@ -444,8 +444,8 @@ _bt_getbuf(Relation rel, BlockNumber blkno, int access) buf = ReadBuffer(rel, P_NEW); /* - * Release the file-extension lock; it's now OK for someone else to - * extend the relation some more. + * Release the file-extension lock; it's now OK for someone else + * to extend the relation some more. */ if (needLock) UnlockPage(rel, 0, ExclusiveLock); @@ -484,7 +484,7 @@ _bt_relbuf(Relation rel, Buffer buf) * and a pin on the buffer. * * NOTE: actually, the buffer manager just marks the shared buffer page - * dirty here; the real I/O happens later. This is okay since we are not + * dirty here; the real I/O happens later. This is okay since we are not * relying on write ordering anyway. The WAL mechanism is responsible for * guaranteeing correctness after a crash. */ @@ -534,13 +534,14 @@ _bt_page_recyclable(Page page) BTPageOpaque opaque; /* - * It's possible to find an all-zeroes page in an index --- for example, - * a backend might successfully extend the relation one page and then - * crash before it is able to make a WAL entry for adding the page. - * If we find a zeroed page then reclaim it. + * It's possible to find an all-zeroes page in an index --- for + * example, a backend might successfully extend the relation one page + * and then crash before it is able to make a WAL entry for adding the + * page. If we find a zeroed page then reclaim it. */ if (PageIsNew(page)) return true; + /* * Otherwise, recycle if deleted and too old to have any processes * interested in it. @@ -565,7 +566,7 @@ _bt_page_recyclable(Page page) * mistake. On exit, metapage data is correct and we no longer have * a pin or lock on the metapage. * - * Actually this is not used for splitting on-the-fly anymore. It's only used + * Actually this is not used for splitting on-the-fly anymore. It's only used * in nbtsort.c at the completion of btree building, where we know we have * sole access to the index anyway. */ @@ -623,7 +624,7 @@ _bt_metaproot(Relation rel, BlockNumber rootbknum, uint32 level) /* * Delete item(s) from a btree page. * - * This must only be used for deleting leaf items. Deleting an item on a + * This must only be used for deleting leaf items. Deleting an item on a * non-leaf page has to be done as part of an atomic action that includes * deleting the page it points to. * @@ -646,9 +647,7 @@ _bt_delitems(Relation rel, Buffer buf, * adjusting item numbers for previous deletions. */ for (i = nitems - 1; i >= 0; i--) - { PageIndexTupleDelete(page, itemnos[i]); - } /* XLOG stuff */ if (!rel->rd_istemp) @@ -666,8 +665,8 @@ _bt_delitems(Relation rel, Buffer buf, rdata[0].next = &(rdata[1]); /* - * The target-offsets array is not in the buffer, but pretend - * that it is. When XLogInsert stores the whole buffer, the offsets + * The target-offsets array is not in the buffer, but pretend that + * it is. When XLogInsert stores the whole buffer, the offsets * array need not be stored too. */ rdata[1].buffer = buf; @@ -701,7 +700,7 @@ _bt_delitems(Relation rel, Buffer buf, * may currently be trying to follow links leading to the page; they have to * be allowed to use its right-link to recover. See nbtree/README. * - * On entry, the target buffer must be pinned and read-locked. This lock and + * On entry, the target buffer must be pinned and read-locked. This lock and * pin will be dropped before exiting. * * Returns the number of pages successfully deleted (zero on failure; could @@ -714,7 +713,7 @@ _bt_delitems(Relation rel, Buffer buf, int _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) { - BlockNumber target, + BlockNumber target, leftsib, rightsib, parent; @@ -740,17 +739,18 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) BTPageOpaque opaque; /* - * We can never delete rightmost pages nor root pages. While at it, + * We can never delete rightmost pages nor root pages. While at it, * check that page is not already deleted and is empty. */ page = BufferGetPage(buf); opaque = (BTPageOpaque) PageGetSpecialPointer(page); if (P_RIGHTMOST(opaque) || P_ISROOT(opaque) || P_ISDELETED(opaque) || - P_FIRSTDATAKEY(opaque) <= PageGetMaxOffsetNumber(page)) + P_FIRSTDATAKEY(opaque) <= PageGetMaxOffsetNumber(page)) { _bt_relbuf(rel, buf); return 0; } + /* * Save info about page, including a copy of its high key (it must * have one, being non-rightmost). @@ -760,12 +760,13 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) leftsib = opaque->btpo_prev; itemid = PageGetItemId(page, P_HIKEY); targetkey = CopyBTItem((BTItem) PageGetItem(page, itemid)); + /* * We need to get an approximate pointer to the page's parent page. - * Use the standard search mechanism to search for the page's high key; - * this will give us a link to either the current parent or someplace - * to its left (if there are multiple equal high keys). To avoid - * deadlocks, we'd better drop the target page lock first. + * Use the standard search mechanism to search for the page's high + * key; this will give us a link to either the current parent or + * someplace to its left (if there are multiple equal high keys). To + * avoid deadlocks, we'd better drop the target page lock first. */ _bt_relbuf(rel, buf); /* we need a scan key to do our search, so build one */ @@ -775,9 +776,11 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) &lbuf, BT_READ); /* don't need a pin on that either */ _bt_relbuf(rel, lbuf); + /* * If we are trying to delete an interior page, _bt_search did more - * than we needed. Locate the stack item pointing to our parent level. + * than we needed. Locate the stack item pointing to our parent + * level. */ ilevel = 0; for (;;) @@ -789,10 +792,12 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) stack = stack->bts_parent; ilevel++; } + /* * We have to lock the pages we need to modify in the standard order: - * moving right, then up. Else we will deadlock against other writers. - * + * moving right, then up. Else we will deadlock against other + * writers. + * * So, we need to find and write-lock the current left sibling of the * target page. The sibling that was current a moment ago could have * split, so we may have to move right. This search could fail if @@ -823,21 +828,24 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) } else lbuf = InvalidBuffer; + /* - * Next write-lock the target page itself. It should be okay to take just - * a write lock not a superexclusive lock, since no scans would stop on an - * empty page. + * Next write-lock the target page itself. It should be okay to take + * just a write lock not a superexclusive lock, since no scans would + * stop on an empty page. */ buf = _bt_getbuf(rel, target, BT_WRITE); page = BufferGetPage(buf); opaque = (BTPageOpaque) PageGetSpecialPointer(page); + /* - * Check page is still empty etc, else abandon deletion. The empty check - * is necessary since someone else might have inserted into it while - * we didn't have it locked; the others are just for paranoia's sake. + * Check page is still empty etc, else abandon deletion. The empty + * check is necessary since someone else might have inserted into it + * while we didn't have it locked; the others are just for paranoia's + * sake. */ if (P_RIGHTMOST(opaque) || P_ISROOT(opaque) || P_ISDELETED(opaque) || - P_FIRSTDATAKEY(opaque) <= PageGetMaxOffsetNumber(page)) + P_FIRSTDATAKEY(opaque) <= PageGetMaxOffsetNumber(page)) { _bt_relbuf(rel, buf); if (BufferIsValid(lbuf)) @@ -846,14 +854,17 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) } if (opaque->btpo_prev != leftsib) elog(ERROR, "left link changed unexpectedly"); + /* * And next write-lock the (current) right sibling. */ rightsib = opaque->btpo_next; rbuf = _bt_getbuf(rel, rightsib, BT_WRITE); + /* * Next find and write-lock the current parent of the target page. - * This is essentially the same as the corresponding step of splitting. + * This is essentially the same as the corresponding step of + * splitting. */ ItemPointerSet(&(stack->bts_btitem.bti_itup.t_tid), target, P_HIKEY); @@ -863,10 +874,11 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) RelationGetRelationName(rel)); parent = stack->bts_blkno; poffset = stack->bts_offset; + /* * If the target is the rightmost child of its parent, then we can't - * delete, unless it's also the only child --- in which case the parent - * changes to half-dead status. + * delete, unless it's also the only child --- in which case the + * parent changes to half-dead status. */ page = BufferGetPage(pbuf); opaque = (BTPageOpaque) PageGetSpecialPointer(page); @@ -893,12 +905,13 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) if (OffsetNumberNext(P_FIRSTDATAKEY(opaque)) == maxoff) parent_one_child = true; } + /* * If we are deleting the next-to-last page on the target's level, - * then the rightsib is a candidate to become the new fast root. - * (In theory, it might be possible to push the fast root even further - * down, but the odds of doing so are slim, and the locking considerations - * daunting.) + * then the rightsib is a candidate to become the new fast root. (In + * theory, it might be possible to push the fast root even further + * down, but the odds of doing so are slim, and the locking + * considerations daunting.) * * We can safely acquire a lock on the metapage here --- see comments for * _bt_newroot(). @@ -914,12 +927,13 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) metabuf = _bt_getbuf(rel, BTREE_METAPAGE, BT_WRITE); metapg = BufferGetPage(metabuf); metad = BTPageGetMeta(metapg); + /* * The expected case here is btm_fastlevel == targetlevel+1; - * if the fastlevel is <= targetlevel, something is wrong, and we - * choose to overwrite it to fix it. + * if the fastlevel is <= targetlevel, something is wrong, and + * we choose to overwrite it to fix it. */ - if (metad->btm_fastlevel > targetlevel+1) + if (metad->btm_fastlevel > targetlevel + 1) { /* no update wanted */ _bt_relbuf(rel, metabuf); @@ -937,9 +951,9 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) /* * Update parent. The normal case is a tad tricky because we want to - * delete the target's downlink and the *following* key. Easiest way is - * to copy the right sibling's downlink over the target downlink, and then - * delete the following item. + * delete the target's downlink and the *following* key. Easiest way + * is to copy the right sibling's downlink over the target downlink, + * and then delete the following item. */ page = BufferGetPage(pbuf); opaque = (BTPageOpaque) PageGetSpecialPointer(page); @@ -950,7 +964,7 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) } else { - OffsetNumber nextoffset; + OffsetNumber nextoffset; itemid = PageGetItemId(page, poffset); btitem = (BTItem) PageGetItem(page, itemid); @@ -968,8 +982,8 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) } /* - * Update siblings' side-links. Note the target page's side-links will - * continue to point to the siblings. + * Update siblings' side-links. Note the target page's side-links + * will continue to point to the siblings. */ if (BufferIsValid(lbuf)) { @@ -1096,10 +1110,11 @@ _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full) _bt_wrtbuf(rel, lbuf); /* - * If parent became half dead, recurse to try to delete it. Otherwise, - * if right sibling is empty and is now the last child of the parent, - * recurse to try to delete it. (These cases cannot apply at the same - * time, though the second case might itself recurse to the first.) + * If parent became half dead, recurse to try to delete it. + * Otherwise, if right sibling is empty and is now the last child of + * the parent, recurse to try to delete it. (These cases cannot apply + * at the same time, though the second case might itself recurse to + * the first.) */ if (parent_half_dead) { diff --git a/src/backend/access/nbtree/nbtree.c b/src/backend/access/nbtree/nbtree.c index 3c814725fe..7d0dea4e78 100644 --- a/src/backend/access/nbtree/nbtree.c +++ b/src/backend/access/nbtree/nbtree.c @@ -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.103 2003/07/21 20:29:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtree.c,v 1.104 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -580,19 +580,20 @@ btbulkdelete(PG_FUNCTION_ARGS) /* * The outer loop iterates over index leaf pages, the inner over items - * on a leaf page. We issue just one _bt_delitems() call per page, - * so as to minimize WAL traffic. + * on a leaf page. We issue just one _bt_delitems() call per page, so + * as to minimize WAL traffic. * - * Note that we exclusive-lock every leaf page containing data items, - * in sequence left to right. It sounds attractive to only exclusive-lock - * those containing items we need to delete, but unfortunately that - * is not safe: we could then pass a stopped indexscan, which could - * in rare cases lead to deleting the item it needs to find when it - * resumes. (See _bt_restscan --- this could only happen if an indexscan - * stops on a deletable item and then a page split moves that item - * into a page further to its right, which the indexscan will have no - * pin on.) We can skip obtaining exclusive lock on empty pages - * though, since no indexscan could be stopped on those. + * Note that we exclusive-lock every leaf page containing data items, in + * sequence left to right. It sounds attractive to only + * exclusive-lock those containing items we need to delete, but + * unfortunately that is not safe: we could then pass a stopped + * indexscan, which could in rare cases lead to deleting the item it + * needs to find when it resumes. (See _bt_restscan --- this could + * only happen if an indexscan stops on a deletable item and then a + * page split moves that item into a page further to its right, which + * the indexscan will have no pin on.) We can skip obtaining + * exclusive lock on empty pages though, since no indexscan could be + * stopped on those. */ buf = _bt_get_endpoint(rel, 0, false); if (BufferIsValid(buf)) /* check for empty index */ @@ -604,7 +605,7 @@ btbulkdelete(PG_FUNCTION_ARGS) OffsetNumber offnum, minoff, maxoff; - BlockNumber nextpage; + BlockNumber nextpage; CHECK_FOR_INTERRUPTS(); @@ -622,12 +623,14 @@ btbulkdelete(PG_FUNCTION_ARGS) */ LockBuffer(buf, BUFFER_LOCK_UNLOCK); LockBufferForCleanup(buf); + /* - * Recompute minoff/maxoff, both of which could have changed - * while we weren't holding the lock. + * Recompute minoff/maxoff, both of which could have + * changed while we weren't holding the lock. */ minoff = P_FIRSTDATAKEY(opaque); maxoff = PageGetMaxOffsetNumber(page); + /* * Scan over all items to see which ones need deleted * according to the callback function. @@ -640,7 +643,7 @@ btbulkdelete(PG_FUNCTION_ARGS) ItemPointer htup; btitem = (BTItem) PageGetItem(page, - PageGetItemId(page, offnum)); + PageGetItemId(page, offnum)); htup = &(btitem->bti_itup.t_tid); if (callback(htup, callback_state)) { @@ -651,6 +654,7 @@ btbulkdelete(PG_FUNCTION_ARGS) num_index_tuples += 1; } } + /* * If we need to delete anything, do it and write the buffer; * else just release the buffer. @@ -662,9 +666,7 @@ btbulkdelete(PG_FUNCTION_ARGS) _bt_wrtbuf(rel, buf); } else - { _bt_relbuf(rel, buf); - } /* And advance to next page, if any */ if (nextpage == P_NONE) break; @@ -712,7 +714,7 @@ btvacuumcleanup(PG_FUNCTION_ARGS) /* No point in remembering more than MaxFSMPages pages */ maxFreePages = MaxFSMPages; if ((BlockNumber) maxFreePages > num_pages) - maxFreePages = (int) num_pages + 1; /* +1 to avoid palloc(0) */ + maxFreePages = (int) num_pages + 1; /* +1 to avoid palloc(0) */ freePages = (BlockNumber *) palloc(maxFreePages * sizeof(BlockNumber)); nFreePages = 0; @@ -728,10 +730,10 @@ btvacuumcleanup(PG_FUNCTION_ARGS) * after we start the scan will not be examined; this should be fine, * since they can't possibly be empty.) */ - for (blkno = BTREE_METAPAGE+1; blkno < num_pages; blkno++) + for (blkno = BTREE_METAPAGE + 1; blkno < num_pages; blkno++) { - Buffer buf; - Page page; + Buffer buf; + Page page; BTPageOpaque opaque; buf = _bt_getbuf(rel, blkno, BT_READ); @@ -753,7 +755,7 @@ btvacuumcleanup(PG_FUNCTION_ARGS) P_FIRSTDATAKEY(opaque) > PageGetMaxOffsetNumber(page)) { /* Empty, try to delete */ - int ndel; + int ndel; /* Run pagedel in a temp context to avoid memory leakage */ MemoryContextReset(mycontext); @@ -768,7 +770,7 @@ btvacuumcleanup(PG_FUNCTION_ARGS) /* * During VACUUM FULL it's okay to recycle deleted pages * immediately, since there can be no other transactions - * scanning the index. Note that we will only recycle the + * scanning the index. Note that we will only recycle the * current page and not any parent pages that _bt_pagedel * might have recursed to; this seems reasonable in the name * of simplicity. (Trying to do otherwise would mean we'd @@ -787,16 +789,16 @@ btvacuumcleanup(PG_FUNCTION_ARGS) } /* - * During VACUUM FULL, we truncate off any recyclable pages at the - * end of the index. In a normal vacuum it'd be unsafe to do this - * except by acquiring exclusive lock on the index and then rechecking - * all the pages; doesn't seem worth it. + * During VACUUM FULL, we truncate off any recyclable pages at the end + * of the index. In a normal vacuum it'd be unsafe to do this except + * by acquiring exclusive lock on the index and then rechecking all + * the pages; doesn't seem worth it. */ if (info->vacuum_full && nFreePages > 0) { - BlockNumber new_pages = num_pages; + BlockNumber new_pages = num_pages; - while (nFreePages > 0 && freePages[nFreePages-1] == new_pages-1) + while (nFreePages > 0 && freePages[nFreePages - 1] == new_pages - 1) { new_pages--; pages_deleted--; @@ -810,9 +812,10 @@ btvacuumcleanup(PG_FUNCTION_ARGS) * Okay to truncate. * * First, flush any shared buffers for the blocks we intend to - * delete. FlushRelationBuffers is a bit more than we need for - * this, since it will also write out dirty buffers for blocks we - * aren't deleting, but it's the closest thing in bufmgr's API. + * delete. FlushRelationBuffers is a bit more than we need + * for this, since it will also write out dirty buffers for + * blocks we aren't deleting, but it's the closest thing in + * bufmgr's API. */ i = FlushRelationBuffers(rel, new_pages); if (i < 0) @@ -822,7 +825,8 @@ btvacuumcleanup(PG_FUNCTION_ARGS) * Do the physical truncation. */ new_pages = smgrtruncate(DEFAULT_SMGR, rel, new_pages); - rel->rd_nblocks = new_pages; /* update relcache immediately */ + rel->rd_nblocks = new_pages; /* update relcache + * immediately */ rel->rd_targblock = InvalidBlockNumber; num_pages = new_pages; } @@ -856,7 +860,7 @@ btvacuumcleanup(PG_FUNCTION_ARGS) * and so no deletion can have occurred on that page. * * On entry, we have a pin but no read lock on the buffer that contained - * the index tuple we stopped the scan on. On exit, we have pin and read + * the index tuple we stopped the scan on. On exit, we have pin and read * lock on the buffer that now contains that index tuple, and the scandesc's * current position is updated to point at it. */ @@ -877,8 +881,8 @@ _bt_restscan(IndexScanDesc scan) BlockNumber blkno; /* - * Reacquire read lock on the buffer. (We should still have - * a reference-count pin on it, so need not get that.) + * Reacquire read lock on the buffer. (We should still have a + * reference-count pin on it, so need not get that.) */ LockBuffer(buf, BT_READ); @@ -921,11 +925,11 @@ _bt_restscan(IndexScanDesc scan) /* * The item we're looking for moved right at least one page, so - * move right. We are careful here to pin and read-lock the next - * non-dead page before releasing the current one. This ensures that - * a concurrent btbulkdelete scan cannot pass our position --- if it - * did, it might be able to reach and delete our target item before - * we can find it again. + * move right. We are careful here to pin and read-lock the next + * non-dead page before releasing the current one. This ensures + * that a concurrent btbulkdelete scan cannot pass our position + * --- if it did, it might be able to reach and delete our target + * item before we can find it again. */ if (P_RIGHTMOST(opaque)) elog(ERROR, "failed to re-find previous key in \"%s\"", diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c index 457914adf7..80abe195ce 100644 --- a/src/backend/access/nbtree/nbtsearch.c +++ b/src/backend/access/nbtree/nbtsearch.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsearch.c,v 1.77 2003/07/29 22:18:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsearch.c,v 1.78 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -64,8 +64,8 @@ _bt_search(Relation rel, int keysz, ScanKey scankey, /* * Race -- the page we just grabbed may have split since we read - * its pointer in the parent (or metapage). If it has, we may need - * to move right to its new sibling. Do that. + * its pointer in the parent (or metapage). If it has, we may + * need to move right to its new sibling. Do that. */ *bufP = _bt_moveright(rel, *bufP, keysz, scankey, BT_READ); @@ -87,14 +87,14 @@ _bt_search(Relation rel, int keysz, ScanKey scankey, par_blkno = BufferGetBlockNumber(*bufP); /* - * We need to save the location of the index entry we chose in - * the parent page on a stack. In case we split the tree, we'll - * use the stack to work back up to the parent page. We also save - * the actual downlink (TID) to uniquely identify the index entry, - * in case it moves right while we're working lower in the - * tree. See the paper by Lehman and Yao for how this is detected - * and handled. (We use the child link to disambiguate duplicate - * keys in the index -- Lehman and Yao disallow duplicate keys.) + * We need to save the location of the index entry we chose in the + * parent page on a stack. In case we split the tree, we'll use + * the stack to work back up to the parent page. We also save the + * actual downlink (TID) to uniquely identify the index entry, in + * case it moves right while we're working lower in the tree. See + * the paper by Lehman and Yao for how this is detected and + * handled. (We use the child link to disambiguate duplicate keys + * in the index -- Lehman and Yao disallow duplicate keys.) */ new_stack = (BTStack) palloc(sizeof(BTStackData)); new_stack->bts_blkno = par_blkno; @@ -151,8 +151,8 @@ _bt_moveright(Relation rel, * might not need to move right; have to scan the page first anyway.) * It could even have split more than once, so scan as far as needed. * - * We also have to move right if we followed a link that brought us to - * a dead page. + * We also have to move right if we followed a link that brought us to a + * dead page. */ while (!P_RIGHTMOST(opaque) && (P_IGNORE(opaque) || @@ -599,8 +599,8 @@ _bt_first(IndexScanDesc scan, ScanDirection dir) /* * At this point we are positioned at the first item >= scan key, or * possibly at the end of a page on which all the existing items are - * less than the scan key and we know that everything on later - * pages is greater than or equal to scan key. + * less than the scan key and we know that everything on later pages + * is greater than or equal to scan key. * * We could step forward in the latter case, but that'd be a waste of * time if we want to scan backwards. So, it's now time to examine @@ -851,7 +851,8 @@ _bt_step(IndexScanDesc scan, Buffer *bufP, ScanDirection dir) } } } - else /* backwards scan */ + else +/* backwards scan */ { if (offnum > P_FIRSTDATAKEY(opaque)) offnum = OffsetNumberPrev(offnum); @@ -860,9 +861,9 @@ _bt_step(IndexScanDesc scan, Buffer *bufP, ScanDirection dir) /* * Walk left to the next page with data. This is much more * complex than the walk-right case because of the possibility - * that the page to our left splits while we are in flight to it, - * plus the possibility that the page we were on gets deleted - * after we leave it. See nbtree/README for details. + * that the page to our left splits while we are in flight to + * it, plus the possibility that the page we were on gets + * deleted after we leave it. See nbtree/README for details. */ for (;;) { @@ -877,10 +878,11 @@ _bt_step(IndexScanDesc scan, Buffer *bufP, ScanDirection dir) } page = BufferGetPage(*bufP); opaque = (BTPageOpaque) PageGetSpecialPointer(page); + /* * Okay, we managed to move left to a non-deleted page. - * Done if it's not half-dead and not empty. Else loop back - * and do it all again. + * Done if it's not half-dead and not empty. Else loop + * back and do it all again. */ if (!P_IGNORE(opaque)) { @@ -946,17 +948,18 @@ _bt_walk_left(Relation rel, Buffer buf) buf = _bt_getbuf(rel, blkno, BT_READ); page = BufferGetPage(buf); opaque = (BTPageOpaque) PageGetSpecialPointer(page); + /* - * If this isn't the page we want, walk right till we find - * what we want --- but go no more than four hops (an - * arbitrary limit). If we don't find the correct page by then, - * the most likely bet is that the original page got deleted - * and isn't in the sibling chain at all anymore, not that its - * left sibling got split more than four times. + * If this isn't the page we want, walk right till we find what we + * want --- but go no more than four hops (an arbitrary limit). + * If we don't find the correct page by then, the most likely bet + * is that the original page got deleted and isn't in the sibling + * chain at all anymore, not that its left sibling got split more + * than four times. * - * Note that it is correct to test P_ISDELETED not P_IGNORE - * here, because half-dead pages are still in the sibling - * chain. Caller must reject half-dead pages if wanted. + * Note that it is correct to test P_ISDELETED not P_IGNORE here, + * because half-dead pages are still in the sibling chain. Caller + * must reject half-dead pages if wanted. */ tries = 0; for (;;) @@ -983,8 +986,8 @@ _bt_walk_left(Relation rel, Buffer buf) if (P_ISDELETED(opaque)) { /* - * It was deleted. Move right to first nondeleted page - * (there must be one); that is the page that has acquired the + * It was deleted. Move right to first nondeleted page (there + * must be one); that is the page that has acquired the * deleted one's keyspace, so stepping left from it will take * us where we want to be. */ @@ -1001,18 +1004,18 @@ _bt_walk_left(Relation rel, Buffer buf) if (!P_ISDELETED(opaque)) break; } + /* - * Now return to top of loop, resetting obknum to - * point to this nondeleted page, and try again. + * Now return to top of loop, resetting obknum to point to + * this nondeleted page, and try again. */ } else { /* - * It wasn't deleted; the explanation had better be - * that the page to the left got split or deleted. - * Without this check, we'd go into an infinite loop - * if there's anything wrong. + * It wasn't deleted; the explanation had better be that the + * page to the left got split or deleted. Without this check, + * we'd go into an infinite loop if there's anything wrong. */ if (opaque->btpo_prev == lblkno) elog(ERROR, "could not find left sibling in \"%s\"", @@ -1028,7 +1031,7 @@ _bt_walk_left(Relation rel, Buffer buf) * _bt_get_endpoint() -- Find the first or last page on a given tree level * * If the index is empty, we will return InvalidBuffer; any other failure - * condition causes ereport(). We will not return a dead page. + * condition causes ereport(). We will not return a dead page. * * The returned buffer is pinned and read-locked. */ @@ -1045,8 +1048,8 @@ _bt_get_endpoint(Relation rel, uint32 level, bool rightmost) /* * If we are looking for a leaf page, okay to descend from fast root; - * otherwise better descend from true root. (There is no point in being - * smarter about intermediate levels.) + * otherwise better descend from true root. (There is no point in + * being smarter about intermediate levels.) */ if (level == 0) buf = _bt_getroot(rel, BT_READ); @@ -1066,9 +1069,9 @@ _bt_get_endpoint(Relation rel, uint32 level, bool rightmost) { /* * If we landed on a deleted page, step right to find a live page - * (there must be one). Also, if we want the rightmost page, - * step right if needed to get to it (this could happen if the - * page split since we obtained a pointer to it). + * (there must be one). Also, if we want the rightmost page, step + * right if needed to get to it (this could happen if the page + * split since we obtained a pointer to it). */ while (P_IGNORE(opaque) || (rightmost && !P_RIGHTMOST(opaque))) diff --git a/src/backend/access/nbtree/nbtsort.c b/src/backend/access/nbtree/nbtsort.c index 92a73021f6..f8eb671df7 100644 --- a/src/backend/access/nbtree/nbtsort.c +++ b/src/backend/access/nbtree/nbtsort.c @@ -36,7 +36,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsort.c,v 1.73 2003/07/21 20:29:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsort.c,v 1.74 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -93,7 +93,7 @@ typedef struct BTPageState static void _bt_blnewpage(Relation index, Buffer *buf, Page *page, - uint32 level); + uint32 level); static BTPageState *_bt_pagestate(Relation index, uint32 level); static void _bt_slideleft(Relation index, Buffer buf, Page page); static void _bt_sortaddtup(Page page, Size itemsize, @@ -469,7 +469,7 @@ _bt_buildadd(Relation index, BTPageState *state, BTItem bti) oopaque->btpo_next = BufferGetBlockNumber(nbuf); nopaque->btpo_prev = BufferGetBlockNumber(obuf); - nopaque->btpo_next = P_NONE; /* redundant */ + nopaque->btpo_next = P_NONE; /* redundant */ } /* diff --git a/src/backend/access/nbtree/nbtxlog.c b/src/backend/access/nbtree/nbtxlog.c index a1a52571fe..35e5ae6ccb 100644 --- a/src/backend/access/nbtree/nbtxlog.c +++ b/src/backend/access/nbtree/nbtxlog.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtxlog.c,v 1.3 2003/02/23 22:43:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtxlog.c,v 1.4 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -29,10 +29,10 @@ typedef struct bt_incomplete_split { RelFileNode node; /* the index */ - BlockNumber leftblk; /* left half of split */ - BlockNumber rightblk; /* right half of split */ + BlockNumber leftblk; /* left half of split */ + BlockNumber rightblk; /* right half of split */ bool is_root; /* we split the root */ -} bt_incomplete_split; +} bt_incomplete_split; static List *incomplete_splits; @@ -107,7 +107,7 @@ _bt_restore_page(Page page, char *from, int len) } static void -_bt_restore_meta(Relation reln, XLogRecPtr lsn, +_bt_restore_meta(Relation reln, XLogRecPtr lsn, BlockNumber root, uint32 level, BlockNumber fastroot, uint32 fastlevel) { @@ -172,7 +172,7 @@ btree_xlog_insert(bool redo, bool isleaf, bool ismeta, if (!redo || !(record->xl_info & XLR_BKP_BLOCK_1)) { buffer = XLogReadBuffer(false, reln, - ItemPointerGetBlockNumber(&(xlrec->target.tid))); + ItemPointerGetBlockNumber(&(xlrec->target.tid))); if (!BufferIsValid(buffer)) elog(PANIC, "btree_insert_%sdo: block unfound", (redo) ? "re" : "un"); page = (Page) BufferGetPage(buffer); @@ -183,13 +183,11 @@ btree_xlog_insert(bool redo, bool isleaf, bool ismeta, if (redo) { if (XLByteLE(lsn, PageGetLSN(page))) - { UnlockAndReleaseBuffer(buffer); - } else { if (PageAddItem(page, (Item) datapos, datalen, - ItemPointerGetOffsetNumber(&(xlrec->target.tid)), + ItemPointerGetOffsetNumber(&(xlrec->target.tid)), LP_USED) == InvalidOffsetNumber) elog(PANIC, "btree_insert_redo: failed to add item"); @@ -204,13 +202,9 @@ btree_xlog_insert(bool redo, bool isleaf, bool ismeta, elog(PANIC, "btree_insert_undo: bad page LSN"); if (!P_ISLEAF(pageop)) - { UnlockAndReleaseBuffer(buffer); - } else - { elog(PANIC, "btree_insert_undo: unimplemented"); - } } } @@ -226,8 +220,8 @@ btree_xlog_insert(bool redo, bool isleaf, bool ismeta, if (redo && !isleaf && incomplete_splits != NIL) { forget_matching_split(reln, xlrec->target.node, - ItemPointerGetBlockNumber(&(xlrec->target.tid)), - ItemPointerGetOffsetNumber(&(xlrec->target.tid)), + ItemPointerGetBlockNumber(&(xlrec->target.tid)), + ItemPointerGetOffsetNumber(&(xlrec->target.tid)), false); } } @@ -238,9 +232,9 @@ btree_xlog_split(bool redo, bool onleft, bool isroot, { xl_btree_split *xlrec = (xl_btree_split *) XLogRecGetData(record); Relation reln; - BlockNumber targetblk; - BlockNumber leftsib; - BlockNumber rightsib; + BlockNumber targetblk; + BlockNumber leftsib; + BlockNumber rightsib; Buffer buffer; Page page; BTPageOpaque pageop; @@ -338,9 +332,7 @@ btree_xlog_split(bool redo, bool onleft, bool isroot, elog(PANIC, "btree_split_redo: uninitialized next right page"); if (XLByteLE(lsn, PageGetLSN(page))) - { UnlockAndReleaseBuffer(buffer); - } else { pageop = (BTPageOpaque) PageGetSpecialPointer(page); @@ -357,8 +349,8 @@ btree_xlog_split(bool redo, bool onleft, bool isroot, if (redo && xlrec->level > 0 && incomplete_splits != NIL) { forget_matching_split(reln, xlrec->target.node, - ItemPointerGetBlockNumber(&(xlrec->target.tid)), - ItemPointerGetOffsetNumber(&(xlrec->target.tid)), + ItemPointerGetBlockNumber(&(xlrec->target.tid)), + ItemPointerGetOffsetNumber(&(xlrec->target.tid)), false); } @@ -422,10 +414,10 @@ btree_xlog_delete_page(bool redo, bool ismeta, { xl_btree_delete_page *xlrec = (xl_btree_delete_page *) XLogRecGetData(record); Relation reln; - BlockNumber parent; - BlockNumber target; - BlockNumber leftsib; - BlockNumber rightsib; + BlockNumber parent; + BlockNumber target; + BlockNumber leftsib; + BlockNumber rightsib; Buffer buffer; Page page; BTPageOpaque pageop; @@ -451,9 +443,7 @@ btree_xlog_delete_page(bool redo, bool ismeta, if (PageIsNew((PageHeader) page)) elog(PANIC, "btree_delete_page_redo: uninitialized parent page"); if (XLByteLE(lsn, PageGetLSN(page))) - { UnlockAndReleaseBuffer(buffer); - } else { OffsetNumber poffset; @@ -469,7 +459,7 @@ btree_xlog_delete_page(bool redo, bool ismeta, { ItemId itemid; BTItem btitem; - OffsetNumber nextoffset; + OffsetNumber nextoffset; itemid = PageGetItemId(page, poffset); btitem = (BTItem) PageGetItem(page, itemid); @@ -494,9 +484,7 @@ btree_xlog_delete_page(bool redo, bool ismeta, if (PageIsNew((PageHeader) page)) elog(PANIC, "btree_delete_page_redo: uninitialized right sibling"); if (XLByteLE(lsn, PageGetLSN(page))) - { UnlockAndReleaseBuffer(buffer); - } else { pageop = (BTPageOpaque) PageGetSpecialPointer(page); @@ -520,9 +508,7 @@ btree_xlog_delete_page(bool redo, bool ismeta, if (PageIsNew((PageHeader) page)) elog(PANIC, "btree_delete_page_redo: uninitialized left sibling"); if (XLByteLE(lsn, PageGetLSN(page))) - { UnlockAndReleaseBuffer(buffer); - } else { pageop = (BTPageOpaque) PageGetSpecialPointer(page); @@ -799,116 +785,116 @@ btree_desc(char *buf, uint8 xl_info, char *rec) switch (info) { case XLOG_BTREE_INSERT_LEAF: - { - xl_btree_insert *xlrec = (xl_btree_insert *) rec; + { + xl_btree_insert *xlrec = (xl_btree_insert *) rec; - strcat(buf, "insert: "); - out_target(buf, &(xlrec->target)); - break; - } + strcat(buf, "insert: "); + out_target(buf, &(xlrec->target)); + break; + } case XLOG_BTREE_INSERT_UPPER: - { - xl_btree_insert *xlrec = (xl_btree_insert *) rec; + { + xl_btree_insert *xlrec = (xl_btree_insert *) rec; - strcat(buf, "insert_upper: "); - out_target(buf, &(xlrec->target)); - break; - } + strcat(buf, "insert_upper: "); + out_target(buf, &(xlrec->target)); + break; + } case XLOG_BTREE_INSERT_META: - { - xl_btree_insert *xlrec = (xl_btree_insert *) rec; + { + xl_btree_insert *xlrec = (xl_btree_insert *) rec; - strcat(buf, "insert_meta: "); - out_target(buf, &(xlrec->target)); - break; - } + strcat(buf, "insert_meta: "); + out_target(buf, &(xlrec->target)); + break; + } case XLOG_BTREE_SPLIT_L: - { - xl_btree_split *xlrec = (xl_btree_split *) rec; + { + xl_btree_split *xlrec = (xl_btree_split *) rec; - strcat(buf, "split_l: "); - out_target(buf, &(xlrec->target)); - sprintf(buf + strlen(buf), "; oth %u; rgh %u", - xlrec->otherblk, xlrec->rightblk); - break; - } + strcat(buf, "split_l: "); + out_target(buf, &(xlrec->target)); + sprintf(buf + strlen(buf), "; oth %u; rgh %u", + xlrec->otherblk, xlrec->rightblk); + break; + } case XLOG_BTREE_SPLIT_R: - { - xl_btree_split *xlrec = (xl_btree_split *) rec; + { + xl_btree_split *xlrec = (xl_btree_split *) rec; - strcat(buf, "split_r: "); - out_target(buf, &(xlrec->target)); - sprintf(buf + strlen(buf), "; oth %u; rgh %u", - xlrec->otherblk, xlrec->rightblk); - break; - } + strcat(buf, "split_r: "); + out_target(buf, &(xlrec->target)); + sprintf(buf + strlen(buf), "; oth %u; rgh %u", + xlrec->otherblk, xlrec->rightblk); + break; + } case XLOG_BTREE_SPLIT_L_ROOT: - { - xl_btree_split *xlrec = (xl_btree_split *) rec; + { + xl_btree_split *xlrec = (xl_btree_split *) rec; - strcat(buf, "split_l_root: "); - out_target(buf, &(xlrec->target)); - sprintf(buf + strlen(buf), "; oth %u; rgh %u", - xlrec->otherblk, xlrec->rightblk); - break; - } + strcat(buf, "split_l_root: "); + out_target(buf, &(xlrec->target)); + sprintf(buf + strlen(buf), "; oth %u; rgh %u", + xlrec->otherblk, xlrec->rightblk); + break; + } case XLOG_BTREE_SPLIT_R_ROOT: - { - xl_btree_split *xlrec = (xl_btree_split *) rec; + { + xl_btree_split *xlrec = (xl_btree_split *) rec; - strcat(buf, "split_r_root: "); - out_target(buf, &(xlrec->target)); - sprintf(buf + strlen(buf), "; oth %u; rgh %u", - xlrec->otherblk, xlrec->rightblk); - break; - } + strcat(buf, "split_r_root: "); + out_target(buf, &(xlrec->target)); + sprintf(buf + strlen(buf), "; oth %u; rgh %u", + xlrec->otherblk, xlrec->rightblk); + break; + } case XLOG_BTREE_DELETE: - { - xl_btree_delete *xlrec = (xl_btree_delete *) rec; + { + xl_btree_delete *xlrec = (xl_btree_delete *) rec; - sprintf(buf + strlen(buf), "delete: node %u/%u; blk %u", - xlrec->node.tblNode, xlrec->node.relNode, xlrec->block); - break; - } + sprintf(buf + strlen(buf), "delete: node %u/%u; blk %u", + xlrec->node.tblNode, xlrec->node.relNode, xlrec->block); + break; + } case XLOG_BTREE_DELETE_PAGE: case XLOG_BTREE_DELETE_PAGE_META: - { - xl_btree_delete_page *xlrec = (xl_btree_delete_page *) rec; + { + xl_btree_delete_page *xlrec = (xl_btree_delete_page *) rec; - strcat(buf, "delete_page: "); - out_target(buf, &(xlrec->target)); - sprintf(buf + strlen(buf), "; dead %u; left %u; right %u", - xlrec->deadblk, xlrec->leftblk, xlrec->rightblk); - break; - } + strcat(buf, "delete_page: "); + out_target(buf, &(xlrec->target)); + sprintf(buf + strlen(buf), "; dead %u; left %u; right %u", + xlrec->deadblk, xlrec->leftblk, xlrec->rightblk); + break; + } case XLOG_BTREE_NEWROOT: - { - xl_btree_newroot *xlrec = (xl_btree_newroot *) rec; + { + xl_btree_newroot *xlrec = (xl_btree_newroot *) rec; - sprintf(buf + strlen(buf), "newroot: node %u/%u; root %u lev %u", - xlrec->node.tblNode, xlrec->node.relNode, - xlrec->rootblk, xlrec->level); - break; - } + sprintf(buf + strlen(buf), "newroot: node %u/%u; root %u lev %u", + xlrec->node.tblNode, xlrec->node.relNode, + xlrec->rootblk, xlrec->level); + break; + } case XLOG_BTREE_NEWMETA: - { - xl_btree_newmeta *xlrec = (xl_btree_newmeta *) rec; + { + xl_btree_newmeta *xlrec = (xl_btree_newmeta *) rec; - sprintf(buf + strlen(buf), "newmeta: node %u/%u; root %u lev %u fast %u lev %u", - xlrec->node.tblNode, xlrec->node.relNode, - xlrec->meta.root, xlrec->meta.level, - xlrec->meta.fastroot, xlrec->meta.fastlevel); - break; - } + sprintf(buf + strlen(buf), "newmeta: node %u/%u; root %u lev %u fast %u lev %u", + xlrec->node.tblNode, xlrec->node.relNode, + xlrec->meta.root, xlrec->meta.level, + xlrec->meta.fastroot, xlrec->meta.fastlevel); + break; + } case XLOG_BTREE_NEWPAGE: - { - xl_btree_newpage *xlrec = (xl_btree_newpage *) rec; + { + xl_btree_newpage *xlrec = (xl_btree_newpage *) rec; - sprintf(buf + strlen(buf), "newpage: node %u/%u; page %u", - xlrec->node.tblNode, xlrec->node.relNode, - xlrec->blkno); - break; - } + sprintf(buf + strlen(buf), "newpage: node %u/%u; page %u", + xlrec->node.tblNode, xlrec->node.relNode, + xlrec->blkno); + break; + } default: strcat(buf, "UNKNOWN"); break; diff --git a/src/backend/access/rtree/rtscan.c b/src/backend/access/rtree/rtscan.c index 6358d622e1..4362835d70 100644 --- a/src/backend/access/rtree/rtscan.c +++ b/src/backend/access/rtree/rtscan.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtscan.c,v 1.45 2003/07/28 00:09:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtscan.c,v 1.46 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -109,10 +109,10 @@ rtrescan(PG_FUNCTION_ARGS) s->numberOfKeys * sizeof(ScanKeyData)); /* - * Scans on internal pages use different operators than they - * do on leaf pages. For example, if the user wants all boxes - * that exactly match (x1,y1,x2,y2), then on internal pages we - * need to find all boxes that contain (x1,y1,x2,y2). + * Scans on internal pages use different operators than they do on + * leaf pages. For example, if the user wants all boxes that + * exactly match (x1,y1,x2,y2), then on internal pages we need to + * find all boxes that contain (x1,y1,x2,y2). */ for (i = 0; i < s->numberOfKeys; i++) { diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index 3653d05bc1..6741e5436d 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -13,7 +13,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/access/transam/clog.c,v 1.16 2003/06/11 22:37:45 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/clog.c,v 1.17 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -73,7 +73,7 @@ static SlruCtlData ClogCtlData; static SlruCtl ClogCtl = &ClogCtlData; - + static int ZeroCLOGPage(int pageno, bool writeXlog); static bool CLOGPagePrecedes(int page1, int page2); diff --git a/src/backend/access/transam/rmgr.c b/src/backend/access/transam/rmgr.c index 59af280802..444d2b97d7 100644 --- a/src/backend/access/transam/rmgr.c +++ b/src/backend/access/transam/rmgr.c @@ -3,7 +3,7 @@ * * Resource managers definition * - * $Header: /cvsroot/pgsql/src/backend/access/transam/rmgr.c,v 1.10 2003/02/21 00:06:22 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/rmgr.c,v 1.11 2003/08/04 00:43:15 momjian Exp $ */ #include "postgres.h" @@ -19,7 +19,7 @@ #include "commands/sequence.h" -RmgrData RmgrTable[RM_MAX_ID+1] = { +RmgrData RmgrTable[RM_MAX_ID + 1] = { {"XLOG", xlog_redo, xlog_undo, xlog_desc, NULL, NULL}, {"Transaction", xact_redo, xact_undo, xact_desc, NULL, NULL}, {"Storage", smgr_redo, smgr_undo, smgr_desc, NULL, NULL}, @@ -32,7 +32,7 @@ RmgrData RmgrTable[RM_MAX_ID+1] = { {"Reserved 9", NULL, NULL, NULL, NULL, NULL}, {"Heap", heap_redo, heap_undo, heap_desc, NULL, NULL}, {"Btree", btree_redo, btree_undo, btree_desc, - btree_xlog_startup, btree_xlog_cleanup}, + btree_xlog_startup, btree_xlog_cleanup}, {"Hash", hash_redo, hash_undo, hash_desc, NULL, NULL}, {"Rtree", rtree_redo, rtree_undo, rtree_desc, NULL, NULL}, {"Gist", gist_redo, gist_undo, gist_desc, NULL, NULL}, diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c index 5129dd3c7e..1c290f2cf5 100644 --- a/src/backend/access/transam/slru.c +++ b/src/backend/access/transam/slru.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/access/transam/slru.c,v 1.3 2003/07/28 00:09:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/slru.c,v 1.4 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -93,7 +93,7 @@ typedef enum SLRU_PAGE_CLEAN, /* page is valid and not dirty */ SLRU_PAGE_DIRTY, /* page is valid but needs write */ SLRU_PAGE_WRITE_IN_PROGRESS /* page is being written out */ -} SlruPageStatus; +} SlruPageStatus; /* * Shared-memory state @@ -117,7 +117,7 @@ typedef struct SlruSharedData * swapping out the latest page. */ int latest_page_number; -} SlruSharedData; +} SlruSharedData; typedef SlruSharedData *SlruShared; @@ -145,7 +145,7 @@ typedef enum SLRU_SEEK_FAILED, SLRU_READ_FAILED, SLRU_WRITE_FAILED -} SlruErrorCause; +} SlruErrorCause; static SlruErrorCause slru_errcause; static int slru_errno; @@ -166,9 +166,9 @@ SimpleLruShmemSize(void) { return MAXALIGN(sizeof(SlruSharedData)) + BLCKSZ * NUM_CLOG_BUFFERS #ifdef EXEC_BACKEND - + MAXALIGN(sizeof(SlruLockData)) + + MAXALIGN(sizeof(SlruLockData)) #endif - ; + ; } void @@ -183,12 +183,14 @@ SimpleLruInit(SlruCtl ctl, const char *name, const char *subdir) shared = (SlruShared) ptr; #ifdef EXEC_BACKEND + /* * Locks are in shared memory */ - locks = (SlruLock)(ptr + MAXALIGN(sizeof(SlruSharedData)) + - BLCKSZ * NUM_CLOG_BUFFERS); + locks = (SlruLock) (ptr + MAXALIGN(sizeof(SlruSharedData)) + + BLCKSZ * NUM_CLOG_BUFFERS); #else + /* * Locks are in private memory */ @@ -199,7 +201,7 @@ SimpleLruInit(SlruCtl ctl, const char *name, const char *subdir) if (!IsUnderPostmaster) - /* Initialize locks and shared memory area */ + /* Initialize locks and shared memory area */ { char *bufptr; int slotno; @@ -210,8 +212,8 @@ SimpleLruInit(SlruCtl ctl, const char *name, const char *subdir) memset(shared, 0, sizeof(SlruSharedData)); - bufptr = (char *)shared + MAXALIGN(sizeof(SlruSharedData)); - + bufptr = (char *) shared + MAXALIGN(sizeof(SlruSharedData)); + for (slotno = 0; slotno < NUM_CLOG_BUFFERS; slotno++) { locks->BufferLocks[slotno] = LWLockAssign(); @@ -247,7 +249,7 @@ int SimpleLruZeroPage(SlruCtl ctl, int pageno) { int slotno; - SlruShared shared = (SlruShared) ctl->shared; + SlruShared shared = (SlruShared) ctl->shared; /* Find a suitable buffer slot for the page */ slotno = SlruSelectLRUPage(ctl, pageno); @@ -285,7 +287,7 @@ SimpleLruZeroPage(SlruCtl ctl, int pageno) char * SimpleLruReadPage(SlruCtl ctl, int pageno, TransactionId xid, bool forwrite) { - SlruShared shared = (SlruShared) ctl->shared; + SlruShared shared = (SlruShared) ctl->shared; /* Outer loop handles restart if we lose the buffer to someone else */ for (;;) @@ -383,7 +385,7 @@ SimpleLruWritePage(SlruCtl ctl, int slotno) { int pageno; bool ok; - SlruShared shared = (SlruShared) ctl->shared; + SlruShared shared = (SlruShared) ctl->shared; /* Do nothing if page does not need writing */ if (shared->page_status[slotno] != SLRU_PAGE_DIRTY && @@ -539,13 +541,13 @@ SlruPhysicalWritePage(SlruCtl ctl, int pageno, int slotno) * possible for this to need to happen when writing a page that's not * first in its segment; we assume the OS can cope with that. (Note: * it might seem that it'd be okay to create files only when - * SimpleLruZeroPage is called for the first page of a segment. However, - * if after a crash and restart the REDO logic elects to replay the - * log from a checkpoint before the latest one, then it's possible - * that we will get commands to set transaction status of transactions - * that have already been truncated from the commit log. Easiest way - * to deal with that is to accept references to nonexistent files here - * and in SlruPhysicalReadPage.) + * SimpleLruZeroPage is called for the first page of a segment. + * However, if after a crash and restart the REDO logic elects to + * replay the log from a checkpoint before the latest one, then it's + * possible that we will get commands to set transaction status of + * transactions that have already been truncated from the commit log. + * Easiest way to deal with that is to accept references to + * nonexistent files here and in SlruPhysicalReadPage.) */ fd = BasicOpenFile(path, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR); if (fd < 0) @@ -608,37 +610,37 @@ SlruReportIOError(SlruCtl ctl, int pageno, TransactionId xid) case SLRU_OPEN_FAILED: ereport(ERROR, (errcode_for_file_access(), - errmsg("could not access status of transaction %u", xid), + errmsg("could not access status of transaction %u", xid), errdetail("open of file \"%s\" failed: %m", path))); break; case SLRU_CREATE_FAILED: ereport(ERROR, (errcode_for_file_access(), - errmsg("could not access status of transaction %u", xid), + errmsg("could not access status of transaction %u", xid), errdetail("creation of file \"%s\" failed: %m", path))); break; case SLRU_SEEK_FAILED: ereport(ERROR, (errcode_for_file_access(), - errmsg("could not access status of transaction %u", xid), - errdetail("lseek of file \"%s\", offset %u failed: %m", - path, offset))); + errmsg("could not access status of transaction %u", xid), + errdetail("lseek of file \"%s\", offset %u failed: %m", + path, offset))); break; case SLRU_READ_FAILED: ereport(ERROR, (errcode_for_file_access(), - errmsg("could not access status of transaction %u", xid), - errdetail("read of file \"%s\", offset %u failed: %m", - path, offset))); + errmsg("could not access status of transaction %u", xid), + errdetail("read of file \"%s\", offset %u failed: %m", + path, offset))); break; case SLRU_WRITE_FAILED: ereport(ERROR, (errcode_for_file_access(), - errmsg("could not access status of transaction %u", xid), - errdetail("write of file \"%s\", offset %u failed: %m", - path, offset))); + errmsg("could not access status of transaction %u", xid), + errdetail("write of file \"%s\", offset %u failed: %m", + path, offset))); break; default: /* can't get here, we trust */ @@ -665,6 +667,7 @@ static int SlruSelectLRUPage(SlruCtl ctl, int pageno) { SlruShared shared = (SlruShared) ctl->shared; + /* Outer loop handles restart after I/O */ for (;;) { @@ -689,7 +692,7 @@ SlruSelectLRUPage(SlruCtl ctl, int pageno) if (shared->page_status[slotno] == SLRU_PAGE_EMPTY) return slotno; if (shared->page_lru_count[slotno] > bestcount && - shared->page_number[slotno] != shared->latest_page_number) + shared->page_number[slotno] != shared->latest_page_number) { bestslot = slotno; bestcount = shared->page_lru_count[slotno]; @@ -705,12 +708,12 @@ SlruSelectLRUPage(SlruCtl ctl, int pageno) /* * We need to do I/O. Normal case is that we have to write it * out, but it's possible in the worst case to have selected a - * read-busy page. In that case we use SimpleLruReadPage to wait for - * the read to complete. + * read-busy page. In that case we use SimpleLruReadPage to wait + * for the read to complete. */ if (shared->page_status[bestslot] == SLRU_PAGE_READ_IN_PROGRESS) (void) SimpleLruReadPage(ctl, shared->page_number[bestslot], - InvalidTransactionId, false); + InvalidTransactionId, false); else SimpleLruWritePage(ctl, bestslot); @@ -747,10 +750,11 @@ SimpleLruFlush(SlruCtl ctl, bool checkpoint) for (slotno = 0; slotno < NUM_CLOG_BUFFERS; slotno++) { SimpleLruWritePage(ctl, slotno); + /* - * When called during a checkpoint, - * we cannot assert that the slot is clean now, since another - * process might have re-dirtied it already. That's okay. + * When called during a checkpoint, we cannot assert that the slot + * is clean now, since another process might have re-dirtied it + * already. That's okay. */ Assert(checkpoint || shared->page_status[slotno] == SLRU_PAGE_EMPTY || @@ -792,10 +796,10 @@ SimpleLruTruncate(SlruCtl ctl, int cutoffPage) CreateCheckPoint(false, true); /* - * Scan shared memory and remove any pages preceding the cutoff - * page, to ensure we won't rewrite them later. (Any dirty pages - * should have been flushed already during the checkpoint, we're just - * being extra careful here.) + * Scan shared memory and remove any pages preceding the cutoff page, + * to ensure we won't rewrite them later. (Any dirty pages should + * have been flushed already during the checkpoint, we're just being + * extra careful here.) */ LWLockAcquire(ctl->locks->ControlLock, LW_EXCLUSIVE); @@ -870,7 +874,7 @@ SlruScanDirectory(SlruCtl ctl, int cutoffPage, bool doDeletions) if (cldir == NULL) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not open directory \"%s\": %m", ctl->Dir))); + errmsg("could not open directory \"%s\": %m", ctl->Dir))); errno = 0; while ((clde = readdir(cldir)) != NULL) @@ -898,7 +902,7 @@ SlruScanDirectory(SlruCtl ctl, int cutoffPage, bool doDeletions) if (errno) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not read directory \"%s\": %m", ctl->Dir))); + errmsg("could not read directory \"%s\": %m", ctl->Dir))); closedir(cldir); return found; diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c index 40b41519a9..550f2ae924 100644 --- a/src/backend/access/transam/xact.c +++ b/src/backend/access/transam/xact.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/transam/xact.c,v 1.149 2003/07/21 20:29:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/xact.c,v 1.150 2003/08/04 00:43:15 momjian Exp $ * * NOTES * Transaction aborts can now occur two ways: @@ -92,7 +92,7 @@ * AbortTransactionBlock * * These are invoked only in response to a user "BEGIN WORK", "COMMIT", - * or "ROLLBACK" command. The tricky part about these functions + * or "ROLLBACK" command. The tricky part about these functions * is that they are called within the postgres main loop, in between * the StartTransactionCommand() and CommitTransactionCommand(). * @@ -197,8 +197,8 @@ static TransactionStateData CurrentTransactionStateData = { 0, /* scan command id */ 0x0, /* start time */ TRANS_DEFAULT, /* transaction state */ - TBLOCK_DEFAULT /* transaction block state from - the client perspective */ + TBLOCK_DEFAULT /* transaction block state from the client + * perspective */ }; TransactionState CurrentTransactionState = &CurrentTransactionStateData; @@ -359,7 +359,7 @@ GetCurrentTransactionStartTimeUsec(int *msec) * TransactionIdIsCurrentTransactionId * * During bootstrap, we cheat and say "it's not my transaction ID" even though - * it is. Along with transam.c's cheat to say that the bootstrap XID is + * it is. Along with transam.c's cheat to say that the bootstrap XID is * already committed, this causes the tqual.c routines to see previously * inserted tuples as committed, which is what we need during bootstrap. */ @@ -561,13 +561,13 @@ RecordTransactionCommit(void) /* * We must mark the transaction committed in clog if its XID - * appears either in permanent rels or in local temporary rels. - * We test this by seeing if we made transaction-controlled - * entries *OR* local-rel tuple updates. Note that if we made - * only the latter, we have not emitted an XLOG record for our - * commit, and so in the event of a crash the clog update might be - * lost. This is okay because no one else will ever care whether - * we committed. + * appears either in permanent rels or in local temporary rels. We + * test this by seeing if we made transaction-controlled entries + * *OR* local-rel tuple updates. Note that if we made only the + * latter, we have not emitted an XLOG record for our commit, and + * so in the event of a crash the clog update might be lost. This + * is okay because no one else will ever care whether we + * committed. */ if (MyLastRecPtr.xrecoff != 0 || MyXactMadeTempRelUpdate) TransactionIdCommit(xid); @@ -755,9 +755,9 @@ AtAbort_Memory(void) { /* * Make sure we are in a valid context (not a child of - * TopTransactionContext...). Note that it is possible for this - * code to be called when we aren't in a transaction at all; go - * directly to TopMemoryContext in that case. + * TopTransactionContext...). Note that it is possible for this code + * to be called when we aren't in a transaction at all; go directly to + * TopMemoryContext in that case. */ if (TopTransactionContext != NULL) { @@ -891,8 +891,8 @@ CommitTransaction(void) DeferredTriggerEndXact(); /* - * Similarly, let ON COMMIT management do its thing before we start - * to commit. + * Similarly, let ON COMMIT management do its thing before we start to + * commit. */ PreCommit_on_commit_actions(); @@ -953,10 +953,10 @@ CommitTransaction(void) * noncritical resource releasing. * * The ordering of operations is not entirely random. The idea is: - * release resources visible to other backends (eg, files, buffer pins); - * then release locks; then release backend-local resources. We want - * to release locks at the point where any backend waiting for us will - * see our transaction as being fully cleaned up. + * release resources visible to other backends (eg, files, buffer + * pins); then release locks; then release backend-local resources. + * We want to release locks at the point where any backend waiting for + * us will see our transaction as being fully cleaned up. */ smgrDoPendingDeletes(true); @@ -1064,7 +1064,7 @@ AbortTransaction(void) } /* - * Post-abort cleanup. See notes in CommitTransaction() concerning + * Post-abort cleanup. See notes in CommitTransaction() concerning * ordering. */ @@ -1194,8 +1194,8 @@ StartTransactionCommand(void) } /* - * We must switch to TopTransactionContext before returning. This - * is already done if we called StartTransaction, otherwise not. + * We must switch to TopTransactionContext before returning. This is + * already done if we called StartTransaction, otherwise not. */ Assert(TopTransactionContext != NULL); MemoryContextSwitchTo(TopTransactionContext); @@ -1370,9 +1370,10 @@ PreventTransactionChain(void *stmtNode, const char *stmtType) if (IsTransactionBlock()) ereport(ERROR, (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION), - /* translator: %s represents an SQL statement name */ + /* translator: %s represents an SQL statement name */ errmsg("%s cannot run inside a transaction block", stmtType))); + /* * Are we inside a function call? If the statement's parameter block * was allocated in QueryContext, assume it is an interactive command. @@ -1381,8 +1382,8 @@ PreventTransactionChain(void *stmtNode, const char *stmtType) if (!MemoryContextContains(QueryContext, stmtNode)) ereport(ERROR, (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION), - /* translator: %s represents an SQL statement name */ - errmsg("%s cannot be executed from a function", stmtType))); + /* translator: %s represents an SQL statement name */ + errmsg("%s cannot be executed from a function", stmtType))); /* If we got past IsTransactionBlock test, should be in default state */ if (CurrentTransactionState->blockState != TBLOCK_DEFAULT) elog(ERROR, "cannot prevent transaction chain"); @@ -1414,6 +1415,7 @@ RequireTransactionChain(void *stmtNode, const char *stmtType) */ if (IsTransactionBlock()) return; + /* * Are we inside a function call? If the statement's parameter block * was allocated in QueryContext, assume it is an interactive command. @@ -1423,7 +1425,7 @@ RequireTransactionChain(void *stmtNode, const char *stmtType) return; ereport(ERROR, (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION), - /* translator: %s represents an SQL statement name */ + /* translator: %s represents an SQL statement name */ errmsg("%s may only be used in BEGIN/END transaction blocks", stmtType))); } diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index 0ceb8951cb..45a2743ba9 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/access/transam/xlog.c,v 1.120 2003/07/28 00:09:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/xlog.c,v 1.121 2003/08/04 00:43:15 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -1046,8 +1046,8 @@ XLogWrite(XLogwrtRqst WriteRqst) if (close(openLogFile) != 0) ereport(PANIC, (errcode_for_file_access(), - errmsg("close of log file %u, segment %u failed: %m", - openLogId, openLogSeg))); + errmsg("close of log file %u, segment %u failed: %m", + openLogId, openLogSeg))); openLogFile = -1; } XLByteToPrevSeg(LogwrtResult.Write, openLogId, openLogSeg); @@ -1162,8 +1162,8 @@ XLogWrite(XLogwrtRqst WriteRqst) if (close(openLogFile) != 0) ereport(PANIC, (errcode_for_file_access(), - errmsg("close of log file %u, segment %u failed: %m", - openLogId, openLogSeg))); + errmsg("close of log file %u, segment %u failed: %m", + openLogId, openLogSeg))); openLogFile = -1; } if (openLogFile < 0) @@ -1266,7 +1266,7 @@ XLogFlush(XLogRecPtr record) XLogCtlInsert *Insert = &XLogCtl->Insert; uint32 freespace = INSERT_FREESPACE(Insert); - if (freespace < SizeOfXLogRecord) /* buffer is full */ + if (freespace < SizeOfXLogRecord) /* buffer is full */ WriteRqstPtr = XLogCtl->xlblocks[Insert->curridx]; else { @@ -1449,8 +1449,8 @@ XLogFileInit(uint32 log, uint32 seg, if (fd < 0) ereport(PANIC, (errcode_for_file_access(), - errmsg("open of \"%s\" (log file %u, segment %u) failed: %m", - path, log, seg))); + errmsg("open of \"%s\" (log file %u, segment %u) failed: %m", + path, log, seg))); return (fd); } @@ -1563,14 +1563,14 @@ XLogFileOpen(uint32 log, uint32 seg, bool econt) { ereport(LOG, (errcode_for_file_access(), - errmsg("open of \"%s\" (log file %u, segment %u) failed: %m", - path, log, seg))); + errmsg("open of \"%s\" (log file %u, segment %u) failed: %m", + path, log, seg))); return (fd); } ereport(PANIC, (errcode_for_file_access(), - errmsg("open of \"%s\" (log file %u, segment %u) failed: %m", - path, log, seg))); + errmsg("open of \"%s\" (log file %u, segment %u) failed: %m", + path, log, seg))); } return (fd); @@ -1621,8 +1621,8 @@ MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr) if (xldir == NULL) ereport(PANIC, (errcode_for_file_access(), - errmsg("could not open transaction log directory \"%s\": %m", - XLogDir))); + errmsg("could not open transaction log directory \"%s\": %m", + XLogDir))); sprintf(lastoff, "%08X%08X", log, seg); @@ -1654,15 +1654,15 @@ MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr) true)) { ereport(LOG, - (errmsg("recycled transaction log file \"%s\"", - xlde->d_name))); + (errmsg("recycled transaction log file \"%s\"", + xlde->d_name))); } else { /* No need for any more future segments... */ ereport(LOG, - (errmsg("removing transaction log file \"%s\"", - xlde->d_name))); + (errmsg("removing transaction log file \"%s\"", + xlde->d_name))); unlink(path); } } @@ -1672,8 +1672,8 @@ MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr) if (errno) ereport(PANIC, (errcode_for_file_access(), - errmsg("could not read transaction log directory \"%s\": %m", - XLogDir))); + errmsg("could not read transaction log directory \"%s\": %m", + XLogDir))); closedir(xldir); } @@ -1746,8 +1746,8 @@ RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode) if (!EQ_CRC64(record->xl_crc, crc)) { ereport(emode, - (errmsg("bad resource manager data checksum in record at %X/%X", - recptr.xlogid, recptr.xrecoff))); + (errmsg("bad resource manager data checksum in record at %X/%X", + recptr.xlogid, recptr.xrecoff))); return (false); } @@ -1769,8 +1769,8 @@ RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode) if (!EQ_CRC64(cbuf, crc)) { ereport(emode, - (errmsg("bad checksum of backup block %d in record at %X/%X", - i + 1, recptr.xlogid, recptr.xrecoff))); + (errmsg("bad checksum of backup block %d in record at %X/%X", + i + 1, recptr.xlogid, recptr.xrecoff))); return (false); } blk += sizeof(BkpBlock) + BLCKSZ; @@ -1931,7 +1931,7 @@ got_record:; { ereport(emode, (errmsg("invalid resource manager id %u at %X/%X", - record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff))); + record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff))); goto next_record_is_invalid; } nextRecord = NULL; @@ -2063,7 +2063,7 @@ ValidXLOGHeader(XLogPageHeader hdr, int emode, bool checkSUI) { ereport(emode, (errmsg("unexpected pageaddr %X/%X in log file %u, segment %u, offset %u", - hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff, + hdr->xlp_pageaddr.xlogid, hdr->xlp_pageaddr.xrecoff, readId, readSeg, readOff))); return false; } @@ -2084,7 +2084,7 @@ ValidXLOGHeader(XLogPageHeader hdr, int emode, bool checkSUI) hdr->xlp_sui > lastReadSUI + 512) { ereport(emode, - /* translator: SUI = startup id */ + /* translator: SUI = startup id */ (errmsg("out-of-sequence SUI %u (after %u) in log file %u, segment %u, offset %u", hdr->xlp_sui, lastReadSUI, readId, readSeg, readOff))); @@ -2235,8 +2235,8 @@ ReadControlFile(void) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized with PG_CONTROL_VERSION %d," - " but the server was compiled with PG_CONTROL_VERSION %d.", - ControlFile->pg_control_version, PG_CONTROL_VERSION), + " but the server was compiled with PG_CONTROL_VERSION %d.", + ControlFile->pg_control_version, PG_CONTROL_VERSION), errhint("It looks like you need to initdb."))); /* Now check the CRC. */ INIT_CRC64(crc); @@ -2265,75 +2265,75 @@ ReadControlFile(void) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized with CATALOG_VERSION_NO %d," - " but the server was compiled with CATALOG_VERSION_NO %d.", - ControlFile->catalog_version_no, CATALOG_VERSION_NO), + " but the server was compiled with CATALOG_VERSION_NO %d.", + ControlFile->catalog_version_no, CATALOG_VERSION_NO), errhint("It looks like you need to initdb."))); if (ControlFile->blcksz != BLCKSZ) ereport(FATAL, (errmsg("database files are incompatible with server"), - errdetail("The database cluster was initialized with BLCKSZ %d," - " but the server was compiled with BLCKSZ %d.", - ControlFile->blcksz, BLCKSZ), - errhint("It looks like you need to recompile or initdb."))); + errdetail("The database cluster was initialized with BLCKSZ %d," + " but the server was compiled with BLCKSZ %d.", + ControlFile->blcksz, BLCKSZ), + errhint("It looks like you need to recompile or initdb."))); if (ControlFile->relseg_size != RELSEG_SIZE) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized with RELSEG_SIZE %d," - " but the server was compiled with RELSEG_SIZE %d.", + " but the server was compiled with RELSEG_SIZE %d.", ControlFile->relseg_size, RELSEG_SIZE), - errhint("It looks like you need to recompile or initdb."))); + errhint("It looks like you need to recompile or initdb."))); if (ControlFile->nameDataLen != NAMEDATALEN) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized with NAMEDATALEN %d," - " but the server was compiled with NAMEDATALEN %d.", + " but the server was compiled with NAMEDATALEN %d.", ControlFile->nameDataLen, NAMEDATALEN), - errhint("It looks like you need to recompile or initdb."))); + errhint("It looks like you need to recompile or initdb."))); if (ControlFile->funcMaxArgs != FUNC_MAX_ARGS) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized with FUNC_MAX_ARGS %d," - " but the server was compiled with FUNC_MAX_ARGS %d.", + " but the server was compiled with FUNC_MAX_ARGS %d.", ControlFile->funcMaxArgs, FUNC_MAX_ARGS), - errhint("It looks like you need to recompile or initdb."))); + errhint("It looks like you need to recompile or initdb."))); #ifdef HAVE_INT64_TIMESTAMP if (ControlFile->enableIntTimes != TRUE) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized without HAVE_INT64_TIMESTAMP" - " but the server was compiled with HAVE_INT64_TIMESTAMP."), - errhint("It looks like you need to recompile or initdb."))); + " but the server was compiled with HAVE_INT64_TIMESTAMP."), + errhint("It looks like you need to recompile or initdb."))); #else if (ControlFile->enableIntTimes != FALSE) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized with HAVE_INT64_TIMESTAMP" - " but the server was compiled without HAVE_INT64_TIMESTAMP."), - errhint("It looks like you need to recompile or initdb."))); + " but the server was compiled without HAVE_INT64_TIMESTAMP."), + errhint("It looks like you need to recompile or initdb."))); #endif if (ControlFile->localeBuflen != LOCALE_NAME_BUFLEN) ereport(FATAL, (errmsg("database files are incompatible with server"), errdetail("The database cluster was initialized with LOCALE_NAME_BUFLEN %d," - " but the server was compiled with LOCALE_NAME_BUFLEN %d.", + " but the server was compiled with LOCALE_NAME_BUFLEN %d.", ControlFile->localeBuflen, LOCALE_NAME_BUFLEN), - errhint("It looks like you need to recompile or initdb."))); + errhint("It looks like you need to recompile or initdb."))); if (setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL) ereport(FATAL, - (errmsg("database files are incompatible with operating system"), - errdetail("The database cluster was initialized with LC_COLLATE \"%s\"," - " which is not recognized by setlocale().", - ControlFile->lc_collate), - errhint("It looks like you need to initdb or install locale support."))); + (errmsg("database files are incompatible with operating system"), + errdetail("The database cluster was initialized with LC_COLLATE \"%s\"," + " which is not recognized by setlocale().", + ControlFile->lc_collate), + errhint("It looks like you need to initdb or install locale support."))); if (setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL) ereport(FATAL, - (errmsg("database files are incompatible with operating system"), - errdetail("The database cluster was initialized with LC_CTYPE \"%s\"," - " which is not recognized by setlocale().", - ControlFile->lc_ctype), - errhint("It looks like you need to initdb or install locale support."))); + (errmsg("database files are incompatible with operating system"), + errdetail("The database cluster was initialized with LC_CTYPE \"%s\"," + " which is not recognized by setlocale().", + ControlFile->lc_ctype), + errhint("It looks like you need to initdb or install locale support."))); /* Make the fixed locale settings visible as GUC variables, too */ SetConfigOption("lc_collate", ControlFile->lc_collate, @@ -2602,10 +2602,10 @@ StartupXLOG(void) str_time(ControlFile->time)))); else if (ControlFile->state == DB_IN_RECOVERY) ereport(LOG, - (errmsg("database system was interrupted while in recovery at %s", - str_time(ControlFile->time)), - errhint("This probably means that some data is corrupted and" - " you will have to use the last backup for recovery."))); + (errmsg("database system was interrupted while in recovery at %s", + str_time(ControlFile->time)), + errhint("This probably means that some data is corrupted and" + " you will have to use the last backup for recovery."))); else if (ControlFile->state == DB_IN_PRODUCTION) ereport(LOG, (errmsg("database system was interrupted at %s", @@ -2637,12 +2637,12 @@ StartupXLOG(void) checkPointLoc = ControlFile->prevCheckPoint; ereport(LOG, (errmsg("using previous checkpoint record at %X/%X", - checkPointLoc.xlogid, checkPointLoc.xrecoff))); + checkPointLoc.xlogid, checkPointLoc.xrecoff))); InRecovery = true; /* force recovery even if SHUTDOWNED */ } else ereport(PANIC, - (errmsg("could not locate a valid checkpoint record"))); + (errmsg("could not locate a valid checkpoint record"))); } LastRec = RecPtr = checkPointLoc; memcpy(&checkPoint, XLogRecGetData(record), sizeof(CheckPoint)); @@ -2665,11 +2665,12 @@ StartupXLOG(void) ShmemVariableCache->oidCount = 0; /* - * If it was a shutdown checkpoint, then any following WAL entries were - * created under the next StartUpID; if it was a regular checkpoint then - * any following WAL entries were created under the same StartUpID. - * We must replay WAL entries using the same StartUpID they were created - * under, so temporarily adopt that SUI (see also xlog_redo()). + * If it was a shutdown checkpoint, then any following WAL entries + * were created under the next StartUpID; if it was a regular + * checkpoint then any following WAL entries were created under the + * same StartUpID. We must replay WAL entries using the same StartUpID + * they were created under, so temporarily adopt that SUI (see also + * xlog_redo()). */ if (wasShutdown) ThisStartUpID = checkPoint.ThisStartUpID + 1; @@ -2690,7 +2691,7 @@ StartupXLOG(void) { if (wasShutdown) ereport(PANIC, - (errmsg("invalid redo/undo record in shutdown checkpoint"))); + (errmsg("invalid redo/undo record in shutdown checkpoint"))); InRecovery = true; } else if (ControlFile->state != DB_SHUTDOWNED) @@ -2699,7 +2700,7 @@ StartupXLOG(void) /* REDO */ if (InRecovery) { - int rmid; + int rmid; ereport(LOG, (errmsg("database system was not properly shut down; " @@ -2791,8 +2792,8 @@ StartupXLOG(void) /* * Tricky point here: readBuf contains the *last* block that the - * LastRec record spans, not the one it starts in. The last block - * is indeed the one we want to use. + * LastRec record spans, not the one it starts in. The last block is + * indeed the one we want to use. */ Assert(readOff == (XLogCtl->xlblocks[0].xrecoff - BLCKSZ) % XLogSegSize); memcpy((char *) Insert->currpage, readBuf, BLCKSZ); @@ -2818,11 +2819,12 @@ StartupXLOG(void) else { /* - * Whenever Write.LogwrtResult points to exactly the end of a page, - * Write.curridx must point to the *next* page (see XLogWrite()). + * Whenever Write.LogwrtResult points to exactly the end of a + * page, Write.curridx must point to the *next* page (see + * XLogWrite()). * - * Note: it might seem we should do AdvanceXLInsertBuffer() here, - * but we can't since we haven't yet determined the correct StartUpID + * Note: it might seem we should do AdvanceXLInsertBuffer() here, but + * we can't since we haven't yet determined the correct StartUpID * to put into the new page's header. The first actual attempt to * insert a log record will advance the insert state. */ @@ -2859,7 +2861,7 @@ StartupXLOG(void) if (InRecovery) { - int rmid; + int rmid; /* * Allow resource managers to do any required cleanup. @@ -2885,14 +2887,15 @@ StartupXLOG(void) ThisStartUpID = ControlFile->checkPointCopy.ThisStartUpID; /* - * Perform a new checkpoint to update our recovery activity to disk. + * Perform a new checkpoint to update our recovery activity to + * disk. * * Note that we write a shutdown checkpoint. This is correct since - * the records following it will use SUI one more than what is shown - * in the checkpoint's ThisStartUpID. + * the records following it will use SUI one more than what is + * shown in the checkpoint's ThisStartUpID. * - * In case we had to use the secondary checkpoint, make sure that - * it will still be shown as the secondary checkpoint after this + * In case we had to use the secondary checkpoint, make sure that it + * will still be shown as the secondary checkpoint after this * CreateCheckPoint operation; we don't want the broken primary * checkpoint to become prevCheckPoint... */ @@ -2907,10 +2910,10 @@ StartupXLOG(void) else { /* - * If we are not doing recovery, then we saw a checkpoint with nothing - * after it, and we can safely use StartUpID equal to one more than - * the checkpoint's SUI. But just for paranoia's sake, check against - * pg_control too. + * If we are not doing recovery, then we saw a checkpoint with + * nothing after it, and we can safely use StartUpID equal to one + * more than the checkpoint's SUI. But just for paranoia's sake, + * check against pg_control too. */ ThisStartUpID = checkPoint.ThisStartUpID; if (ThisStartUpID < ControlFile->checkPointCopy.ThisStartUpID) @@ -2923,7 +2926,8 @@ StartupXLOG(void) PreallocXlogFiles(EndOfLog); /* - * Advance StartUpID to one more than the highest value used previously. + * Advance StartUpID to one more than the highest value used + * previously. */ ThisStartUpID++; XLogCtl->ThisStartUpID = ThisStartUpID; @@ -2973,9 +2977,9 @@ ReadCheckpointRecord(XLogRecPtr RecPtr, if (!XRecOffIsValid(RecPtr.xrecoff)) { ereport(LOG, - /* translator: %s is "primary" or "secondary" */ + /* translator: %s is "primary" or "secondary" */ (errmsg("invalid %s checkpoint link in control file", - (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); + (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); return NULL; } @@ -2984,34 +2988,34 @@ ReadCheckpointRecord(XLogRecPtr RecPtr, if (record == NULL) { ereport(LOG, - /* translator: %s is "primary" or "secondary" */ + /* translator: %s is "primary" or "secondary" */ (errmsg("invalid %s checkpoint record", - (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); + (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); return NULL; } if (record->xl_rmid != RM_XLOG_ID) { ereport(LOG, - /* translator: %s is "primary" or "secondary" */ - (errmsg("invalid resource manager id in %s checkpoint record", - (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); + /* translator: %s is "primary" or "secondary" */ + (errmsg("invalid resource manager id in %s checkpoint record", + (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); return NULL; } if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN && record->xl_info != XLOG_CHECKPOINT_ONLINE) { ereport(LOG, - /* translator: %s is "primary" or "secondary" */ + /* translator: %s is "primary" or "secondary" */ (errmsg("invalid xl_info in %s checkpoint record", - (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); + (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); return NULL; } if (record->xl_len != sizeof(CheckPoint)) { ereport(LOG, - /* translator: %s is "primary" or "secondary" */ + /* translator: %s is "primary" or "secondary" */ (errmsg("invalid length of %s checkpoint record", - (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); + (whichChkpt == 1) ? gettext("primary") : gettext("secondary")))); return NULL; } return record; @@ -3112,10 +3116,11 @@ CreateCheckPoint(bool shutdown, bool force) if (MyXactMadeXLogEntry) ereport(ERROR, (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION), - errmsg("checkpoint cannot be made inside transaction block"))); + errmsg("checkpoint cannot be made inside transaction block"))); /* - * Acquire CheckpointLock to ensure only one checkpoint happens at a time. + * Acquire CheckpointLock to ensure only one checkpoint happens at a + * time. * * The CheckpointLock can be held for quite a while, which is not good * because we won't respond to a cancel/die request while waiting for @@ -3149,14 +3154,15 @@ CreateCheckPoint(bool shutdown, bool force) LWLockAcquire(WALInsertLock, LW_EXCLUSIVE); /* - * If this isn't a shutdown or forced checkpoint, and we have not inserted - * any XLOG records since the start of the last checkpoint, skip the - * checkpoint. The idea here is to avoid inserting duplicate checkpoints - * when the system is idle. That wastes log space, and more importantly it - * exposes us to possible loss of both current and previous checkpoint - * records if the machine crashes just as we're writing the update. - * (Perhaps it'd make even more sense to checkpoint only when the previous - * checkpoint record is in a different xlog page?) + * If this isn't a shutdown or forced checkpoint, and we have not + * inserted any XLOG records since the start of the last checkpoint, + * skip the checkpoint. The idea here is to avoid inserting duplicate + * checkpoints when the system is idle. That wastes log space, and + * more importantly it exposes us to possible loss of both current and + * previous checkpoint records if the machine crashes just as we're + * writing the update. (Perhaps it'd make even more sense to + * checkpoint only when the previous checkpoint record is in a + * different xlog page?) * * We have to make two tests to determine that nothing has happened since * the start of the last checkpoint: current insertion point must @@ -3204,12 +3210,13 @@ CreateCheckPoint(bool shutdown, bool force) * Here we update the shared RedoRecPtr for future XLogInsert calls; * this must be done while holding the insert lock AND the info_lck. * - * Note: if we fail to complete the checkpoint, RedoRecPtr will be - * left pointing past where it really needs to point. This is okay; - * the only consequence is that XLogInsert might back up whole buffers - * that it didn't really need to. We can't postpone advancing RedoRecPtr - * because XLogInserts that happen while we are dumping buffers must - * assume that their buffer changes are not included in the checkpoint. + * Note: if we fail to complete the checkpoint, RedoRecPtr will be left + * pointing past where it really needs to point. This is okay; the + * only consequence is that XLogInsert might back up whole buffers + * that it didn't really need to. We can't postpone advancing + * RedoRecPtr because XLogInserts that happen while we are dumping + * buffers must assume that their buffer changes are not included in + * the checkpoint. */ { /* use volatile pointer to prevent code rearrangement */ @@ -3538,15 +3545,15 @@ assign_xlog_sync_method(const char *method, bool doit, bool interactive) if (pg_fsync(openLogFile) != 0) ereport(PANIC, (errcode_for_file_access(), - errmsg("fsync of log file %u, segment %u failed: %m", - openLogId, openLogSeg))); + errmsg("fsync of log file %u, segment %u failed: %m", + openLogId, openLogSeg))); if (open_sync_bit != new_sync_bit) { if (close(openLogFile) != 0) ereport(PANIC, (errcode_for_file_access(), - errmsg("close of log file %u, segment %u failed: %m", - openLogId, openLogSeg))); + errmsg("close of log file %u, segment %u failed: %m", + openLogId, openLogSeg))); openLogFile = -1; } } @@ -3570,16 +3577,16 @@ issue_xlog_fsync(void) if (pg_fsync(openLogFile) != 0) ereport(PANIC, (errcode_for_file_access(), - errmsg("fsync of log file %u, segment %u failed: %m", - openLogId, openLogSeg))); + errmsg("fsync of log file %u, segment %u failed: %m", + openLogId, openLogSeg))); break; #ifdef HAVE_FDATASYNC case SYNC_METHOD_FDATASYNC: if (pg_fdatasync(openLogFile) != 0) ereport(PANIC, (errcode_for_file_access(), - errmsg("fdatasync of log file %u, segment %u failed: %m", - openLogId, openLogSeg))); + errmsg("fdatasync of log file %u, segment %u failed: %m", + openLogId, openLogSeg))); break; #endif case SYNC_METHOD_OPEN: diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c index b02fa775de..328f2ab9b3 100644 --- a/src/backend/bootstrap/bootstrap.c +++ b/src/backend/bootstrap/bootstrap.c @@ -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.163 2003/07/27 21:49:53 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.164 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -238,7 +238,7 @@ BootstrapMain(int argc, char *argv[]) * * If we are running under the postmaster, this is done already. */ - if (!IsUnderPostmaster /* when exec || ExecBackend */) + if (!IsUnderPostmaster /* when exec || ExecBackend */ ) MemoryContextInit(); /* @@ -247,7 +247,7 @@ BootstrapMain(int argc, char *argv[]) /* Set defaults, to be overriden by explicit options below */ dbname = NULL; - if (!IsUnderPostmaster /* when exec || ExecBackend*/) + if (!IsUnderPostmaster /* when exec || ExecBackend */ ) { InitializeGUCOptions(); potential_DataDir = getenv("PGDATA"); /* Null if no PGDATA @@ -285,22 +285,22 @@ BootstrapMain(int argc, char *argv[]) xlogop = atoi(optarg); break; case 'p': - { - /* indicates fork from postmaster */ + { + /* indicates fork from postmaster */ #ifdef EXEC_BACKEND - char *p; + char *p; - sscanf(optarg, "%d,%p,", &UsedShmemSegID, &UsedShmemSegAddr); - p = strchr(optarg, ','); - if (p) - p = strchr(p+1, ','); - if (p) - dbname = strdup(p+1); + sscanf(optarg, "%d,%p,", &UsedShmemSegID, &UsedShmemSegAddr); + p = strchr(optarg, ','); + if (p) + p = strchr(p + 1, ','); + if (p) + dbname = strdup(p + 1); #else - dbname = strdup(optarg); + dbname = strdup(optarg); #endif - break; - } + break; + } case 'B': SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; @@ -346,12 +346,10 @@ BootstrapMain(int argc, char *argv[]) usage(); - if (IsUnderPostmaster && ExecBackend && MyProc /* ordinary backend */) - { + if (IsUnderPostmaster && ExecBackend && MyProc /* ordinary backend */ ) AttachSharedMemoryAndSemaphores(); - } - - if (!IsUnderPostmaster /* when exec || ExecBackend*/) + + if (!IsUnderPostmaster /* when exec || ExecBackend */ ) { if (!potential_DataDir) { @@ -473,8 +471,8 @@ BootstrapMain(int argc, char *argv[]) /* * In NOP mode, all we really want to do is create shared memory and - * semaphores (just to prove we can do it with the current GUC settings). - * So, quit now. + * semaphores (just to prove we can do it with the current GUC + * settings). So, quit now. */ if (xlogop == BS_XLOG_NOP) proc_exit(0); diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c index 77b1d3b2d7..7ace67de6b 100644 --- a/src/backend/catalog/aclchk.c +++ b/src/backend/catalog/aclchk.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/aclchk.c,v 1.85 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/aclchk.c,v 1.86 2003/08/04 00:43:16 momjian Exp $ * * NOTES * See acl.h. @@ -97,37 +97,40 @@ merge_acl_with_grant(Acl *old_acl, bool is_grant, if (grantee->username) { - aclitem.ai_grantee = get_usesysid(grantee->username); + aclitem. ai_grantee = get_usesysid(grantee->username); + idtype = ACL_IDTYPE_UID; } else if (grantee->groupname) { - aclitem.ai_grantee = get_grosysid(grantee->groupname); + aclitem. ai_grantee = get_grosysid(grantee->groupname); + idtype = ACL_IDTYPE_GID; } else { - aclitem.ai_grantee = ACL_ID_WORLD; + aclitem. ai_grantee = ACL_ID_WORLD; + idtype = ACL_IDTYPE_WORLD; } /* * Grant options can only be granted to individual users, not - * groups or public. The reason is that if a user would - * re-grant a privilege that he held through a group having a - * grant option, and later the user is removed from the group, - * the situation is impossible to clean up. + * groups or public. The reason is that if a user would re-grant + * a privilege that he held through a group having a grant option, + * and later the user is removed from the group, the situation is + * impossible to clean up. */ if (is_grant && idtype != ACL_IDTYPE_UID && grant_option) ereport(ERROR, (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("grant options can only be granted to individual users"))); - aclitem.ai_grantor = GetUserId(); + aclitem. ai_grantor = GetUserId(); ACLITEM_SET_PRIVS_IDTYPE(aclitem, - (is_grant || !grant_option) ? privileges : ACL_NO_RIGHTS, - (grant_option || !is_grant) ? privileges : ACL_NO_RIGHTS, + (is_grant || !grant_option) ? privileges : ACL_NO_RIGHTS, + (grant_option || !is_grant) ? privileges : ACL_NO_RIGHTS, idtype); new_acl = aclinsert3(new_acl, &aclitem, modechg, behavior); @@ -247,7 +250,7 @@ ExecuteGrantStmt_Relation(GrantStmt *stmt) new_acl = merge_acl_with_grant(old_acl, stmt->is_grant, stmt->grantees, privileges, - stmt->grant_option, stmt->behavior); + stmt->grant_option, stmt->behavior); /* finished building new ACL value, now insert it */ MemSet(values, 0, sizeof(values)); @@ -346,7 +349,7 @@ ExecuteGrantStmt_Database(GrantStmt *stmt) new_acl = merge_acl_with_grant(old_acl, stmt->is_grant, stmt->grantees, privileges, - stmt->grant_option, stmt->behavior); + stmt->grant_option, stmt->behavior); /* finished building new ACL value, now insert it */ MemSet(values, 0, sizeof(values)); @@ -443,7 +446,7 @@ ExecuteGrantStmt_Function(GrantStmt *stmt) new_acl = merge_acl_with_grant(old_acl, stmt->is_grant, stmt->grantees, privileges, - stmt->grant_option, stmt->behavior); + stmt->grant_option, stmt->behavior); /* finished building new ACL value, now insert it */ MemSet(values, 0, sizeof(values)); @@ -543,7 +546,7 @@ ExecuteGrantStmt_Language(GrantStmt *stmt) new_acl = merge_acl_with_grant(old_acl, stmt->is_grant, stmt->grantees, privileges, - stmt->grant_option, stmt->behavior); + stmt->grant_option, stmt->behavior); /* finished building new ACL value, now insert it */ MemSet(values, 0, sizeof(values)); @@ -619,7 +622,7 @@ ExecuteGrantStmt_Namespace(GrantStmt *stmt) pg_namespace_tuple = (Form_pg_namespace) GETSTRUCT(tuple); if (stmt->is_grant - && !pg_namespace_ownercheck(HeapTupleGetOid(tuple), GetUserId()) + && !pg_namespace_ownercheck(HeapTupleGetOid(tuple), GetUserId()) && pg_namespace_aclcheck(HeapTupleGetOid(tuple), GetUserId(), ACL_GRANT_OPTION_FOR(privileges)) != ACLCHECK_OK) aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_NAMESPACE, nspname); @@ -640,7 +643,7 @@ ExecuteGrantStmt_Namespace(GrantStmt *stmt) new_acl = merge_acl_with_grant(old_acl, stmt->is_grant, stmt->grantees, privileges, - stmt->grant_option, stmt->behavior); + stmt->grant_option, stmt->behavior); /* finished building new ACL value, now insert it */ MemSet(values, 0, sizeof(values)); @@ -805,7 +808,7 @@ in_group(AclId uid, AclId gid) static AclResult aclcheck(Acl *acl, AclId userid, AclMode mode) { - AclItem *aidat; + AclItem *aidat; int i, num; @@ -833,10 +836,10 @@ aclcheck(Acl *acl, AclId userid, AclMode mode) if (aidat[i].ai_privs & mode) return ACLCHECK_OK; } - + /* - * See if he has the permission via any group (do this in a - * separate pass to avoid expensive(?) lookups in pg_group) + * See if he has the permission via any group (do this in a separate + * pass to avoid expensive(?) lookups in pg_group) */ for (i = 0; i < num; i++) if (ACLITEM_GET_IDTYPE(aidat[i]) == ACL_IDTYPE_GID @@ -856,7 +859,7 @@ aclcheck(Acl *acl, AclId userid, AclMode mode) * supply strings that might be already quoted. */ -static const char * const no_priv_msg[MAX_ACL_KIND] = +static const char *const no_priv_msg[MAX_ACL_KIND] = { /* ACL_KIND_CLASS */ gettext_noop("permission denied for relation %s"), @@ -878,7 +881,7 @@ static const char * const no_priv_msg[MAX_ACL_KIND] = gettext_noop("permission denied for conversion %s") }; -static const char * const not_owner_msg[MAX_ACL_KIND] = +static const char *const not_owner_msg[MAX_ACL_KIND] = { /* ACL_KIND_CLASS */ gettext_noop("must be owner of relation %s"), @@ -972,7 +975,7 @@ pg_class_aclcheck(Oid table_oid, AclId userid, AclMode mode) if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), - errmsg("relation with OID %u does not exist", table_oid))); + errmsg("relation with OID %u does not exist", table_oid))); /* * Deny anyone permission to update a system catalog unless @@ -1124,7 +1127,7 @@ pg_proc_aclcheck(Oid proc_oid, AclId userid, AclMode mode) if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("function with OID %u does not exist", proc_oid))); + errmsg("function with OID %u does not exist", proc_oid))); aclDatum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proacl, &isNull); @@ -1179,7 +1182,7 @@ pg_language_aclcheck(Oid lang_oid, AclId userid, AclMode mode) if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("language with OID %u does not exist", lang_oid))); + errmsg("language with OID %u does not exist", lang_oid))); aclDatum = SysCacheGetAttr(LANGOID, tuple, Anum_pg_language_lanacl, &isNull); @@ -1288,7 +1291,7 @@ pg_class_ownercheck(Oid class_oid, AclId userid) if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), - errmsg("relation with OID %u does not exist", class_oid))); + errmsg("relation with OID %u does not exist", class_oid))); owner_id = ((Form_pg_class) GETSTRUCT(tuple))->relowner; @@ -1344,7 +1347,7 @@ pg_oper_ownercheck(Oid oper_oid, AclId userid) if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("operator with OID %u does not exist", oper_oid))); + errmsg("operator with OID %u does not exist", oper_oid))); owner_id = ((Form_pg_operator) GETSTRUCT(tuple))->oprowner; @@ -1372,7 +1375,7 @@ pg_proc_ownercheck(Oid proc_oid, AclId userid) if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("function with OID %u does not exist", proc_oid))); + errmsg("function with OID %u does not exist", proc_oid))); owner_id = ((Form_pg_proc) GETSTRUCT(tuple))->proowner; diff --git a/src/backend/catalog/dependency.c b/src/backend/catalog/dependency.c index 2cdf4bc229..251fb82d81 100644 --- a/src/backend/catalog/dependency.c +++ b/src/backend/catalog/dependency.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/dependency.c,v 1.28 2003/07/28 00:09:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/dependency.c,v 1.29 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -93,8 +93,8 @@ static Oid object_classes[MAX_OCLASS]; static void findAutoDeletableObjects(const ObjectAddress *object, - ObjectAddresses *oktodelete, - Relation depRel); + ObjectAddresses *oktodelete, + Relation depRel); static bool recursiveDeletion(const ObjectAddress *object, DropBehavior behavior, int msglevel, @@ -102,11 +102,11 @@ static bool recursiveDeletion(const ObjectAddress *object, ObjectAddresses *oktodelete, Relation depRel); static bool deleteDependentObjects(const ObjectAddress *object, - const char *objDescription, - DropBehavior behavior, - int msglevel, - ObjectAddresses *oktodelete, - Relation depRel); + const char *objDescription, + DropBehavior behavior, + int msglevel, + ObjectAddresses *oktodelete, + Relation depRel); static void doDeletion(const ObjectAddress *object); static bool find_expr_references_walker(Node *node, find_expr_references_context *context); @@ -118,7 +118,7 @@ static void add_object_address(ObjectClasses oclass, Oid objectId, int32 subId, static void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs); static bool object_address_present(const ObjectAddress *object, - ObjectAddresses *addrs); + ObjectAddresses *addrs); static void term_object_addresses(ObjectAddresses *addrs); static void init_object_classes(void); static ObjectClasses getObjectClass(const ObjectAddress *object); @@ -158,9 +158,9 @@ performDeletion(const ObjectAddress *object, /* * Construct a list of objects that are reachable by AUTO or INTERNAL - * dependencies from the target object. These should be deleted silently, - * even if the actual deletion pass first reaches one of them via a - * non-auto dependency. + * dependencies from the target object. These should be deleted + * silently, even if the actual deletion pass first reaches one of + * them via a non-auto dependency. */ init_object_addresses(&oktodelete); @@ -170,8 +170,8 @@ performDeletion(const ObjectAddress *object, NULL, &oktodelete, depRel)) ereport(ERROR, (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST), - errmsg("cannot drop %s because other objects depend on it", - objDescription), + errmsg("cannot drop %s because other objects depend on it", + objDescription), errhint("Use DROP ... CASCADE to drop the dependent objects too."))); term_object_addresses(&oktodelete); @@ -184,7 +184,7 @@ performDeletion(const ObjectAddress *object, /* * deleteWhatDependsOn: attempt to drop everything that depends on the - * specified object, though not the object itself. Behavior is always + * specified object, though not the object itself. Behavior is always * CASCADE. * * This is currently used only to clean out the contents of a schema @@ -212,9 +212,9 @@ deleteWhatDependsOn(const ObjectAddress *object, /* * Construct a list of objects that are reachable by AUTO or INTERNAL - * dependencies from the target object. These should be deleted silently, - * even if the actual deletion pass first reaches one of them via a - * non-auto dependency. + * dependencies from the target object. These should be deleted + * silently, even if the actual deletion pass first reaches one of + * them via a non-auto dependency. */ init_object_addresses(&oktodelete); @@ -266,9 +266,9 @@ findAutoDeletableObjects(const ObjectAddress *object, ObjectAddress otherObject; /* - * If this object is already in oktodelete, then we already visited it; - * don't do so again (this prevents infinite recursion if there's a loop - * in pg_depend). Otherwise, add it. + * If this object is already in oktodelete, then we already visited + * it; don't do so again (this prevents infinite recursion if there's + * a loop in pg_depend). Otherwise, add it. */ if (object_address_present(object, oktodelete)) return; @@ -276,8 +276,8 @@ findAutoDeletableObjects(const ObjectAddress *object, /* * Scan pg_depend records that link to this object, showing the things - * that depend on it. For each one that is AUTO or INTERNAL, visit the - * referencing object. + * that depend on it. For each one that is AUTO or INTERNAL, visit + * the referencing object. * * When dropping a whole object (subId = 0), find pg_depend records for * its sub-objects too. @@ -319,6 +319,7 @@ findAutoDeletableObjects(const ObjectAddress *object, findAutoDeletableObjects(&otherObject, oktodelete, depRel); break; case DEPENDENCY_PIN: + /* * For a PIN dependency we just ereport immediately; there * won't be any others to examine, and we aren't ever @@ -461,11 +462,11 @@ recursiveDeletion(const ObjectAddress *object, char *otherObjDesc = getObjectDescription(&otherObject); ereport(ERROR, - (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST), - errmsg("cannot drop %s because %s requires it", - objDescription, otherObjDesc), - errhint("You may drop %s instead.", - otherObjDesc))); + (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST), + errmsg("cannot drop %s because %s requires it", + objDescription, otherObjDesc), + errhint("You may drop %s instead.", + otherObjDesc))); } /* @@ -559,10 +560,9 @@ recursiveDeletion(const ObjectAddress *object, /* * Step 2: scan pg_depend records that link to this object, showing * the things that depend on it. Recursively delete those things. - * Note it's important to delete the dependent objects - * before the referenced one, since the deletion routines might do - * things like try to update the pg_class record when deleting a check - * constraint. + * Note it's important to delete the dependent objects before the + * referenced one, since the deletion routines might do things like + * try to update the pg_class record when deleting a check constraint. */ if (!deleteDependentObjects(object, objDescription, behavior, msglevel, @@ -674,11 +674,12 @@ deleteDependentObjects(const ObjectAddress *object, switch (foundDep->deptype) { case DEPENDENCY_NORMAL: + /* * Perhaps there was another dependency path that would - * have allowed silent deletion of the otherObject, had - * we only taken that path first. - * In that case, act like this link is AUTO, too. + * have allowed silent deletion of the otherObject, had we + * only taken that path first. In that case, act like this + * link is AUTO, too. */ if (object_address_present(&otherObject, oktodelete)) ereport(DEBUG2, @@ -872,7 +873,7 @@ recordDependencyOnExpr(const ObjectAddress *depender, * recordDependencyOnSingleRelExpr - find expression dependencies * * As above, but only one relation is expected to be referenced (with - * varno = 1 and varlevelsup = 0). Pass the relation OID instead of a + * varno = 1 and varlevelsup = 0). Pass the relation OID instead of a * range table. An additional frammish is that dependencies on that * relation (or its component columns) will be marked with 'self_behavior', * whereas 'behavior' is used for everything else. @@ -1001,7 +1002,7 @@ find_expr_references_walker(Node *node, else if (rte->rtekind == RTE_JOIN) { /* Scan join output column to add references to join inputs */ - List *save_rtables; + List *save_rtables; /* We must make the context appropriate for join's level */ save_rtables = context->rtables; @@ -1026,7 +1027,7 @@ find_expr_references_walker(Node *node, } if (IsA(node, OpExpr)) { - OpExpr *opexpr = (OpExpr *) node; + OpExpr *opexpr = (OpExpr *) node; add_object_address(OCLASS_OPERATOR, opexpr->opno, 0, &context->addrs); @@ -1034,7 +1035,7 @@ find_expr_references_walker(Node *node, } if (IsA(node, DistinctExpr)) { - DistinctExpr *distinctexpr = (DistinctExpr *) node; + DistinctExpr *distinctexpr = (DistinctExpr *) node; add_object_address(OCLASS_OPERATOR, distinctexpr->opno, 0, &context->addrs); @@ -1042,7 +1043,7 @@ find_expr_references_walker(Node *node, } if (IsA(node, ScalarArrayOpExpr)) { - ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node; + ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node; add_object_address(OCLASS_OPERATOR, opexpr->opno, 0, &context->addrs); @@ -1066,7 +1067,7 @@ find_expr_references_walker(Node *node, } if (IsA(node, SubLink)) { - SubLink *sublink = (SubLink *) node; + SubLink *sublink = (SubLink *) node; List *opid; foreach(opid, sublink->operOids) @@ -1092,7 +1093,8 @@ find_expr_references_walker(Node *node, * Add whole-relation refs for each plain relation mentioned in * the subquery's rtable. (Note: query_tree_walker takes care of * recursing into RTE_FUNCTION and RTE_SUBQUERY RTEs, so no need - * to do that here. But keep it from looking at join alias lists.) + * to do that here. But keep it from looking at join alias + * lists.) */ foreach(rtable, query->rtable) { diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c index 15dbc50a13..c8a411646f 100644 --- a/src/backend/catalog/heap.c +++ b/src/backend/catalog/heap.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.249 2003/07/29 17:21:20 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.250 2003/08/04 00:43:16 momjian Exp $ * * * INTERFACE ROUTINES @@ -418,8 +418,8 @@ CheckAttributeType(const char *attname, Oid atttypid) * Warn user, but don't fail, if column to be created has UNKNOWN type * (usually as a result of a 'retrieve into' - jolly) * - * Refuse any attempt to create a pseudo-type column or one that uses - * a standalone composite type. (Eventually we should probably refuse + * Refuse any attempt to create a pseudo-type column or one that uses a + * standalone composite type. (Eventually we should probably refuse * all references to complex types, but for now there's still some * Berkeley-derived code that thinks it can do this...) */ @@ -439,7 +439,7 @@ CheckAttributeType(const char *attname, Oid atttypid) } else if (att_typtype == 'c') { - Oid typrelid = get_typ_typrelid(atttypid); + Oid typrelid = get_typ_typrelid(atttypid); if (get_rel_relkind(typrelid) == RELKIND_COMPOSITE_TYPE) ereport(ERROR, @@ -975,12 +975,13 @@ RemoveAttributeById(Oid relid, AttrNumber attnum) attStruct->attisdropped = true; /* - * Set the type OID to invalid. A dropped attribute's type link cannot - * be relied on (once the attribute is dropped, the type might be too). - * Fortunately we do not need the type row --- the only really essential - * information is the type's typlen and typalign, which are preserved in - * the attribute's attlen and attalign. We set atttypid to zero here - * as a means of catching code that incorrectly expects it to be valid. + * Set the type OID to invalid. A dropped attribute's type link + * cannot be relied on (once the attribute is dropped, the type might + * be too). Fortunately we do not need the type row --- the only + * really essential information is the type's typlen and typalign, + * which are preserved in the attribute's attlen and attalign. We set + * atttypid to zero here as a means of catching code that incorrectly + * expects it to be valid. */ attStruct->atttypid = InvalidOid; @@ -1401,7 +1402,7 @@ StoreRelCheck(Relation rel, char *ccname, char *ccbin) ' ', ' ', ' ', - InvalidOid, /* no associated index */ + InvalidOid, /* no associated index */ expr, /* Tree form check constraint */ ccbin, /* Binary form check constraint */ ccsrc); /* Source form check constraint */ @@ -1568,8 +1569,8 @@ AddRelationRawConstraints(Relation rel, if (strcmp(cdef2->name, ccname) == 0) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("CHECK constraint \"%s\" already exists", - ccname))); + errmsg("CHECK constraint \"%s\" already exists", + ccname))); } } else @@ -1639,7 +1640,7 @@ AddRelationRawConstraints(Relation rel, if (pstate->p_hasSubLinks) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot use sub-select in CHECK constraint"))); + errmsg("cannot use sub-select in CHECK constraint"))); if (pstate->p_hasAggs) ereport(ERROR, (errcode(ERRCODE_GROUPING_ERROR), @@ -1750,7 +1751,7 @@ cookDefault(ParseState *pstate, if (contain_var_clause(expr)) ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), - errmsg("cannot use column references in DEFAULT clause"))); + errmsg("cannot use column references in DEFAULT clause"))); /* * It can't return a set either. @@ -1773,9 +1774,9 @@ cookDefault(ParseState *pstate, errmsg("cannot use aggregate in DEFAULT clause"))); /* - * Coerce the expression to the correct type and typmod, if given. This - * should match the parser's processing of non-defaulted expressions --- - * see updateTargetListEntry(). + * Coerce the expression to the correct type and typmod, if given. + * This should match the parser's processing of non-defaulted + * expressions --- see updateTargetListEntry(). */ if (OidIsValid(atttypid)) { @@ -1793,7 +1794,7 @@ cookDefault(ParseState *pstate, attname, format_type_be(atttypid), format_type_be(type_id)), - errhint("You will need to rewrite or cast the expression."))); + errhint("You will need to rewrite or cast the expression."))); } return expr; @@ -1952,7 +1953,7 @@ RelationTruncateIndexes(Oid heapId) /* * index_build will close both the heap and index relations (but - * not give up the locks we hold on them). We're done with this + * not give up the locks we hold on them). We're done with this * index, but we must re-open the heap rel. */ heapRelation = heap_open(heapId, NoLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index cb5a78c3da..0b03c630b5 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/index.c,v 1.212 2003/07/21 01:59:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/index.c,v 1.213 2003/08/04 00:43:16 momjian Exp $ * * * INTERFACE ROUTINES @@ -65,8 +65,8 @@ /* non-export function prototypes */ static TupleDesc ConstructTupleDescriptor(Relation heapRelation, - IndexInfo *indexInfo, - Oid *classObjectId); + IndexInfo *indexInfo, + Oid *classObjectId); static void UpdateRelationRelation(Relation indexRelation); static void InitializeAttributeOids(Relation indexRelation, int numatts, Oid indexoid); @@ -124,7 +124,7 @@ ConstructTupleDescriptor(Relation heapRelation, /* * For simple index columns, we copy the pg_attribute row from the - * parent relation and modify it as necessary. For expressions we + * parent relation and modify it as necessary. For expressions we * have to cons up a pg_attribute row the hard way. */ for (i = 0; i < numatts; i++) @@ -149,7 +149,7 @@ ConstructTupleDescriptor(Relation heapRelation, * here we are indexing on a system attribute (-1...-n) */ from = SystemAttributeDefinition(atnum, - heapRelation->rd_rel->relhasoids); + heapRelation->rd_rel->relhasoids); } else { @@ -162,8 +162,8 @@ ConstructTupleDescriptor(Relation heapRelation, } /* - * now that we've determined the "from", let's copy the tuple desc - * data... + * now that we've determined the "from", let's copy the tuple + * desc data... */ memcpy(to, from, ATTRIBUTE_TUPLE_SIZE); @@ -185,7 +185,7 @@ ConstructTupleDescriptor(Relation heapRelation, /* Expressional index */ Node *indexkey; - if (indexprs == NIL) /* shouldn't happen */ + if (indexprs == NIL) /* shouldn't happen */ elog(ERROR, "too few entries in indexprs list"); indexkey = (Node *) lfirst(indexprs); indexprs = lnext(indexprs); @@ -197,7 +197,8 @@ ConstructTupleDescriptor(Relation heapRelation, sprintf(NameStr(to->attname), "pg_expression_%d", i + 1); /* - * Lookup the expression type in pg_type for the type length etc. + * Lookup the expression type in pg_type for the type length + * etc. */ keyType = exprType(indexkey); tuple = SearchSysCache(TYPEOID, @@ -534,7 +535,7 @@ index_create(Oid heapRelationId, if (shared_relation && IsUnderPostmaster) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("shared indexes cannot be created after initdb"))); + errmsg("shared indexes cannot be created after initdb"))); if (get_relname_relid(indexRelationName, namespaceId)) ereport(ERROR, @@ -668,7 +669,7 @@ index_create(Oid heapRelationId, ' ', ' ', ' ', - InvalidOid, /* no associated index */ + InvalidOid, /* no associated index */ NULL, /* no check constraint */ NULL, NULL); @@ -709,7 +710,7 @@ index_create(Oid heapRelationId, if (indexInfo->ii_Expressions) { recordDependencyOnSingleRelExpr(&myself, - (Node *) indexInfo->ii_Expressions, + (Node *) indexInfo->ii_Expressions, heapRelationId, DEPENDENCY_NORMAL, DEPENDENCY_AUTO); @@ -719,7 +720,7 @@ index_create(Oid heapRelationId, if (indexInfo->ii_Predicate) { recordDependencyOnSingleRelExpr(&myself, - (Node *) indexInfo->ii_Predicate, + (Node *) indexInfo->ii_Predicate, heapRelationId, DEPENDENCY_NORMAL, DEPENDENCY_AUTO); @@ -831,8 +832,8 @@ index_drop(Oid indexId) /* * We are presently too lazy to attempt to compute the new correct - * value of relhasindex (the next VACUUM will fix it if necessary). - * So there is no need to update the pg_class tuple for the owning + * value of relhasindex (the next VACUUM will fix it if necessary). So + * there is no need to update the pg_class tuple for the owning * relation. But we must send out a shared-cache-inval notice on the * owning relation to ensure other backends update their relcache * lists of indexes. @@ -958,7 +959,7 @@ FormIndexDatum(IndexInfo *indexInfo, if (indexprs == NIL) elog(ERROR, "wrong number of index expressions"); iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexprs), - GetPerTupleExprContext(estate), + GetPerTupleExprContext(estate), &isNull, NULL); indexprs = lnext(indexprs); @@ -1160,7 +1161,7 @@ setNewRelfilenode(Relation relation) if (!in_place_upd) { tuple = SearchSysCacheCopy(RELOID, - ObjectIdGetDatum(RelationGetRelid(relation)), + ObjectIdGetDatum(RelationGetRelid(relation)), 0, 0, 0); } else @@ -1170,7 +1171,7 @@ setNewRelfilenode(Relation relation) ScanKeyEntryInitialize(&key[0], 0, ObjectIdAttributeNumber, F_OIDEQ, - ObjectIdGetDatum(RelationGetRelid(relation))); + ObjectIdGetDatum(RelationGetRelid(relation))); pg_class_scan = heap_beginscan(pg_class, SnapshotNow, 1, key); tuple = heap_getnext(pg_class_scan, ForwardScanDirection); @@ -1325,9 +1326,9 @@ UpdateStats(Oid relid, double reltuples) } /* - * Update statistics in pg_class, if they changed. (Avoiding an - * unnecessary update is not just a tiny performance improvement; - * it also reduces the window wherein concurrent CREATE INDEX commands + * Update statistics in pg_class, if they changed. (Avoiding an + * unnecessary update is not just a tiny performance improvement; it + * also reduces the window wherein concurrent CREATE INDEX commands * may conflict.) */ rd_rel = (Form_pg_class) GETSTRUCT(tuple); @@ -1338,8 +1339,9 @@ UpdateStats(Oid relid, double reltuples) if (in_place_upd) { /* - * At bootstrap time, we don't need to worry about concurrency or - * visibility of changes, so we cheat. Also cheat if REINDEX. + * At bootstrap time, we don't need to worry about concurrency + * or visibility of changes, so we cheat. Also cheat if + * REINDEX. */ LockBuffer(pg_class_scan->rs_cbuf, BUFFER_LOCK_EXCLUSIVE); rd_rel->relpages = (int32) relpages; @@ -1367,7 +1369,7 @@ UpdateStats(Oid relid, double reltuples) /* * We shouldn't have to do this, but we do... Modify the reldesc in * place with the new values so that the cache contains the latest - * copy. (XXX is this really still necessary? The relcache will get + * copy. (XXX is this really still necessary? The relcache will get * fixed at next CommandCounterIncrement, so why bother here?) */ whichRel->rd_rel->relpages = (int32) relpages; @@ -1454,8 +1456,8 @@ IndexBuildHeapScan(Relation heapRelation, heapDescriptor = RelationGetDescr(heapRelation); /* - * Need an EState for evaluation of index expressions - * and partial-index predicates. + * Need an EState for evaluation of index expressions and + * partial-index predicates. */ estate = CreateExecutorState(); econtext = GetPerTupleExprContext(estate); @@ -1463,7 +1465,8 @@ IndexBuildHeapScan(Relation heapRelation, /* * If this is a predicate (partial) index, we will need to evaluate * the predicate using ExecQual, which requires the current tuple to - * be in a slot of a TupleTable. Likewise if there are any expressions. + * be in a slot of a TupleTable. Likewise if there are any + * expressions. */ if (indexInfo->ii_Predicate != NIL || indexInfo->ii_Expressions != NIL) { @@ -1741,15 +1744,15 @@ reindex_index(Oid indexId, bool force, bool inplace) * it's a nailed-in-cache index, we must do inplace processing because * the relcache can't cope with changing its relfilenode. * - * In either of these cases, we are definitely processing a system - * index, so we'd better be ignoring system indexes. + * In either of these cases, we are definitely processing a system index, + * so we'd better be ignoring system indexes. */ if (iRel->rd_rel->relisshared) { if (!IsIgnoringSystemIndexes()) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("the target relation %u is shared", indexId))); + errmsg("the target relation %u is shared", indexId))); inplace = true; } if (iRel->rd_isnailed) @@ -1757,7 +1760,7 @@ reindex_index(Oid indexId, bool force, bool inplace) if (!IsIgnoringSystemIndexes()) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("the target relation %u is nailed", indexId))); + errmsg("the target relation %u is nailed", indexId))); inplace = true; } diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c index 28b9859677..6a39fc6901 100644 --- a/src/backend/catalog/namespace.c +++ b/src/backend/catalog/namespace.c @@ -13,7 +13,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/namespace.c,v 1.55 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/namespace.c,v 1.56 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -164,7 +164,7 @@ RangeVarGetRelid(const RangeVar *relation, bool failOK) if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cross-database references are not implemented"))); + errmsg("cross-database references are not implemented"))); } if (relation->schemaname) @@ -217,7 +217,7 @@ RangeVarGetCreationNamespace(const RangeVar *newRelation) if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cross-database references are not implemented"))); + errmsg("cross-database references are not implemented"))); } if (newRelation->istemp) @@ -226,7 +226,7 @@ RangeVarGetCreationNamespace(const RangeVar *newRelation) if (newRelation->schemaname) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), - errmsg("TEMP tables may not specify a schema name"))); + errmsg("TEMP tables may not specify a schema name"))); /* Initialize temp namespace if first time through */ if (!OidIsValid(myTempNamespace)) InitTempTableNamespace(); @@ -1057,7 +1057,7 @@ OpclassIsVisible(Oid opcid) Oid ConversionGetConid(const char *conname) { - Oid conid; + Oid conid; List *lptr; recomputeNamespacePath(); @@ -1115,11 +1115,11 @@ ConversionIsVisible(Oid conid) /* * If it is in the path, it might still not be visible; it could * be hidden by another conversion of the same name earlier in the - * path. So we must do a slow check to see if this conversion would - * be found by ConversionGetConid. + * path. So we must do a slow check to see if this conversion + * would be found by ConversionGetConid. */ char *conname = NameStr(conform->conname); - + visible = (ConversionGetConid(conname) == conid); } @@ -1164,13 +1164,13 @@ DeconstructQualifiedName(List *names, if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cross-database references are not implemented"))); + errmsg("cross-database references are not implemented"))); break; default: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("improper qualified name (too many dotted names): %s", - NameListToString(names)))); + errmsg("improper qualified name (too many dotted names): %s", + NameListToString(names)))); break; } @@ -1281,8 +1281,8 @@ makeRangeVarFromNameList(List *names) default: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("improper relation name (too many dotted names): %s", - NameListToString(names)))); + errmsg("improper relation name (too many dotted names): %s", + NameListToString(names)))); break; } @@ -1720,8 +1720,8 @@ RemoveTempRelations(Oid tempNamespaceId) /* * We want to get rid of everything in the target namespace, but not - * the namespace itself (deleting it only to recreate it later would be - * a waste of cycles). We do this by finding everything that has a + * the namespace itself (deleting it only to recreate it later would + * be a waste of cycles). We do this by finding everything that has a * dependency on the namespace. */ object.classId = get_system_catalog_relid(NamespaceRelationName); @@ -1797,7 +1797,7 @@ assign_search_path(const char *newval, bool doit, bool interactive) 0, 0, 0)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_SCHEMA), - errmsg("schema \"%s\" does not exist", curname))); + errmsg("schema \"%s\" does not exist", curname))); } } diff --git a/src/backend/catalog/pg_aggregate.c b/src/backend/catalog/pg_aggregate.c index 6837f3b922..779468ce21 100644 --- a/src/backend/catalog/pg_aggregate.c +++ b/src/backend/catalog/pg_aggregate.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/pg_aggregate.c,v 1.61 2003/07/21 01:59:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_aggregate.c,v 1.62 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -29,8 +29,8 @@ #include "utils/syscache.h" -static Oid lookup_agg_function(List *fnName, int nargs, Oid *input_types, - Oid *rettype); +static Oid lookup_agg_function(List *fnName, int nargs, Oid *input_types, + Oid *rettype); /* @@ -79,7 +79,7 @@ AggregateCreate(const char *aggName, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("cannot determine transition datatype"), errdetail("An aggregate using ANYARRAY or ANYELEMENT as " - "trans type must have one of them as its base type."))); + "trans type must have one of them as its base type."))); /* handle transfn */ MemSet(fnArgs, 0, FUNC_MAX_ARGS * sizeof(Oid)); @@ -99,8 +99,8 @@ AggregateCreate(const char *aggName, * enforce_generic_type_consistency, if transtype isn't polymorphic) * must exactly match declared transtype. * - * In the non-polymorphic-transtype case, it might be okay to allow - * a rettype that's binary-coercible to transtype, but I'm not quite + * In the non-polymorphic-transtype case, it might be okay to allow a + * rettype that's binary-coercible to transtype, but I'm not quite * convinced that it's either safe or useful. When transtype is * polymorphic we *must* demand exact equality. */ @@ -151,9 +151,9 @@ AggregateCreate(const char *aggName, Assert(OidIsValid(finaltype)); /* - * If finaltype (i.e. aggregate return type) is polymorphic, - * basetype must be polymorphic also, else parser will fail to deduce - * result type. (Note: given the previous test on transtype and basetype, + * If finaltype (i.e. aggregate return type) is polymorphic, basetype + * must be polymorphic also, else parser will fail to deduce result + * type. (Note: given the previous test on transtype and basetype, * this cannot happen, unless someone has snuck a finalfn definition * into the catalogs that itself violates the rule against polymorphic * result with no polymorphic input.) @@ -163,8 +163,8 @@ AggregateCreate(const char *aggName, ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("cannot determine result datatype"), - errdetail("An aggregate returning ANYARRAY or ANYELEMENT " - "must have one of them as its base type."))); + errdetail("An aggregate returning ANYARRAY or ANYELEMENT " + "must have one of them as its base type."))); /* * Everything looks okay. Try to create the pg_proc entry for the @@ -278,21 +278,21 @@ lookup_agg_function(List *fnName, ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("function %s does not exist", - func_signature_string(fnName, nargs, input_types)))); + func_signature_string(fnName, nargs, input_types)))); if (retset) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("function %s returns a set", - func_signature_string(fnName, nargs, input_types)))); + func_signature_string(fnName, nargs, input_types)))); /* - * If the given type(s) are all polymorphic, there's nothing we - * can check. Otherwise, enforce consistency, and possibly refine - * the result type. + * If the given type(s) are all polymorphic, there's nothing we can + * check. Otherwise, enforce consistency, and possibly refine the + * result type. */ if ((input_types[0] == ANYARRAYOID || input_types[0] == ANYELEMENTOID) && (nargs == 1 || - (input_types[1] == ANYARRAYOID || input_types[1] == ANYELEMENTOID))) + (input_types[1] == ANYARRAYOID || input_types[1] == ANYELEMENTOID))) { /* nothing to check here */ } @@ -305,8 +305,8 @@ lookup_agg_function(List *fnName, } /* - * func_get_detail will find functions requiring run-time argument type - * coercion, but nodeAgg.c isn't prepared to deal with that + * func_get_detail will find functions requiring run-time argument + * type coercion, but nodeAgg.c isn't prepared to deal with that */ if (true_oid_array[0] != ANYARRAYOID && true_oid_array[0] != ANYELEMENTOID && @@ -314,7 +314,7 @@ lookup_agg_function(List *fnName, ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("function %s requires run-time type coercion", - func_signature_string(fnName, nargs, true_oid_array)))); + func_signature_string(fnName, nargs, true_oid_array)))); if (nargs == 2 && true_oid_array[1] != ANYARRAYOID && @@ -323,7 +323,7 @@ lookup_agg_function(List *fnName, ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("function %s requires run-time type coercion", - func_signature_string(fnName, nargs, true_oid_array)))); + func_signature_string(fnName, nargs, true_oid_array)))); return fnOid; } diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c index 89adeb57b9..ae8b7dec03 100644 --- a/src/backend/catalog/pg_constraint.c +++ b/src/backend/catalog/pg_constraint.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/pg_constraint.c,v 1.14 2003/07/21 01:59:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_constraint.c,v 1.15 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -195,7 +195,7 @@ CreateConstraintEntry(const char *constraintName, /* * Register auto dependency from constraint to owning domain */ - ObjectAddress domobject; + ObjectAddress domobject; domobject.classId = RelOid_pg_type; domobject.objectId = domainId; @@ -234,8 +234,8 @@ CreateConstraintEntry(const char *constraintName, if (OidIsValid(indexRelId)) { /* - * Register normal dependency on the unique index that supports - * a foreign-key constraint. + * Register normal dependency on the unique index that supports a + * foreign-key constraint. */ ObjectAddress relobject; @@ -438,8 +438,8 @@ RemoveConstraintById(Oid conId) Relation rel; /* - * If the constraint is for a relation, open and exclusive-lock the - * relation it's for. + * If the constraint is for a relation, open and exclusive-lock + * the relation it's for. */ rel = heap_open(con->conrelid, AccessExclusiveLock); @@ -463,7 +463,7 @@ RemoveConstraintById(Oid conId) con->conrelid); classForm = (Form_pg_class) GETSTRUCT(relTup); - if (classForm->relchecks == 0) /* should not happen */ + if (classForm->relchecks == 0) /* should not happen */ elog(ERROR, "relation \"%s\" has relchecks = 0", RelationGetRelationName(rel)); classForm->relchecks--; @@ -483,16 +483,15 @@ RemoveConstraintById(Oid conId) else if (OidIsValid(con->contypid)) { /* - * XXX for now, do nothing special when dropping a domain constraint + * XXX for now, do nothing special when dropping a domain + * constraint * * Probably there should be some form of locking on the domain type, * but we have no such concept at the moment. */ } else - { elog(ERROR, "constraint %u is not of a known type", conId); - } /* Fry the constraint itself */ simple_heap_delete(conDesc, &tup->t_self); diff --git a/src/backend/catalog/pg_conversion.c b/src/backend/catalog/pg_conversion.c index 70bd294297..5c10fa7b28 100644 --- a/src/backend/catalog/pg_conversion.c +++ b/src/backend/catalog/pg_conversion.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/pg_conversion.c,v 1.13 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_conversion.c,v 1.14 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -76,9 +76,9 @@ ConversionCreate(const char *conname, Oid connamespace, contoencoding)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("default conversion for %s to %s already exists", - pg_encoding_to_char(conforencoding), - pg_encoding_to_char(contoencoding)))); + errmsg("default conversion for %s to %s already exists", + pg_encoding_to_char(conforencoding), + pg_encoding_to_char(contoencoding)))); } /* open pg_conversion */ @@ -147,7 +147,7 @@ ConversionDrop(Oid conversionOid, DropBehavior behavior) if (!superuser() && ((Form_pg_conversion) GETSTRUCT(tuple))->conowner != GetUserId()) aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CONVERSION, - NameStr(((Form_pg_conversion) GETSTRUCT(tuple))->conname)); + NameStr(((Form_pg_conversion) GETSTRUCT(tuple))->conname)); ReleaseSysCache(tuple); diff --git a/src/backend/catalog/pg_operator.c b/src/backend/catalog/pg_operator.c index da3e2a4692..141d3a142a 100644 --- a/src/backend/catalog/pg_operator.c +++ b/src/backend/catalog/pg_operator.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/pg_operator.c,v 1.81 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_operator.c,v 1.82 2003/08/04 00:43:16 momjian Exp $ * * NOTES * these routines moved here from commands/define.c and somewhat cleaned up. @@ -409,7 +409,7 @@ OperatorCreate(const char *operatorName, if (!OidIsValid(leftTypeId) && !OidIsValid(rightTypeId)) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("at least one of leftarg or rightarg must be specified"))); + errmsg("at least one of leftarg or rightarg must be specified"))); if (!(OidIsValid(leftTypeId) && OidIsValid(rightTypeId))) { @@ -417,11 +417,11 @@ OperatorCreate(const char *operatorName, if (commutatorName) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("only binary operators can have commutators"))); + errmsg("only binary operators can have commutators"))); if (joinName) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("only binary operators can have join selectivity"))); + errmsg("only binary operators can have join selectivity"))); if (canHash) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), diff --git a/src/backend/catalog/pg_proc.c b/src/backend/catalog/pg_proc.c index d8ff4a5225..2c11a17db5 100644 --- a/src/backend/catalog/pg_proc.c +++ b/src/backend/catalog/pg_proc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/pg_proc.c,v 1.102 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_proc.c,v 1.103 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -94,7 +94,7 @@ ProcedureCreate(const char *procedureName, */ if (returnType == ANYARRAYOID || returnType == ANYELEMENTOID) { - bool genericParam = false; + bool genericParam = false; for (i = 0; i < parameterCount; i++) { @@ -231,7 +231,7 @@ ProcedureCreate(const char *procedureName, returnsSet != oldproc->proretset) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("cannot change return type of existing function"), + errmsg("cannot change return type of existing function"), errhint("Use DROP FUNCTION first."))); /* Can't change aggregate status, either */ @@ -339,8 +339,8 @@ ProcedureCreate(const char *procedureName, * * This is normally applied during function definition, but in the case * of a function with polymorphic arguments, we instead apply it during - * function execution startup. The rettype is then the actual resolved - * output type of the function, rather than the declared type. (Therefore, + * function execution startup. The rettype is then the actual resolved + * output type of the function, rather than the declared type. (Therefore, * we should never see ANYARRAY or ANYELEMENT as rettype.) */ void @@ -366,7 +366,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList) (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("return type mismatch in function declared to return %s", format_type_be(rettype)), - errdetail("Function's final statement must be a SELECT."))); + errdetail("Function's final statement must be a SELECT."))); return; } @@ -395,9 +395,9 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList) if (cmd != CMD_SELECT) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("return type mismatch in function declared to return %s", - format_type_be(rettype)), - errdetail("Function's final statement must be a SELECT."))); + errmsg("return type mismatch in function declared to return %s", + format_type_be(rettype)), + errdetail("Function's final statement must be a SELECT."))); /* * Count the non-junk entries in the result targetlist. @@ -421,7 +421,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList) (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("return type mismatch in function declared to return %s", format_type_be(rettype)), - errdetail("Final SELECT must return exactly one column."))); + errdetail("Final SELECT must return exactly one column."))); restype = ((TargetEntry *) lfirst(tlist))->resdom->restype; if (!IsBinaryCoercible(restype, rettype)) @@ -481,7 +481,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList) (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("return type mismatch in function declared to return %s", format_type_be(rettype)), - errdetail("Final SELECT returns too many columns."))); + errdetail("Final SELECT returns too many columns."))); attr = reln->rd_att->attrs[colindex - 1]; } while (attr->attisdropped); rellogcols++; @@ -538,8 +538,8 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList) else ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("return type %s is not supported for SQL functions", - format_type_be(rettype)))); + errmsg("return type %s is not supported for SQL functions", + format_type_be(rettype)))); } @@ -684,8 +684,8 @@ fmgr_sql_validator(PG_FUNCTION_ARGS) else ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("SQL functions cannot have arguments of type %s", - format_type_be(proc->proargtypes[i])))); + errmsg("SQL functions cannot have arguments of type %s", + format_type_be(proc->proargtypes[i])))); } } @@ -696,13 +696,13 @@ fmgr_sql_validator(PG_FUNCTION_ARGS) prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp)); /* - * We can't do full prechecking of the function definition if there are - * any polymorphic input types, because actual datatypes of expression - * results will be unresolvable. The check will be done at runtime - * instead. + * We can't do full prechecking of the function definition if there + * are any polymorphic input types, because actual datatypes of + * expression results will be unresolvable. The check will be done at + * runtime instead. * - * We can run the text through the raw parser though; this will at - * least catch silly syntactic errors. + * We can run the text through the raw parser though; this will at least + * catch silly syntactic errors. */ if (!haspolyarg) { @@ -712,9 +712,7 @@ fmgr_sql_validator(PG_FUNCTION_ARGS) check_sql_fn_retval(proc->prorettype, functyptype, querytree_list); } else - { querytree_list = pg_parse_query(prosrc); - } ReleaseSysCache(tuple); diff --git a/src/backend/catalog/pg_type.c b/src/backend/catalog/pg_type.c index 7980e6afad..d578644e68 100644 --- a/src/backend/catalog/pg_type.c +++ b/src/backend/catalog/pg_type.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/catalog/pg_type.c,v 1.88 2003/07/21 01:59:11 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_type.c,v 1.89 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -359,7 +359,8 @@ TypeCreate(const char *typeName, void GenerateTypeDependencies(Oid typeNamespace, Oid typeObjectId, - Oid relationOid, /* only for 'c'atalog types */ + Oid relationOid, /* only for 'c'atalog + * types */ char relationKind, /* ditto */ Oid inputProcedure, Oid outputProcedure, @@ -426,13 +427,13 @@ GenerateTypeDependencies(Oid typeNamespace, /* * If the type is a rowtype for a relation, mark it as internally - * dependent on the relation, *unless* it is a stand-alone - * composite type relation. For the latter case, we have to - * reverse the dependency. + * dependent on the relation, *unless* it is a stand-alone composite + * type relation. For the latter case, we have to reverse the + * dependency. * - * In the former case, this allows the type to be auto-dropped when - * the relation is, and not otherwise. And in the latter, of - * course we get the opposite effect. + * In the former case, this allows the type to be auto-dropped when the + * relation is, and not otherwise. And in the latter, of course we get + * the opposite effect. */ if (OidIsValid(relationOid)) { @@ -447,11 +448,11 @@ GenerateTypeDependencies(Oid typeNamespace, } /* - * If the type is an array type, mark it auto-dependent on the - * base type. (This is a compromise between the typical case - * where the array type is automatically generated and the case - * where it is manually created: we'd prefer INTERNAL for the - * former case and NORMAL for the latter.) + * If the type is an array type, mark it auto-dependent on the base + * type. (This is a compromise between the typical case where the + * array type is automatically generated and the case where it is + * manually created: we'd prefer INTERNAL for the former case and + * NORMAL for the latter.) */ if (OidIsValid(elementType)) { diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c index 1d9b25b5b0..5a57d5c5c7 100644 --- a/src/backend/commands/aggregatecmds.c +++ b/src/backend/commands/aggregatecmds.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/aggregatecmds.c,v 1.12 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/aggregatecmds.c,v 1.13 2003/08/04 00:43:16 momjian Exp $ * * DESCRIPTION * The "DefineFoo" routines take the parse tree and pick out the @@ -256,16 +256,16 @@ RenameAggregate(List *name, TypeName *basetype, const char *newname) if (basetypeOid == ANYOID) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_FUNCTION), - errmsg("function %s(*) already exists in schema \"%s\"", - newname, - get_namespace_name(namespaceOid)))); + errmsg("function %s(*) already exists in schema \"%s\"", + newname, + get_namespace_name(namespaceOid)))); else ereport(ERROR, (errcode(ERRCODE_DUPLICATE_FUNCTION), errmsg("function %s already exists in schema \"%s\"", funcname_signature_string(newname, procForm->pronargs, - procForm->proargtypes), + procForm->proargtypes), get_namespace_name(namespaceOid)))); } diff --git a/src/backend/commands/alter.c b/src/backend/commands/alter.c index b377635099..4fd43871e9 100644 --- a/src/backend/commands/alter.c +++ b/src/backend/commands/alter.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/alter.c,v 1.4 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/alter.c,v 1.5 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -79,52 +79,52 @@ ExecRenameStmt(RenameStmt *stmt) case OBJECT_TABLE: case OBJECT_COLUMN: case OBJECT_TRIGGER: - { - Oid relid; - - CheckRelationOwnership(stmt->relation, true); - - relid = RangeVarGetRelid(stmt->relation, false); - - switch (stmt->renameType) { - case OBJECT_TABLE: + Oid relid; + + CheckRelationOwnership(stmt->relation, true); + + relid = RangeVarGetRelid(stmt->relation, false); + + switch (stmt->renameType) { - /* - * RENAME TABLE requires that we (still) hold - * CREATE rights on the containing namespace, as - * well as ownership of the table. - */ - Oid namespaceId = get_rel_namespace(relid); - AclResult aclresult; + case OBJECT_TABLE: + { + /* + * RENAME TABLE requires that we (still) hold + * CREATE rights on the containing namespace, + * as well as ownership of the table. + */ + Oid namespaceId = get_rel_namespace(relid); + AclResult aclresult; - aclresult = pg_namespace_aclcheck(namespaceId, - GetUserId(), - ACL_CREATE); - if (aclresult != ACLCHECK_OK) - aclcheck_error(aclresult, ACL_KIND_NAMESPACE, - get_namespace_name(namespaceId)); + aclresult = pg_namespace_aclcheck(namespaceId, + GetUserId(), + ACL_CREATE); + if (aclresult != ACLCHECK_OK) + aclcheck_error(aclresult, ACL_KIND_NAMESPACE, + get_namespace_name(namespaceId)); - renamerel(relid, stmt->newname); - break; - } - case OBJECT_COLUMN: - renameatt(relid, - stmt->subname, /* old att name */ - stmt->newname, /* new att name */ + renamerel(relid, stmt->newname); + break; + } + case OBJECT_COLUMN: + renameatt(relid, + stmt->subname, /* old att name */ + stmt->newname, /* new att name */ interpretInhOption(stmt->relation->inhOpt), /* recursive? */ - false); /* recursing already? */ - break; - case OBJECT_TRIGGER: - renametrig(relid, - stmt->subname, /* old att name */ - stmt->newname); /* new att name */ - break; - default: - /*can't happen*/; + false); /* recursing already? */ + break; + case OBJECT_TRIGGER: + renametrig(relid, + stmt->subname, /* old att name */ + stmt->newname); /* new att name */ + break; + default: + /* can't happen */ ; + } + break; } - break; - } default: elog(ERROR, "unrecognized rename stmt type: %d", diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index 5277884f1f..dac2d5d7bb 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/analyze.c,v 1.56 2003/07/20 21:56:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/analyze.c,v 1.57 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -220,9 +220,9 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) /* * Silently ignore tables that are temp tables of other backends --- - * trying to analyze these is rather pointless, since their - * contents are probably not up-to-date on disk. (We don't throw a - * warning here; it would just lead to chatter during a database-wide + * trying to analyze these is rather pointless, since their contents + * are probably not up-to-date on disk. (We don't throw a warning + * here; it would just lead to chatter during a database-wide * ANALYZE.) */ if (isOtherTempNamespace(RelationGetNamespace(onerel))) diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c index dafea7c869..69085740cc 100644 --- a/src/backend/commands/async.c +++ b/src/backend/commands/async.c @@ -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.96 2003/07/20 21:56:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.97 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -603,10 +603,10 @@ Async_NotifyHandler(SIGNAL_ARGS) bool save_ImmediateInterruptOK = ImmediateInterruptOK; /* - * We may be called while ImmediateInterruptOK is true; turn it off - * while messing with the NOTIFY state. (We would have to save - * and restore it anyway, because PGSemaphore operations inside - * ProcessIncomingNotify() might reset it.) + * We may be called while ImmediateInterruptOK is true; turn it + * off while messing with the NOTIFY state. (We would have to + * save and restore it anyway, because PGSemaphore operations + * inside ProcessIncomingNotify() might reset it.) */ ImmediateInterruptOK = false; @@ -639,7 +639,8 @@ Async_NotifyHandler(SIGNAL_ARGS) } /* - * Restore ImmediateInterruptOK, and check for interrupts if needed. + * Restore ImmediateInterruptOK, and check for interrupts if + * needed. */ ImmediateInterruptOK = save_ImmediateInterruptOK; if (save_ImmediateInterruptOK) diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c index 18f6bfcf6b..23e03443fc 100644 --- a/src/backend/commands/cluster.c +++ b/src/backend/commands/cluster.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.112 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.113 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -58,12 +58,12 @@ typedef struct */ typedef struct { - Oid tableOid; - Oid indexOid; -} RelToCluster; + Oid tableOid; + Oid indexOid; +} RelToCluster; -static void cluster_rel(RelToCluster *rv, bool recheck); +static void cluster_rel(RelToCluster * rv, bool recheck); static Oid make_new_heap(Oid OIDOldHeap, const char *NewName); static void copy_heap_data(Oid OIDNewHeap, Oid OIDOldHeap, Oid OIDOldIndex); static List *get_indexattr_list(Relation OldHeap, Oid OldIndex); @@ -74,7 +74,7 @@ static List *get_tables_to_cluster(MemoryContext cluster_context); /*--------------------------------------------------------------------------- - * This cluster code allows for clustering multiple tables at once. Because + * This cluster code allows for clustering multiple tables at once. Because * of this, we cannot just run everything on a single transaction, or we * would be forced to acquire exclusive locks on all the tables being * clustered, simultaneously --- very likely leading to deadlock. @@ -82,17 +82,17 @@ static List *get_tables_to_cluster(MemoryContext cluster_context); * To solve this we follow a similar strategy to VACUUM code, * clustering each relation in a separate transaction. For this to work, * we need to: - * - provide a separate memory context so that we can pass information in - * a way that survives across transactions - * - start a new transaction every time a new relation is clustered - * - check for validity of the information on to-be-clustered relations, - * as someone might have deleted a relation behind our back, or - * clustered one on a different index - * - end the transaction + * - provide a separate memory context so that we can pass information in + * a way that survives across transactions + * - start a new transaction every time a new relation is clustered + * - check for validity of the information on to-be-clustered relations, + * as someone might have deleted a relation behind our back, or + * clustered one on a different index + * - end the transaction * * The single-relation case does not have any such overhead. * - * We also allow a relation being specified without index. In that case, + * We also allow a relation being specified without index. In that case, * the indisclustered bit will be looked up, and an ERROR will be thrown * if there is no index with the bit set. *--------------------------------------------------------------------------- @@ -103,10 +103,10 @@ cluster(ClusterStmt *stmt) if (stmt->relation != NULL) { /* This is the single-relation case. */ - Oid tableOid, - indexOid = InvalidOid; - Relation rel; - RelToCluster rvtc; + Oid tableOid, + indexOid = InvalidOid; + Relation rel; + RelToCluster rvtc; /* Find and lock the table */ rel = heap_openrv(stmt->relation, AccessExclusiveLock); @@ -123,10 +123,10 @@ cluster(ClusterStmt *stmt) List *index; /* We need to find the index that has indisclustered set. */ - foreach (index, RelationGetIndexList(rel)) + foreach(index, RelationGetIndexList(rel)) { - HeapTuple idxtuple; - Form_pg_index indexForm; + HeapTuple idxtuple; + Form_pg_index indexForm; indexOid = lfirsto(index); idxtuple = SearchSysCache(INDEXRELID, @@ -152,14 +152,17 @@ cluster(ClusterStmt *stmt) } else { - /* The index is expected to be in the same namespace as the relation. */ + /* + * The index is expected to be in the same namespace as the + * relation. + */ indexOid = get_relname_relid(stmt->indexname, rel->rd_rel->relnamespace); if (!OidIsValid(indexOid)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("index \"%s\" for table \"%s\" does not exist", - stmt->indexname, stmt->relation->relname))); + errmsg("index \"%s\" for table \"%s\" does not exist", + stmt->indexname, stmt->relation->relname))); } /* All other checks are done in cluster_rel() */ @@ -175,16 +178,16 @@ cluster(ClusterStmt *stmt) else { /* - * This is the "multi relation" case. We need to cluster all tables - * that have some index with indisclustered set. + * This is the "multi relation" case. We need to cluster all + * tables that have some index with indisclustered set. */ - MemoryContext cluster_context; - List *rv, - *rvs; + MemoryContext cluster_context; + List *rv, + *rvs; /* - * We cannot run this form of CLUSTER inside a user transaction block; - * we'd be holding locks way too long. + * We cannot run this form of CLUSTER inside a user transaction + * block; we'd be holding locks way too long. */ PreventTransactionChain((void *) stmt, "CLUSTER"); @@ -201,8 +204,8 @@ cluster(ClusterStmt *stmt) ALLOCSET_DEFAULT_MAXSIZE); /* - * Build the list of relations to cluster. Note that this lives in - * cluster_context. + * Build the list of relations to cluster. Note that this lives + * in cluster_context. */ rvs = get_tables_to_cluster(cluster_context); @@ -210,13 +213,14 @@ cluster(ClusterStmt *stmt) CommitTransactionCommand(); /* Ok, now that we've got them all, cluster them one by one */ - foreach (rv, rvs) + foreach(rv, rvs) { - RelToCluster *rvtc = (RelToCluster *) lfirst(rv); + RelToCluster *rvtc = (RelToCluster *) lfirst(rv); /* Start a new transaction for each relation. */ StartTransactionCommand(); - SetQuerySnapshot(); /* might be needed for functions in indexes */ + SetQuerySnapshot(); /* might be needed for functions in + * indexes */ cluster_rel(rvtc, true); CommitTransactionCommand(); } @@ -244,7 +248,7 @@ cluster(ClusterStmt *stmt) * them incrementally while we load the table. */ static void -cluster_rel(RelToCluster *rvtc, bool recheck) +cluster_rel(RelToCluster * rvtc, bool recheck) { Relation OldHeap, OldIndex; @@ -256,14 +260,14 @@ cluster_rel(RelToCluster *rvtc, bool recheck) * Since we may open a new transaction for each relation, we have to * check that the relation still is what we think it is. * - * If this is a single-transaction CLUSTER, we can skip these tests. - * We *must* skip the one on indisclustered since it would reject an + * If this is a single-transaction CLUSTER, we can skip these tests. We + * *must* skip the one on indisclustered since it would reject an * attempt to cluster a not-previously-clustered index. */ if (recheck) { - HeapTuple tuple; - Form_pg_index indexForm; + HeapTuple tuple; + Form_pg_index indexForm; /* * Check if the relation and index still exist before opening them @@ -319,10 +323,10 @@ cluster_rel(RelToCluster *rvtc, bool recheck) RelationGetRelationName(OldHeap)))); /* - * Disallow clustering on incomplete indexes (those that might not index - * every row of the relation). We could relax this by making a separate - * seqscan pass over the table to copy the missing rows, but that seems - * expensive and tedious. + * Disallow clustering on incomplete indexes (those that might not + * index every row of the relation). We could relax this by making a + * separate seqscan pass over the table to copy the missing rows, but + * that seems expensive and tedious. */ if (!heap_attisnull(OldIndex->rd_indextuple, Anum_pg_index_indpred)) ereport(ERROR, @@ -334,7 +338,7 @@ cluster_rel(RelToCluster *rvtc, bool recheck) /* * If the AM doesn't index nulls, then it's a partial index unless - * we can prove all the rows are non-null. Note we only need look + * we can prove all the rows are non-null. Note we only need look * at the first column; multicolumn-capable AMs are *required* to * index nulls in columns after the first. */ @@ -347,7 +351,7 @@ cluster_rel(RelToCluster *rvtc, bool recheck) (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot cluster when index access method does not handle nulls"), errhint("You may be able to work around this by marking column \"%s\" NOT NULL.", - NameStr(OldHeap->rd_att->attrs[colno - 1]->attname)))); + NameStr(OldHeap->rd_att->attrs[colno - 1]->attname)))); } else if (colno < 0) { @@ -382,7 +386,7 @@ cluster_rel(RelToCluster *rvtc, bool recheck) if (isOtherTempNamespace(RelationGetNamespace(OldHeap))) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot cluster temp tables of other processes"))); + errmsg("cannot cluster temp tables of other processes"))); /* Drop relcache refcnt on OldIndex, but keep lock */ index_close(OldIndex); @@ -397,7 +401,7 @@ cluster_rel(RelToCluster *rvtc, bool recheck) * rebuild_relation: rebuild an existing relation * * This is shared code between CLUSTER and TRUNCATE. In the TRUNCATE - * case, the new relation is built and left empty. In the CLUSTER case, + * case, the new relation is built and left empty. In the CLUSTER case, * it is filled with data read from the old relation in the order specified * by the index. * @@ -432,6 +436,7 @@ rebuild_relation(Relation OldHeap, Oid indexOid) snprintf(NewHeapName, sizeof(NewHeapName), "pg_temp_%u", tableOid); OIDNewHeap = make_new_heap(tableOid, NewHeapName); + /* * We don't need CommandCounterIncrement() because make_new_heap did * it. @@ -754,8 +759,8 @@ swap_relfilenodes(Oid r1, Oid r2) /* swap size statistics too, since new rel has freshly-updated stats */ { - int4 swap_pages; - float4 swap_tuples; + int4 swap_pages; + float4 swap_tuples; swap_pages = relform1->relpages; relform1->relpages = relform2->relpages; @@ -857,20 +862,20 @@ swap_relfilenodes(Oid r1, Oid r2) static List * get_tables_to_cluster(MemoryContext cluster_context) { - Relation indRelation; - HeapScanDesc scan; - ScanKeyData entry; - HeapTuple indexTuple; - Form_pg_index index; - MemoryContext old_context; - RelToCluster *rvtc; - List *rvs = NIL; + Relation indRelation; + HeapScanDesc scan; + ScanKeyData entry; + HeapTuple indexTuple; + Form_pg_index index; + MemoryContext old_context; + RelToCluster *rvtc; + List *rvs = NIL; /* * Get all indexes that have indisclustered set and are owned by - * appropriate user. System relations or nailed-in relations cannot ever - * have indisclustered set, because CLUSTER will refuse to set it when - * called with one of them as argument. + * appropriate user. System relations or nailed-in relations cannot + * ever have indisclustered set, because CLUSTER will refuse to set it + * when called with one of them as argument. */ indRelation = relation_openr(IndexRelationName, AccessShareLock); ScanKeyEntryInitialize(&entry, 0, @@ -886,8 +891,8 @@ get_tables_to_cluster(MemoryContext cluster_context) continue; /* - * We have to build the list in a different memory context so - * it will survive the cross-transaction processing + * We have to build the list in a different memory context so it + * will survive the cross-transaction processing */ old_context = MemoryContextSwitchTo(cluster_context); diff --git a/src/backend/commands/comment.c b/src/backend/commands/comment.c index ecd50bdb36..e0ebba0df9 100644 --- a/src/backend/commands/comment.c +++ b/src/backend/commands/comment.c @@ -7,7 +7,7 @@ * Copyright (c) 1996-2001, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/comment.c,v 1.67 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/comment.c,v 1.68 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -383,8 +383,8 @@ CommentAttribute(List *qualname, char *comment) if (attnum == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - attrname, RelationGetRelationName(relation)))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + attrname, RelationGetRelationName(relation)))); /* Create the comment using the relation's oid */ @@ -418,16 +418,17 @@ CommentDatabase(List *qualname, char *comment) database = strVal(lfirst(qualname)); /* - * We cannot currently support cross-database comments (since other DBs - * cannot see pg_description of this database). So, we reject attempts - * to comment on a database other than the current one. Someday this - * might be improved, but it would take a redesigned infrastructure. + * We cannot currently support cross-database comments (since other + * DBs cannot see pg_description of this database). So, we reject + * attempts to comment on a database other than the current one. + * Someday this might be improved, but it would take a redesigned + * infrastructure. * * When loading a dump, we may see a COMMENT ON DATABASE for the old name - * of the database. Erroring out would prevent pg_restore from completing - * (which is really pg_restore's fault, but for now we will work around - * the problem here). Consensus is that the best fix is to treat wrong - * database name as a WARNING not an ERROR. + * of the database. Erroring out would prevent pg_restore from + * completing (which is really pg_restore's fault, but for now we will + * work around the problem here). Consensus is that the best fix is + * to treat wrong database name as a WARNING not an ERROR. */ /* First get the database OID */ @@ -569,7 +570,7 @@ CommentRule(List *qualname, char *comment) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("there are multiple rules \"%s\"", rulename), - errhint("Specify a relation name as well as a rule name."))); + errhint("Specify a relation name as well as a rule name."))); heap_endscan(scanDesc); heap_close(RewriteRelation, AccessShareLock); @@ -811,8 +812,8 @@ CommentTrigger(List *qualname, char *comment) if (!HeapTupleIsValid(triggertuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("trigger \"%s\" for relation \"%s\" does not exist", - trigname, RelationGetRelationName(relation)))); + errmsg("trigger \"%s\" for relation \"%s\" does not exist", + trigname, RelationGetRelationName(relation)))); oid = HeapTupleGetOid(triggertuple); @@ -891,7 +892,7 @@ CommentConstraint(List *qualname, char *comment) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("relation \"%s\" has multiple constraints named \"%s\"", - RelationGetRelationName(relation), conName))); + RelationGetRelationName(relation), conName))); conOid = HeapTupleGetOid(tuple); } } @@ -902,8 +903,8 @@ CommentConstraint(List *qualname, char *comment) if (!OidIsValid(conOid)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("constraint \"%s\" for relation \"%s\" does not exist", - conName, RelationGetRelationName(relation)))); + errmsg("constraint \"%s\" for relation \"%s\" does not exist", + conName, RelationGetRelationName(relation)))); /* Create the comment with the pg_constraint oid */ CreateComments(conOid, RelationGetRelid(pg_constraint), 0, comment); diff --git a/src/backend/commands/conversioncmds.c b/src/backend/commands/conversioncmds.c index b917c527ac..e9afb95624 100644 --- a/src/backend/commands/conversioncmds.c +++ b/src/backend/commands/conversioncmds.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/conversioncmds.c,v 1.9 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/conversioncmds.c,v 1.10 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -148,11 +148,11 @@ RenameConversion(List *name, const char *newname) 0, 0)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("conversion \"%s\" already exists in schema \"%s\"", - newname, get_namespace_name(namespaceOid)))); + errmsg("conversion \"%s\" already exists in schema \"%s\"", + newname, get_namespace_name(namespaceOid)))); /* must be owner */ - if (!superuser() && + if (!superuser() && ((Form_pg_conversion) GETSTRUCT(tup))->conowner != GetUserId()) aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CONVERSION, NameListToString(name)); diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c index fa91439a57..5c7238de8d 100644 --- a/src/backend/commands/copy.c +++ b/src/backend/commands/copy.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.205 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.206 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -61,7 +61,7 @@ typedef enum CopyDest COPY_FILE, /* to/from file */ COPY_OLD_FE, /* to/from frontend (old protocol) */ COPY_NEW_FE /* to/from frontend (new protocol) */ -} CopyDest; +} CopyDest; /* * Represents the type of data returned by CopyReadAttribute() @@ -82,17 +82,17 @@ typedef enum EolType EOL_NL, EOL_CR, EOL_CRNL -} EolType; +} EolType; /* non-export function prototypes */ static void CopyTo(Relation rel, List *attnumlist, bool binary, bool oids, - char *delim, char *null_print); + char *delim, char *null_print); static void CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, - char *delim, char *null_print); + char *delim, char *null_print); static char *CopyReadAttribute(const char *delim, CopyReadResult *result); static Datum CopyReadBinaryAttribute(int column_no, FmgrInfo *flinfo, - Oid typelem, bool *isnull); + Oid typelem, bool *isnull); static void CopyAttributeOut(char *string, char *delim); static List *CopyGetAttnums(Relation rel, List *attnamelist); @@ -136,6 +136,7 @@ static void CopySendChar(char c); static void CopySendEndOfRow(bool binary); static void CopyGetData(void *databuf, int datasize); static int CopyGetChar(void); + #define CopyGetEof() (fe_eof) static int CopyPeekChar(void); static void CopyDonePeek(int c, bool pickup); @@ -155,14 +156,14 @@ SendCopyBegin(bool binary, int natts) { /* new way */ StringInfoData buf; - int16 format = (binary ? 1 : 0); - int i; + int16 format = (binary ? 1 : 0); + int i; pq_beginmessage(&buf, 'H'); - pq_sendbyte(&buf, format); /* overall format */ + pq_sendbyte(&buf, format); /* overall format */ pq_sendint(&buf, natts, 2); for (i = 0; i < natts; i++) - pq_sendint(&buf, format, 2); /* per-column formats */ + pq_sendint(&buf, format, 2); /* per-column formats */ pq_endmessage(&buf); copy_dest = COPY_NEW_FE; copy_msgbuf = makeStringInfo(); @@ -200,14 +201,14 @@ ReceiveCopyBegin(bool binary, int natts) { /* new way */ StringInfoData buf; - int16 format = (binary ? 1 : 0); - int i; + int16 format = (binary ? 1 : 0); + int i; pq_beginmessage(&buf, 'G'); - pq_sendbyte(&buf, format); /* overall format */ + pq_sendbyte(&buf, format); /* overall format */ pq_sendint(&buf, natts, 2); for (i = 0; i < natts; i++) - pq_sendint(&buf, format, 2); /* per-column formats */ + pq_sendint(&buf, format, 2); /* per-column formats */ pq_endmessage(&buf); copy_dest = COPY_NEW_FE; copy_msgbuf = makeStringInfo(); @@ -289,7 +290,7 @@ CopySendData(void *databuf, int datasize) /* no hope of recovering connection sync, so FATAL */ ereport(FATAL, (errcode(ERRCODE_CONNECTION_FAILURE), - errmsg("connection lost during COPY to stdout"))); + errmsg("connection lost during COPY to stdout"))); } break; case COPY_NEW_FE: @@ -378,7 +379,7 @@ CopyGetData(void *databuf, int datasize) case COPY_NEW_FE: while (datasize > 0 && !fe_eof) { - int avail; + int avail; while (copy_msgbuf->cursor >= copy_msgbuf->len) { @@ -389,24 +390,24 @@ CopyGetData(void *databuf, int datasize) if (mtype == EOF) ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), - errmsg("unexpected EOF on client connection"))); + errmsg("unexpected EOF on client connection"))); if (pq_getmessage(copy_msgbuf, 0)) ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), - errmsg("unexpected EOF on client connection"))); + errmsg("unexpected EOF on client connection"))); switch (mtype) { - case 'd': /* CopyData */ + case 'd': /* CopyData */ break; - case 'c': /* CopyDone */ + case 'c': /* CopyDone */ /* COPY IN correctly terminated by frontend */ fe_eof = true; return; - case 'f': /* CopyFail */ + case 'f': /* CopyFail */ ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED), errmsg("COPY from stdin failed: %s", - pq_getmsgstring(copy_msgbuf)))); + pq_getmsgstring(copy_msgbuf)))); break; default: ereport(ERROR, @@ -421,7 +422,7 @@ CopyGetData(void *databuf, int datasize) avail = datasize; pq_copymsgbytes(copy_msgbuf, databuf, avail); databuf = (void *) ((char *) databuf + avail); - datasize =- avail; + datasize = -avail; } break; } @@ -430,7 +431,7 @@ CopyGetData(void *databuf, int datasize) static int CopyGetChar(void) { - int ch; + int ch; switch (copy_dest) { @@ -448,16 +449,16 @@ CopyGetChar(void) } break; case COPY_NEW_FE: - { - unsigned char cc; + { + unsigned char cc; - CopyGetData(&cc, 1); - if (fe_eof) - ch = EOF; - else - ch = cc; - break; - } + CopyGetData(&cc, 1); + if (fe_eof) + ch = EOF; + else + ch = cc; + break; + } default: ch = EOF; break; @@ -479,7 +480,7 @@ CopyGetChar(void) static int CopyPeekChar(void) { - int ch; + int ch; switch (copy_dest) { @@ -497,16 +498,16 @@ CopyPeekChar(void) } break; case COPY_NEW_FE: - { - unsigned char cc; + { + unsigned char cc; - CopyGetData(&cc, 1); - if (fe_eof) - ch = EOF; - else - ch = cc; - break; - } + CopyGetData(&cc, 1); + if (fe_eof) + ch = EOF; + else + ch = cc; + break; + } default: ch = EOF; break; @@ -524,7 +525,7 @@ CopyDonePeek(int c, bool pickup) switch (copy_dest) { case COPY_FILE: - if (!pickup) + if (!pickup) { /* We don't want to pick it up - so put it back in there */ ungetc(c, copy_file); @@ -537,7 +538,11 @@ CopyDonePeek(int c, bool pickup) /* We want to pick it up */ (void) pq_getbyte(); } - /* If we didn't want to pick it up, just leave it where it sits */ + + /* + * If we didn't want to pick it up, just leave it where it + * sits + */ break; case COPY_NEW_FE: if (!pickup) @@ -737,7 +742,7 @@ DoCopy(const CopyStmt *stmt) (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("must be superuser to COPY to or from a file"), errhint("Anyone can COPY to stdout or from stdin. " - "psql's \\copy command also works for anyone."))); + "psql's \\copy command also works for anyone."))); /* * Presently, only single-character delimiter strings are supported. @@ -791,8 +796,8 @@ DoCopy(const CopyStmt *stmt) else ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("cannot copy to non-table relation \"%s\"", - RelationGetRelationName(rel)))); + errmsg("cannot copy to non-table relation \"%s\"", + RelationGetRelationName(rel)))); } if (pipe) { @@ -810,8 +815,8 @@ DoCopy(const CopyStmt *stmt) if (copy_file == NULL) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not open file \"%s\" for reading: %m", - filename))); + errmsg("could not open file \"%s\" for reading: %m", + filename))); fstat(fileno(copy_file), &st); if (S_ISDIR(st.st_mode)) @@ -841,8 +846,8 @@ DoCopy(const CopyStmt *stmt) else ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("cannot copy from non-table relation \"%s\"", - RelationGetRelationName(rel)))); + errmsg("cannot copy from non-table relation \"%s\"", + RelationGetRelationName(rel)))); } if (pipe) { @@ -863,7 +868,7 @@ DoCopy(const CopyStmt *stmt) if (!is_absolute_path(filename)) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), - errmsg("relative path not allowed for COPY to file"))); + errmsg("relative path not allowed for COPY to file"))); oumask = umask((mode_t) 022); copy_file = AllocateFile(filename, PG_BINARY_W); @@ -872,8 +877,8 @@ DoCopy(const CopyStmt *stmt) if (copy_file == NULL) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not open file \"%s\" for writing: %m", - filename))); + errmsg("could not open file \"%s\" for writing: %m", + filename))); fstat(fileno(copy_file), &st); if (S_ISDIR(st.st_mode)) @@ -955,8 +960,8 @@ CopyTo(Relation rel, List *attnumlist, bool binary, bool oids, } /* - * Create a temporary memory context that we can reset once per row - * to recover palloc'd memory. This avoids any problems with leaks + * Create a temporary memory context that we can reset once per row to + * recover palloc'd memory. This avoids any problems with leaks * inside datatype output routines, and should be faster than retail * pfree's anyway. (We don't need a whole econtext as CopyFrom does.) */ @@ -1040,9 +1045,9 @@ CopyTo(Relation rel, List *attnumlist, bool binary, bool oids, if (isnull) { if (!binary) - CopySendString(null_print); /* null indicator */ + CopySendString(null_print); /* null indicator */ else - CopySendInt32(-1); /* null marker */ + CopySendInt32(-1); /* null marker */ } else { @@ -1060,7 +1065,7 @@ CopyTo(Relation rel, List *attnumlist, bool binary, bool oids, outputbytes = DatumGetByteaP(FunctionCall2(&out_functions[attnum - 1], value, - ObjectIdGetDatum(elements[attnum - 1]))); + ObjectIdGetDatum(elements[attnum - 1]))); /* We assume the result will not have been toasted */ CopySendInt32(VARSIZE(outputbytes) - VARHDRSZ); CopySendData(VARDATA(outputbytes), @@ -1199,7 +1204,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, { /* attribute is NOT to be copied from input */ /* use default value if one exists */ - Node *defexpr = build_column_default(rel, i + 1); + Node *defexpr = build_column_default(rel, i + 1); if (defexpr != NULL) { @@ -1219,10 +1224,10 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, /* * Easiest way to do this is to use parse_coerce.c to set up * an expression that checks the constraints. (At present, - * the expression might contain a length-coercion-function call - * and/or CoerceToDomain nodes.) The bottom of the expression - * is a Param node so that we can fill in the actual datum during - * the data input loop. + * the expression might contain a length-coercion-function + * call and/or CoerceToDomain nodes.) The bottom of the + * expression is a Param node so that we can fill in the + * actual datum during the data input loop. */ prm = makeNode(Param); prm->paramkind = PARAM_EXEC; @@ -1241,11 +1246,11 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, } /* - * Check BEFORE STATEMENT insertion triggers. It's debateable - * whether we should do this for COPY, since it's not really an - * "INSERT" statement as such. However, executing these triggers - * maintains consistency with the EACH ROW triggers that we already - * fire on COPY. + * Check BEFORE STATEMENT insertion triggers. It's debateable whether + * we should do this for COPY, since it's not really an "INSERT" + * statement as such. However, executing these triggers maintains + * consistency with the EACH ROW triggers that we already fire on + * COPY. */ ExecBSInsertTriggers(estate, resultRelInfo); @@ -1276,13 +1281,13 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, if ((tmp >> 16) != 0) ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("unrecognized critical flags in COPY file header"))); + errmsg("unrecognized critical flags in COPY file header"))); /* Header extension length */ tmp = CopyGetInt32(); if (CopyGetEof() || tmp < 0) ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("invalid COPY file header (missing length)"))); + errmsg("invalid COPY file header (missing length)"))); /* Skip extension header, if present */ while (tmp-- > 0) { @@ -1290,7 +1295,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, if (CopyGetEof()) ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("invalid COPY file header (wrong length)"))); + errmsg("invalid COPY file header (wrong length)"))); } } @@ -1418,9 +1423,9 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, /* * Complain if there are more fields on the input line. * - * Special case: if we're reading a zero-column table, we - * won't yet have called CopyReadAttribute() at all; so do that - * and check we have an empty line. Fortunately we can keep that + * Special case: if we're reading a zero-column table, we won't + * yet have called CopyReadAttribute() at all; so do that and + * check we have an empty line. Fortunately we can keep that * silly corner case out of the main line of execution. */ if (result == NORMAL_ATTR) @@ -1431,7 +1436,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, if (result == NORMAL_ATTR || *string != '\0') ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("extra data after last expected column"))); + errmsg("extra data after last expected column"))); if (result == END_OF_FILE) { /* EOF at start of line: all is well */ @@ -1442,7 +1447,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, else ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("extra data after last expected column"))); + errmsg("extra data after last expected column"))); } /* @@ -1475,8 +1480,8 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, { loaded_oid = DatumGetObjectId(CopyReadBinaryAttribute(0, - &oid_in_function, - oid_in_element, + &oid_in_function, + oid_in_element, &isnull)); if (isnull || loaded_oid == InvalidOid) ereport(ERROR, @@ -1531,9 +1536,9 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids, prmdata->isnull = (nulls[i] == 'n'); /* - * Execute the constraint expression. Allow the expression - * to replace the value (consider e.g. a timestamp precision - * restriction). + * Execute the constraint expression. Allow the + * expression to replace the value (consider e.g. a + * timestamp precision restriction). */ values[i] = ExecEvalExpr(exprstate, econtext, &isnull, NULL); @@ -1674,11 +1679,12 @@ CopyReadAttribute(const char *delim, CopyReadResult *result) ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), errmsg("literal carriage return found in data"), - errhint("Use \"\\r\" to represent carriage return."))); - /* Check for \r\n on first line, _and_ handle \r\n. */ + errhint("Use \"\\r\" to represent carriage return."))); + /* Check for \r\n on first line, _and_ handle \r\n. */ if (copy_lineno == 1 || eol_type == EOL_CRNL) { - int c2 = CopyPeekChar(); + int c2 = CopyPeekChar(); + if (c2 == '\n') { CopyDonePeek(c2, true); /* eat newline */ @@ -1690,9 +1696,13 @@ CopyReadAttribute(const char *delim, CopyReadResult *result) if (eol_type == EOL_CRNL) ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("literal carriage return found in data"), + errmsg("literal carriage return found in data"), errhint("Use \"\\r\" to represent carriage return."))); - /* if we got here, it is the first line and we didn't get \n, so put it back */ + + /* + * if we got here, it is the first line and we didn't + * get \n, so put it back + */ CopyDonePeek(c2, false); eol_type = EOL_CR; } @@ -1802,12 +1812,12 @@ CopyReadAttribute(const char *delim, CopyReadResult *result) c = CopyGetChar(); if (c == '\n') ereport(ERROR, - (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("end-of-copy marker does not match previous newline style"))); + (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), + errmsg("end-of-copy marker does not match previous newline style"))); if (c != '\r') ereport(ERROR, - (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), - errmsg("end-of-copy marker corrupt"))); + (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), + errmsg("end-of-copy marker corrupt"))); } c = CopyGetChar(); if (c != '\r' && c != '\n') @@ -1816,21 +1826,20 @@ CopyReadAttribute(const char *delim, CopyReadResult *result) errmsg("end-of-copy marker corrupt"))); if ((eol_type == EOL_NL && c != '\n') || (eol_type == EOL_CRNL && c != '\n') || - (eol_type == EOL_CR && c != '\r')) + (eol_type == EOL_CR && c != '\r')) ereport(ERROR, (errcode(ERRCODE_BAD_COPY_FILE_FORMAT), errmsg("end-of-copy marker does not match previous newline style"))); + /* - * In protocol version 3, we should ignore anything after - * \. up to the protocol end of copy data. (XXX maybe - * better not to treat \. as special?) + * In protocol version 3, we should ignore anything + * after \. up to the protocol end of copy data. (XXX + * maybe better not to treat \. as special?) */ if (copy_dest == COPY_NEW_FE) { while (c != EOF) - { c = CopyGetChar(); - } } *result = END_OF_FILE; goto copy_eof; @@ -2045,8 +2054,8 @@ CopyGetAttnums(Relation rel, List *attnamelist) if (intMember(attnum, attnums)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), - errmsg("attribute \"%s\" specified more than once", - name))); + errmsg("attribute \"%s\" specified more than once", + name))); attnums = lappendi(attnums, attnum); } } diff --git a/src/backend/commands/dbcommands.c b/src/backend/commands/dbcommands.c index 70678b26b0..547f3fb2f3 100644 --- a/src/backend/commands/dbcommands.c +++ b/src/backend/commands/dbcommands.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/dbcommands.c,v 1.119 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/dbcommands.c,v 1.120 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -200,7 +200,7 @@ createdb(const CreatedbStmt *stmt) if (dbpath != NULL) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot use an alternate location on this platform"))); + errmsg("cannot use an alternate location on this platform"))); #endif /* @@ -260,8 +260,8 @@ createdb(const CreatedbStmt *stmt) if (DatabaseHasActiveBackends(src_dboid, true)) ereport(ERROR, (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("source database \"%s\" is being accessed by other users", - dbtemplate))); + errmsg("source database \"%s\" is being accessed by other users", + dbtemplate))); /* If encoding is defaulted, use source's encoding */ if (encoding < 0) @@ -345,7 +345,7 @@ createdb(const CreatedbStmt *stmt) /* Make the symlink, if needed */ if (alt_loc) { -#ifdef HAVE_SYMLINK /* already throws error above */ +#ifdef HAVE_SYMLINK /* already throws error above */ if (symlink(alt_loc, nominal_loc) != 0) #endif ereport(ERROR, @@ -450,7 +450,7 @@ dropdb(const char *dbname) char *nominal_loc; char dbpath[MAXPGPATH]; Relation pgdbrel; - SysScanDesc pgdbscan; + SysScanDesc pgdbscan; ScanKeyData key; HeapTuple tup; @@ -503,8 +503,8 @@ dropdb(const char *dbname) if (DatabaseHasActiveBackends(db_id, false)) ereport(ERROR, (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("database \"%s\" is being accessed by other users", - dbname))); + errmsg("database \"%s\" is being accessed by other users", + dbname))); /* * Find the database's tuple by OID (should be unique). @@ -577,10 +577,13 @@ dropdb(const char *dbname) void RenameDatabase(const char *oldname, const char *newname) { - HeapTuple tup, newtup; + HeapTuple tup, + newtup; Relation rel; - SysScanDesc scan, scan2; - ScanKeyData key, key2; + SysScanDesc scan, + scan2; + ScanKeyData key, + key2; /* * Obtain AccessExclusiveLock so that no new session gets started @@ -610,15 +613,14 @@ RenameDatabase(const char *oldname, const char *newname) errmsg("current database may not be renamed"))); /* - * Make sure the database does not have active sessions. Might - * not be necessary, but it's consistent with other database - * operations. + * Make sure the database does not have active sessions. Might not be + * necessary, but it's consistent with other database operations. */ if (DatabaseHasActiveBackends(HeapTupleGetOid(tup), false)) ereport(ERROR, (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("database \"%s\" is being accessed by other users", - oldname))); + errmsg("database \"%s\" is being accessed by other users", + oldname))); /* make sure the new name doesn't exist */ ScanKeyEntryInitialize(&key2, 0, Anum_pg_database_datname, @@ -651,10 +653,10 @@ RenameDatabase(const char *oldname, const char *newname) heap_close(rel, NoLock); /* - * Force dirty buffers out to disk, so that newly-connecting - * backends will see the renamed database in pg_database right - * away. (They'll see an uncommitted tuple, but they don't care; - * see GetRawDatabaseInfo.) + * Force dirty buffers out to disk, so that newly-connecting backends + * will see the renamed database in pg_database right away. (They'll + * see an uncommitted tuple, but they don't care; see + * GetRawDatabaseInfo.) */ BufferSync(); } @@ -671,7 +673,7 @@ AlterDatabaseSet(AlterDatabaseSetStmt *stmt) newtuple; Relation rel; ScanKeyData scankey; - SysScanDesc scan; + SysScanDesc scan; Datum repl_val[Natts_pg_database]; char repl_null[Natts_pg_database]; char repl_repl[Natts_pg_database]; @@ -689,9 +691,9 @@ AlterDatabaseSet(AlterDatabaseSetStmt *stmt) errmsg("database \"%s\" does not exist", stmt->dbname))); if (!(superuser() - || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId())) + || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId())) aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE, - stmt->dbname); + stmt->dbname); MemSet(repl_repl, ' ', sizeof(repl_repl)); repl_repl[Anum_pg_database_datconfig - 1] = 'r'; @@ -750,7 +752,7 @@ get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP, { Relation relation; ScanKeyData scanKey; - SysScanDesc scan; + SysScanDesc scan; HeapTuple tuple; bool gottuple; @@ -862,7 +864,7 @@ resolve_alt_dbpath(const char *dbpath, Oid dboid) #ifndef ALLOW_ABSOLUTE_DBPATHS ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("absolute paths are not allowed as database locations"))); + errmsg("absolute paths are not allowed as database locations"))); #endif prefix = dbpath; } @@ -874,8 +876,8 @@ resolve_alt_dbpath(const char *dbpath, Oid dboid) if (!var) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("postmaster environment variable \"%s\" not found", - dbpath))); + errmsg("postmaster environment variable \"%s\" not found", + dbpath))); if (!is_absolute_path(var)) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), @@ -955,7 +957,7 @@ get_database_oid(const char *dbname) { Relation pg_database; ScanKeyData entry[1]; - SysScanDesc scan; + SysScanDesc scan; HeapTuple dbtuple; Oid oid; @@ -993,7 +995,7 @@ get_database_name(Oid dbid) { Relation pg_database; ScanKeyData entry[1]; - SysScanDesc scan; + SysScanDesc scan; HeapTuple dbtuple; char *result; diff --git a/src/backend/commands/define.c b/src/backend/commands/define.c index bf0c95a75e..c924dcc7b7 100644 --- a/src/backend/commands/define.c +++ b/src/backend/commands/define.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.82 2003/07/20 21:56:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.83 2003/08/04 00:43:16 momjian Exp $ * * DESCRIPTION * The "DefineFoo" routines take the parse tree and pick out the @@ -51,7 +51,8 @@ case_translate_language_name(const char *input, char *output) { int i; - MemSet(output, 0, NAMEDATALEN); /* ensure result Name is zero-filled */ + MemSet(output, 0, NAMEDATALEN); /* ensure result Name is + * zero-filled */ for (i = 0; i < NAMEDATALEN - 1 && input[i]; ++i) output[i] = tolower((unsigned char) input[i]); diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c index bc137b0eac..916c1ff772 100644 --- a/src/backend/commands/explain.c +++ b/src/backend/commands/explain.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994-5, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.111 2003/07/20 21:56:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.112 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,11 +45,11 @@ typedef struct ExplainState static void ExplainOneQuery(Query *query, ExplainStmt *stmt, TupOutputState *tstate); -static double elapsed_time(struct timeval *starttime); +static double elapsed_time(struct timeval * starttime); static void explain_outNode(StringInfo str, - Plan *plan, PlanState *planstate, - Plan *outer_plan, - int indent, ExplainState *es); + Plan *plan, PlanState * planstate, + Plan *outer_plan, + int indent, ExplainState *es); static void show_scan_qual(List *qual, bool is_or_qual, const char *qlabel, int scanrelid, Plan *outer_plan, StringInfo str, int indent, ExplainState *es); @@ -58,8 +58,8 @@ static void show_upper_qual(List *qual, const char *qlabel, const char *inner_name, int inner_varno, Plan *inner_plan, StringInfo str, int indent, ExplainState *es); static void show_sort_keys(List *tlist, int nkeys, AttrNumber *keycols, - const char *qlabel, - StringInfo str, int indent, ExplainState *es); + const char *qlabel, + StringInfo str, int indent, ExplainState *es); static Node *make_ors_ands_explicit(List *orclauses); /* @@ -255,8 +255,8 @@ ExplainOnePlan(QueryDesc *queryDesc, ExplainStmt *stmt, } /* - * Close down the query and free resources. Include time for this - * in the total runtime. + * Close down the query and free resources. Include time for this in + * the total runtime. */ gettimeofday(&starttime, NULL); @@ -282,7 +282,7 @@ ExplainOnePlan(QueryDesc *queryDesc, ExplainStmt *stmt, /* Compute elapsed time in seconds since given gettimeofday() timestamp */ static double -elapsed_time(struct timeval *starttime) +elapsed_time(struct timeval * starttime) { struct timeval endtime; @@ -313,7 +313,7 @@ elapsed_time(struct timeval *starttime) */ static void explain_outNode(StringInfo str, - Plan *plan, PlanState *planstate, + Plan *plan, PlanState * planstate, Plan *outer_plan, int indent, ExplainState *es) { @@ -542,8 +542,8 @@ explain_outNode(StringInfo str, /* * If the expression is still a function call, we can get * the real name of the function. Otherwise, punt (this - * can happen if the optimizer simplified away the function - * call, for example). + * can happen if the optimizer simplified away the + * function call, for example). */ if (rte->funcexpr && IsA(rte->funcexpr, FuncExpr)) { @@ -583,15 +583,13 @@ explain_outNode(StringInfo str, double nloops = planstate->instrument->nloops; appendStringInfo(str, " (actual time=%.2f..%.2f rows=%.0f loops=%.0f)", - 1000.0 * planstate->instrument->startup / nloops, - 1000.0 * planstate->instrument->total / nloops, + 1000.0 * planstate->instrument->startup / nloops, + 1000.0 * planstate->instrument->total / nloops, planstate->instrument->ntuples / nloops, planstate->instrument->nloops); } else if (es->printAnalyze) - { appendStringInfo(str, " (never executed)"); - } } appendStringInfoChar(str, '\n'); @@ -709,7 +707,7 @@ explain_outNode(StringInfo str, foreach(lst, planstate->initPlan) { SubPlanState *sps = (SubPlanState *) lfirst(lst); - SubPlan *sp = (SubPlan *) sps->xprstate.expr; + SubPlan *sp = (SubPlan *) sps->xprstate.expr; es->rtable = sp->rtable; for (i = 0; i < indent; i++) @@ -807,7 +805,7 @@ explain_outNode(StringInfo str, foreach(lst, planstate->subPlan) { SubPlanState *sps = (SubPlanState *) lfirst(lst); - SubPlan *sp = (SubPlan *) sps->xprstate.expr; + SubPlan *sp = (SubPlan *) sps->xprstate.expr; es->rtable = sp->rtable; for (i = 0; i < indent; i++) @@ -865,7 +863,7 @@ show_scan_qual(List *qual, bool is_or_qual, const char *qlabel, */ if (outer_plan) { - Relids varnos = pull_varnos(node); + Relids varnos = pull_varnos(node); if (bms_is_member(OUTER, varnos)) outercontext = deparse_context_for_subplan("outer", @@ -1037,9 +1035,7 @@ make_ors_ands_explicit(List *orclauses) FastListInit(&args); foreach(orptr, orclauses) - { FastAppend(&args, make_ands_explicit(lfirst(orptr))); - } return (Node *) make_orclause(FastListValue(&args)); } diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c index 7a6a3775d6..181f52e114 100644 --- a/src/backend/commands/functioncmds.c +++ b/src/backend/commands/functioncmds.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/functioncmds.c,v 1.31 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/functioncmds.c,v 1.32 2003/08/04 00:43:16 momjian Exp $ * * DESCRIPTION * These routines take the parse tree and pick out the @@ -80,8 +80,8 @@ compute_return_type(TypeName *returnType, Oid languageOid, if (languageOid == SQLlanguageId) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("SQL function cannot return shell type %s", - TypeNameToString(returnType)))); + errmsg("SQL function cannot return shell type %s", + TypeNameToString(returnType)))); else ereport(NOTICE, (errcode(ERRCODE_WRONG_OBJECT_TYPE), @@ -147,8 +147,8 @@ compute_parameter_types(List *argTypes, Oid languageOid, if (parameterCount >= FUNC_MAX_ARGS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_ARGUMENTS), - errmsg("functions cannot have more than %d arguments", - FUNC_MAX_ARGS))); + errmsg("functions cannot have more than %d arguments", + FUNC_MAX_ARGS))); toid = LookupTypeName(t); if (OidIsValid(toid)) @@ -159,8 +159,8 @@ compute_parameter_types(List *argTypes, Oid languageOid, if (languageOid == SQLlanguageId) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("SQL function cannot accept shell type %s", - TypeNameToString(t)))); + errmsg("SQL function cannot accept shell type %s", + TypeNameToString(t)))); else ereport(NOTICE, (errcode(ERRCODE_WRONG_OBJECT_TYPE), @@ -330,8 +330,8 @@ compute_attributes_with_style(List *parameters, bool *isStrict_p, char *volatili else ereport(WARNING, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("unrecognized function attribute \"%s\" ignored", - param->defname))); + errmsg("unrecognized function attribute \"%s\" ignored", + param->defname))); } } @@ -558,7 +558,7 @@ RemoveFunction(RemoveFuncStmt *stmt) (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is an aggregate function", NameListToString(functionName)), - errhint("Use DROP AGGREGATE to drop aggregate functions."))); + errhint("Use DROP AGGREGATE to drop aggregate functions."))); if (((Form_pg_proc) GETSTRUCT(tup))->prolang == INTERNALlanguageId) { @@ -664,7 +664,7 @@ RenameFunction(List *name, List *argtypes, const char *newname) (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is an aggregate function", NameListToString(name)), - errhint("Use ALTER AGGREGATE to rename aggregate functions."))); + errhint("Use ALTER AGGREGATE to rename aggregate functions."))); namespaceOid = procForm->pronamespace; @@ -728,7 +728,7 @@ SetFunctionReturnType(Oid funcOid, Oid newRetType) elog(ERROR, "cache lookup failed for function %u", funcOid); procForm = (Form_pg_proc) GETSTRUCT(tup); - if (procForm->prorettype != OPAQUEOID) /* caller messed up */ + if (procForm->prorettype != OPAQUEOID) /* caller messed up */ elog(ERROR, "function %u doesn't return OPAQUE", funcOid); /* okay to overwrite copied tuple */ @@ -815,7 +815,7 @@ CreateCast(CreateCastStmt *stmt) if (sourcetypeid == targettypeid) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("source data type and target data type are the same"))); + errmsg("source data type and target data type are the same"))); /* No shells, no pseudo-types allowed */ if (!get_typisdefined(sourcetypeid)) @@ -878,10 +878,11 @@ CreateCast(CreateCastStmt *stmt) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("return data type of cast function must match target data type"))); + /* * Restricting the volatility of a cast function may or may not be * a good idea in the abstract, but it definitely breaks many old - * user-defined types. Disable this check --- tgl 2/1/03 + * user-defined types. Disable this check --- tgl 2/1/03 */ #ifdef NOT_USED if (procstruct->provolatile == PROVOLATILE_VOLATILE) @@ -892,7 +893,7 @@ CreateCast(CreateCastStmt *stmt) if (procstruct->proisagg) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("cast function must not be an aggregate function"))); + errmsg("cast function must not be an aggregate function"))); if (procstruct->proretset) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), @@ -902,12 +903,12 @@ CreateCast(CreateCastStmt *stmt) } else { - int16 typ1len; - int16 typ2len; - bool typ1byval; - bool typ2byval; - char typ1align; - char typ2align; + int16 typ1len; + int16 typ2len; + bool typ1byval; + bool typ2byval; + char typ1align; + char typ2align; /* indicates binary coercibility */ funcid = InvalidOid; @@ -924,7 +925,7 @@ CreateCast(CreateCastStmt *stmt) /* * Also, insist that the types match as to size, alignment, and * pass-by-value attributes; this provides at least a crude check - * that they have similar representations. A pair of types that + * that they have similar representations. A pair of types that * fail this test should certainly not be equated. */ get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align); @@ -958,9 +959,9 @@ CreateCast(CreateCastStmt *stmt) relation = heap_openr(CastRelationName, RowExclusiveLock); /* - * Check for duplicate. This is just to give a friendly error message, - * the unique index would catch it anyway (so no need to sweat about - * race conditions). + * Check for duplicate. This is just to give a friendly error + * message, the unique index would catch it anyway (so no need to + * sweat about race conditions). */ tuple = SearchSysCache(CASTSOURCETARGET, ObjectIdGetDatum(sourcetypeid), diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 4cd66fd1b5..5e3cec954d 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/indexcmds.c,v 1.103 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/indexcmds.c,v 1.104 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -44,11 +44,11 @@ /* non-export function prototypes */ static void CheckPredicate(List *predList); static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *classOidP, - List *attList, - Oid relId, - char *accessMethodName, Oid accessMethodId); + List *attList, + Oid relId, + char *accessMethodName, Oid accessMethodId); static Oid GetIndexOpClass(List *opclass, Oid attrType, - char *accessMethodName, Oid accessMethodId); + char *accessMethodName, Oid accessMethodId); static Oid GetDefaultOpClass(Oid attrType, Oid accessMethodId); /* @@ -157,8 +157,8 @@ DefineIndex(RangeVar *heapRelation, if (unique && !accessMethodForm->amcanunique) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("access method \"%s\" does not support UNIQUE indexes", - accessMethodName))); + errmsg("access method \"%s\" does not support UNIQUE indexes", + accessMethodName))); if (numberOfAttributes > 1 && !accessMethodForm->amcanmulticol) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), @@ -192,16 +192,16 @@ DefineIndex(RangeVar *heapRelation, } /* - * Check that all of the attributes in a primary key are marked - * as not null, otherwise attempt to ALTER TABLE .. SET NOT NULL + * Check that all of the attributes in a primary key are marked as not + * null, otherwise attempt to ALTER TABLE .. SET NOT NULL */ if (primary) { - List *keys; + List *keys; foreach(keys, attributeList) { - IndexElem *key = (IndexElem *) lfirst(keys); + IndexElem *key = (IndexElem *) lfirst(keys); HeapTuple atttuple; if (!key->name) @@ -216,15 +216,16 @@ DefineIndex(RangeVar *heapRelation, atttuple = SearchSysCacheAttName(relationId, key->name); if (HeapTupleIsValid(atttuple)) { - if (! ((Form_pg_attribute) GETSTRUCT(atttuple))->attnotnull) + if (!((Form_pg_attribute) GETSTRUCT(atttuple))->attnotnull) { /* * Try to make it NOT NULL. * * XXX: Shouldn't the ALTER TABLE .. SET NOT NULL cascade * to child tables? Currently, since the PRIMARY KEY - * itself doesn't cascade, we don't cascade the notnull - * constraint either; but this is pretty debatable. + * itself doesn't cascade, we don't cascade the + * notnull constraint either; but this is pretty + * debatable. */ AlterTableAlterColumnSetNotNull(relationId, false, key->name); @@ -236,8 +237,8 @@ DefineIndex(RangeVar *heapRelation, /* This shouldn't happen if parser did its job ... */ ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("column \"%s\" named in key does not exist", - key->name))); + errmsg("column \"%s\" named in key does not exist", + key->name))); } } } @@ -248,7 +249,7 @@ DefineIndex(RangeVar *heapRelation, */ indexInfo = makeNode(IndexInfo); indexInfo->ii_NumIndexAttrs = numberOfAttributes; - indexInfo->ii_Expressions = NIL; /* for now */ + indexInfo->ii_Expressions = NIL; /* for now */ indexInfo->ii_ExpressionsState = NIL; indexInfo->ii_Predicate = cnfPred; indexInfo->ii_PredicateState = NIL; @@ -308,7 +309,7 @@ CheckPredicate(List *predList) if (contain_mutable_functions((Node *) predList)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("functions in index predicate must be marked IMMUTABLE"))); + errmsg("functions in index predicate must be marked IMMUTABLE"))); } static void @@ -351,7 +352,7 @@ ComputeIndexAttrs(IndexInfo *indexInfo, else if (attribute->expr && IsA(attribute->expr, Var)) { /* Tricky tricky, he wrote (column) ... treat as simple attr */ - Var *var = (Var *) attribute->expr; + Var *var = (Var *) attribute->expr; indexInfo->ii_KeyAttrNumbers[attn] = var->varattno; atttype = get_atttype(relId, var->varattno); @@ -360,30 +361,30 @@ ComputeIndexAttrs(IndexInfo *indexInfo, { /* Index expression */ Assert(attribute->expr != NULL); - indexInfo->ii_KeyAttrNumbers[attn] = 0; /* marks expression */ + indexInfo->ii_KeyAttrNumbers[attn] = 0; /* marks expression */ indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions, attribute->expr); atttype = exprType(attribute->expr); /* - * We don't currently support generation of an actual query plan - * for an index expression, only simple scalar expressions; - * hence these restrictions. + * We don't currently support generation of an actual query + * plan for an index expression, only simple scalar + * expressions; hence these restrictions. */ if (contain_subplans(attribute->expr)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot use sub-select in index expression"))); + errmsg("cannot use sub-select in index expression"))); if (contain_agg_clause(attribute->expr)) ereport(ERROR, (errcode(ERRCODE_GROUPING_ERROR), - errmsg("cannot use aggregate in index expression"))); + errmsg("cannot use aggregate in index expression"))); /* * A expression using mutable functions is probably wrong, - * since if you aren't going to get the same result for the same - * data every time, it's not clear what the index entries mean at - * all. + * since if you aren't going to get the same result for the + * same data every time, it's not clear what the index entries + * mean at all. */ if (contain_mutable_functions(attribute->expr)) ereport(ERROR, @@ -413,21 +414,20 @@ GetIndexOpClass(List *opclass, Oid attrType, opInputType; /* - * Release 7.0 removed network_ops, timespan_ops, and - * datetime_ops, so we ignore those opclass names - * so the default *_ops is used. This can be - * removed in some later release. bjm 2000/02/07 + * Release 7.0 removed network_ops, timespan_ops, and datetime_ops, so + * we ignore those opclass names so the default *_ops is used. This + * can be removed in some later release. bjm 2000/02/07 * - * Release 7.1 removes lztext_ops, so suppress that too - * for a while. tgl 2000/07/30 + * Release 7.1 removes lztext_ops, so suppress that too for a while. tgl + * 2000/07/30 * - * Release 7.2 renames timestamp_ops to timestamptz_ops, - * so suppress that too for awhile. I'm starting to - * think we need a better approach. tgl 2000/10/01 + * Release 7.2 renames timestamp_ops to timestamptz_ops, so suppress that + * too for awhile. I'm starting to think we need a better approach. + * tgl 2000/10/01 */ if (length(opclass) == 1) { - char *claname = strVal(lfirst(opclass)); + char *claname = strVal(lfirst(opclass)); if (strcmp(claname, "network_ops") == 0 || strcmp(claname, "timespan_ops") == 0 || @@ -499,8 +499,8 @@ GetIndexOpClass(List *opclass, Oid attrType, if (!IsBinaryCoercible(attrType, opInputType)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("operator class \"%s\" does not accept data type %s", - NameListToString(opclass), format_type_be(attrType)))); + errmsg("operator class \"%s\" does not accept data type %s", + NameListToString(opclass), format_type_be(attrType)))); ReleaseSysCache(tuple); @@ -607,7 +607,7 @@ ReindexIndex(RangeVar *indexRelation, bool force /* currently unused */ ) tuple = SearchSysCache(RELOID, ObjectIdGetDatum(indOid), 0, 0, 0); - if (!HeapTupleIsValid(tuple)) /* shouldn't happen */ + if (!HeapTupleIsValid(tuple)) /* shouldn't happen */ elog(ERROR, "cache lookup failed for relation %u", indOid); if (((Form_pg_class) GETSTRUCT(tuple))->relkind != RELKIND_INDEX) @@ -785,7 +785,8 @@ ReindexDatabase(const char *dbname, bool force, bool all) for (i = 0; i < relcnt; i++) { StartTransactionCommand(); - SetQuerySnapshot(); /* might be needed for functions in indexes */ + SetQuerySnapshot(); /* might be needed for functions in + * indexes */ if (reindex_relation(relids[i], force)) ereport(NOTICE, (errmsg("relation %u was reindexed", relids[i]))); diff --git a/src/backend/commands/opclasscmds.c b/src/backend/commands/opclasscmds.c index 60b041466f..52792bc31a 100644 --- a/src/backend/commands/opclasscmds.c +++ b/src/backend/commands/opclasscmds.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/opclasscmds.c,v 1.15 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/opclasscmds.c,v 1.16 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -103,13 +103,13 @@ DefineOpClass(CreateOpClassStmt *stmt) * Currently, we require superuser privileges to create an opclass. * This seems necessary because we have no way to validate that the * offered set of operators and functions are consistent with the AM's - * expectations. It would be nice to provide such a check someday, - * if it can be done without solving the halting problem :-( + * expectations. It would be nice to provide such a check someday, if + * it can be done without solving the halting problem :-( */ if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to create an operator class"))); + errmsg("must be superuser to create an operator class"))); /* Look up the datatype */ typeoid = typenameTypeId(stmt->datatype); @@ -157,8 +157,8 @@ DefineOpClass(CreateOpClassStmt *stmt) if (operators[item->number - 1] != InvalidOid) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("operator number %d appears more than once", - item->number))); + errmsg("operator number %d appears more than once", + item->number))); if (item->args != NIL) { TypeName *typeName1 = (TypeName *) lfirst(item->args); @@ -211,7 +211,7 @@ DefineOpClass(CreateOpClassStmt *stmt) if (OidIsValid(storageoid)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("storage type specified more than once"))); + errmsg("storage type specified more than once"))); storageoid = typenameTypeId(item->storedtype); break; default: @@ -532,7 +532,7 @@ RemoveOpClass(RemoveOpClassStmt *stmt) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("operator class \"%s\" does not exist for access method \"%s\"", - NameListToString(stmt->opclassname), stmt->amname))); + NameListToString(stmt->opclassname), stmt->amname))); opcID = HeapTupleGetOid(tuple); @@ -681,7 +681,7 @@ RenameOpClass(List *name, const char *access_method, const char *newname) tup = SearchSysCacheCopy(CLAOID, ObjectIdGetDatum(opcOid), 0, 0, 0); - if (!HeapTupleIsValid(tup)) /* should not happen */ + if (!HeapTupleIsValid(tup)) /* should not happen */ elog(ERROR, "cache lookup failed for opclass %u", opcOid); namespaceOid = ((Form_pg_opclass) GETSTRUCT(tup))->opcnamespace; diff --git a/src/backend/commands/operatorcmds.c b/src/backend/commands/operatorcmds.c index 6a4d479c12..ddc088fe2f 100644 --- a/src/backend/commands/operatorcmds.c +++ b/src/backend/commands/operatorcmds.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/operatorcmds.c,v 1.10 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/operatorcmds.c,v 1.11 2003/08/04 00:43:16 momjian Exp $ * * DESCRIPTION * The "DefineFoo" routines take the parse tree and pick out the @@ -103,7 +103,7 @@ DefineOperator(List *names, List *parameters) if (typeName1->setof) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("setof type not allowed for operator argument"))); + errmsg("setof type not allowed for operator argument"))); } else if (strcasecmp(defel->defname, "rightarg") == 0) { @@ -111,7 +111,7 @@ DefineOperator(List *names, List *parameters) if (typeName2->setof) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), - errmsg("setof type not allowed for operator argument"))); + errmsg("setof type not allowed for operator argument"))); } else if (strcasecmp(defel->defname, "procedure") == 0) functionName = defGetQualifiedName(defel); diff --git a/src/backend/commands/portalcmds.c b/src/backend/commands/portalcmds.c index cf4a063871..aa5a5b9ea6 100644 --- a/src/backend/commands/portalcmds.c +++ b/src/backend/commands/portalcmds.c @@ -4,17 +4,17 @@ * Utility commands affecting portals (that is, SQL cursor commands) * * Note: see also tcop/pquery.c, which implements portal operations for - * the FE/BE protocol. This module uses pquery.c for some operations. + * the FE/BE protocol. This module uses pquery.c for some operations. * And both modules depend on utils/mmgr/portalmem.c, which controls * storage management for portals (but doesn't run any queries in them). - * + * * * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/portalcmds.c,v 1.19 2003/08/01 13:53:36 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/portalcmds.c,v 1.20 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -36,7 +36,7 @@ * Execute SQL DECLARE CURSOR command. */ void -PerformCursorOpen(DeclareCursorStmt *stmt) +PerformCursorOpen(DeclareCursorStmt * stmt) { List *rewritten; Query *query; @@ -64,7 +64,8 @@ PerformCursorOpen(DeclareCursorStmt *stmt) /* * The query has been through parse analysis, but not rewriting or * planning as yet. Note that the grammar ensured we have a SELECT - * query, so we are not expecting rule rewriting to do anything strange. + * query, so we are not expecting rule rewriting to do anything + * strange. */ rewritten = QueryRewrite((Query *) stmt->query); if (length(rewritten) != 1 || !IsA(lfirst(rewritten), Query)) @@ -86,8 +87,9 @@ PerformCursorOpen(DeclareCursorStmt *stmt) plan = planner(query, true, stmt->options); /* - * Create a portal and copy the query and plan into its memory context. - * (If a duplicate cursor name already exists, warn and drop it.) + * Create a portal and copy the query and plan into its memory + * context. (If a duplicate cursor name already exists, warn and drop + * it.) */ portal = CreatePortal(stmt->portalname, true, false); @@ -98,7 +100,7 @@ PerformCursorOpen(DeclareCursorStmt *stmt) PortalDefineQuery(portal, NULL, /* unfortunately don't have sourceText */ - "SELECT", /* cursor's query is always a SELECT */ + "SELECT", /* cursor's query is always a SELECT */ makeList1(query), makeList1(plan), PortalGetHeapMemory(portal)); @@ -108,9 +110,9 @@ PerformCursorOpen(DeclareCursorStmt *stmt) /* * Set up options for portal. * - * If the user didn't specify a SCROLL type, allow or disallow - * scrolling based on whether it would require any additional - * runtime overhead to do so. + * If the user didn't specify a SCROLL type, allow or disallow scrolling + * based on whether it would require any additional runtime overhead + * to do so. */ portal->cursorOptions = stmt->options; if (!(portal->cursorOptions & (CURSOR_OPT_SCROLL | CURSOR_OPT_NO_SCROLL))) @@ -129,8 +131,8 @@ PerformCursorOpen(DeclareCursorStmt *stmt) Assert(portal->strategy == PORTAL_ONE_SELECT); /* - * We're done; the query won't actually be run until PerformPortalFetch - * is called. + * We're done; the query won't actually be run until + * PerformPortalFetch is called. */ } @@ -169,7 +171,7 @@ PerformPortalFetch(FetchStmt *stmt, /* FIXME: shouldn't this be an ERROR? */ ereport(WARNING, (errcode(ERRCODE_UNDEFINED_CURSOR), - errmsg("portal \"%s\" does not exist", stmt->portalname))); + errmsg("portal \"%s\" does not exist", stmt->portalname))); if (completionTag) strcpy(completionTag, stmt->ismove ? "MOVE 0" : "FETCH 0"); return; @@ -219,7 +221,7 @@ PerformPortalClose(const char *name) ereport(WARNING, (errcode(ERRCODE_UNDEFINED_CURSOR), errmsg("portal \"%s\" does not exist", name), - errfunction("PerformPortalClose"))); /* for ecpg */ + errfunction("PerformPortalClose"))); /* for ecpg */ return; } @@ -249,7 +251,8 @@ PortalCleanup(Portal portal, bool isError) /* * Shut down executor, if still running. We skip this during error * abort, since other mechanisms will take care of releasing executor - * resources, and we can't be sure that ExecutorEnd itself wouldn't fail. + * resources, and we can't be sure that ExecutorEnd itself wouldn't + * fail. */ queryDesc = PortalGetQueryDesc(portal); if (queryDesc) @@ -271,14 +274,14 @@ PortalCleanup(Portal portal, bool isError) void PersistHoldablePortal(Portal portal) { - QueryDesc *queryDesc = PortalGetQueryDesc(portal); + QueryDesc *queryDesc = PortalGetQueryDesc(portal); MemoryContext savePortalContext; MemoryContext saveQueryContext; MemoryContext oldcxt; /* - * If we're preserving a holdable portal, we had better be - * inside the transaction that originally created it. + * If we're preserving a holdable portal, we had better be inside the + * transaction that originally created it. */ Assert(portal->createXact == GetCurrentTransactionId()); Assert(queryDesc != NULL); @@ -321,9 +324,8 @@ PersistHoldablePortal(Portal portal) MemoryContextSwitchTo(PortalContext); /* - * Rewind the executor: we need to store the entire result set in - * the tuplestore, so that subsequent backward FETCHs can be - * processed. + * Rewind the executor: we need to store the entire result set in the + * tuplestore, so that subsequent backward FETCHs can be processed. */ ExecutorRewind(queryDesc); @@ -351,17 +353,17 @@ PersistHoldablePortal(Portal portal) /* * Reset the position in the result set: ideally, this could be * implemented by just skipping straight to the tuple # that we need - * to be at, but the tuplestore API doesn't support that. So we - * start at the beginning of the tuplestore and iterate through it - * until we reach where we need to be. FIXME someday? + * to be at, but the tuplestore API doesn't support that. So we start + * at the beginning of the tuplestore and iterate through it until we + * reach where we need to be. FIXME someday? */ MemoryContextSwitchTo(portal->holdContext); if (!portal->atEnd) { - long store_pos; + long store_pos; - if (portal->posOverflow) /* oops, cannot trust portalPos */ + if (portal->posOverflow) /* oops, cannot trust portalPos */ ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("could not reposition held cursor"))); @@ -370,8 +372,8 @@ PersistHoldablePortal(Portal portal) for (store_pos = 0; store_pos < portal->portalPos; store_pos++) { - HeapTuple tup; - bool should_free; + HeapTuple tup; + bool should_free; tup = tuplestore_gettuple(portal->holdStore, true, &should_free); @@ -389,8 +391,8 @@ PersistHoldablePortal(Portal portal) /* * We can now release any subsidiary memory of the portal's heap * context; we'll never use it again. The executor already dropped - * its context, but this will clean up anything that glommed onto - * the portal's heap via PortalContext. + * its context, but this will clean up anything that glommed onto the + * portal's heap via PortalContext. */ MemoryContextDeleteChildren(PortalGetHeapMemory(portal)); } diff --git a/src/backend/commands/prepare.c b/src/backend/commands/prepare.c index cd58d7fc7b..d0fabd1ad3 100644 --- a/src/backend/commands/prepare.c +++ b/src/backend/commands/prepare.c @@ -10,7 +10,7 @@ * Copyright (c) 2002-2003, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/prepare.c,v 1.21 2003/07/28 00:09:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/prepare.c,v 1.22 2003/08/04 00:43:16 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -39,7 +39,7 @@ static HTAB *prepared_queries = NULL; static void InitQueryHashTable(void); static ParamListInfo EvaluateParams(EState *estate, - List *params, List *argtypes); + List *params, List *argtypes); /* * Implements the 'PREPARE' utility statement. @@ -90,12 +90,12 @@ PrepareQuery(PrepareStmt *stmt) /* Rewrite the query. The result could be 0, 1, or many queries. */ query_list = QueryRewrite(stmt->query); - /* Generate plans for queries. Snapshot is already set. */ + /* Generate plans for queries. Snapshot is already set. */ plan_list = pg_plan_queries(query_list, false); /* Save the results. */ StorePreparedStatement(stmt->name, - NULL, /* text form not available */ + NULL, /* text form not available */ commandTag, query_list, plan_list, @@ -131,8 +131,8 @@ ExecuteQuery(ExecuteStmt *stmt, DestReceiver *dest) if (entry->argtype_list != NIL) { /* - * Need an EState to evaluate parameters; must not delete it - * till end of query, in case parameters are pass-by-reference. + * Need an EState to evaluate parameters; must not delete it till + * end of query, in case parameters are pass-by-reference. */ estate = CreateExecutorState(); paramLI = EvaluateParams(estate, stmt->params, entry->argtype_list); @@ -144,15 +144,15 @@ ExecuteQuery(ExecuteStmt *stmt, DestReceiver *dest) portal = CreateNewPortal(); /* - * For CREATE TABLE / AS EXECUTE, make a copy of the stored query - * so that we can modify its destination (yech, but this has - * always been ugly). For regular EXECUTE we can just use the - * stored query where it sits, since the executor is read-only. + * For CREATE TABLE / AS EXECUTE, make a copy of the stored query so + * that we can modify its destination (yech, but this has always been + * ugly). For regular EXECUTE we can just use the stored query where + * it sits, since the executor is read-only. */ if (stmt->into) { MemoryContext oldContext; - Query *query; + Query *query; oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal)); @@ -208,11 +208,11 @@ ExecuteQuery(ExecuteStmt *stmt, DestReceiver *dest) static ParamListInfo EvaluateParams(EState *estate, List *params, List *argtypes) { - int nargs = length(argtypes); - ParamListInfo paramLI; - List *exprstates; - List *l; - int i = 0; + int nargs = length(argtypes); + ParamListInfo paramLI; + List *exprstates; + List *l; + int i = 0; /* Parser should have caught this error, but check for safety */ if (length(params) != nargs) @@ -229,7 +229,7 @@ EvaluateParams(EState *estate, List *params, List *argtypes) bool isNull; paramLI[i].value = ExecEvalExprSwitchContext(n, - GetPerTupleExprContext(estate), + GetPerTupleExprContext(estate), &isNull, NULL); paramLI[i].kind = PARAM_NUM; @@ -273,7 +273,7 @@ InitQueryHashTable(void) * to the hash entry, so the caller can dispose of their copy. * * Exception: commandTag is presumed to be a pointer to a constant string, - * or possibly NULL, so it need not be copied. Note that commandTag should + * or possibly NULL, so it need not be copied. Note that commandTag should * be NULL only if the original query (before rewriting) was empty. */ void @@ -367,9 +367,9 @@ FetchPreparedStatement(const char *stmt_name, bool throwError) if (prepared_queries) { /* - * We can't just use the statement name as supplied by the user: the - * hash package is picky enough that it needs to be NULL-padded out to - * the appropriate length to work correctly. + * We can't just use the statement name as supplied by the user: + * the hash package is picky enough that it needs to be + * NULL-padded out to the appropriate length to work correctly. */ MemSet(key, 0, sizeof(key)); strncpy(key, stmt_name, sizeof(key)); @@ -412,9 +412,9 @@ FetchPreparedStatementParams(const char *stmt_name) * Note: the result is created or copied into current memory context. */ TupleDesc -FetchPreparedStatementResultDesc(PreparedStatement *stmt) +FetchPreparedStatementResultDesc(PreparedStatement * stmt) { - Query *query; + Query *query; switch (ChoosePortalStrategy(stmt->query_list)) { @@ -476,7 +476,7 @@ DropPreparedStatement(const char *stmt_name, bool showError) void ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate) { - ExecuteStmt *execstmt = (ExecuteStmt *) stmt->query->utilityStmt; + ExecuteStmt *execstmt = (ExecuteStmt *) stmt->query->utilityStmt; PreparedStatement *entry; List *l, *query_list, @@ -499,8 +499,8 @@ ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate) if (entry->argtype_list != NIL) { /* - * Need an EState to evaluate parameters; must not delete it - * till end of query, in case parameters are pass-by-reference. + * Need an EState to evaluate parameters; must not delete it till + * end of query, in case parameters are pass-by-reference. */ estate = CreateExecutorState(); paramLI = EvaluateParams(estate, execstmt->params, @@ -510,8 +510,8 @@ ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate) /* Explain each query */ foreach(l, query_list) { - Query *query = (Query *) lfirst(l); - Plan *plan = (Plan *) lfirst(plan_list); + Query *query = (Query *) lfirst(l); + Plan *plan = (Plan *) lfirst(plan_list); bool is_last_query; plan_list = lnext(plan_list); @@ -533,7 +533,7 @@ ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate) if (query->commandType != CMD_SELECT) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("prepared statement is not a SELECT"))); + errmsg("prepared statement is not a SELECT"))); /* Copy the query so we can modify it */ query = copyObject(query); diff --git a/src/backend/commands/proclang.c b/src/backend/commands/proclang.c index 69000b29bc..b0a4702a71 100644 --- a/src/backend/commands/proclang.c +++ b/src/backend/commands/proclang.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/proclang.c,v 1.47 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/proclang.c,v 1.48 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -60,7 +60,7 @@ CreateProceduralLanguage(CreatePLangStmt *stmt) if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to create procedural language"))); + errmsg("must be superuser to create procedural language"))); /* * Translate the language name and check that this language doesn't @@ -85,7 +85,7 @@ CreateProceduralLanguage(CreatePLangStmt *stmt) if (funcrettype != LANGUAGE_HANDLEROID) { /* - * We allow OPAQUE just so we can load old dump files. When we + * We allow OPAQUE just so we can load old dump files. When we * see a handler function declared OPAQUE, change it to * LANGUAGE_HANDLER. */ @@ -183,7 +183,7 @@ DropProceduralLanguage(DropPLangStmt *stmt) if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to drop procedural language"))); + errmsg("must be superuser to drop procedural language"))); /* * Translate the language name, check that this language exist and is @@ -225,7 +225,7 @@ DropProceduralLanguageById(Oid langOid) langTup = SearchSysCache(LANGOID, ObjectIdGetDatum(langOid), 0, 0, 0); - if (!HeapTupleIsValid(langTup)) /* should not happen */ + if (!HeapTupleIsValid(langTup)) /* should not happen */ elog(ERROR, "cache lookup failed for language %u", langOid); simple_heap_delete(rel, &langTup->t_self); @@ -266,7 +266,7 @@ RenameLanguage(const char *oldname, const char *newname) if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to rename procedural language"))); + errmsg("must be superuser to rename procedural language"))); /* rename */ namestrcpy(&(((Form_pg_language) GETSTRUCT(tup))->lanname), newname); diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c index 5ad81634f4..4eb285daa3 100644 --- a/src/backend/commands/schemacmds.c +++ b/src/backend/commands/schemacmds.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/schemacmds.c,v 1.14 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/schemacmds.c,v 1.15 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -98,7 +98,7 @@ CreateSchemaCommand(CreateSchemaStmt *stmt) ereport(ERROR, (errcode(ERRCODE_RESERVED_NAME), errmsg("unacceptable schema name \"%s\"", schemaName), - errdetail("The prefix \"pg_\" is reserved for system schemas."))); + errdetail("The prefix \"pg_\" is reserved for system schemas."))); /* Create the schema's namespace */ namespaceId = NamespaceCreate(schemaName, owner_userid); @@ -215,7 +215,7 @@ RemoveSchemaById(Oid schemaOid) tup = SearchSysCache(NAMESPACEOID, ObjectIdGetDatum(schemaOid), 0, 0, 0); - if (!HeapTupleIsValid(tup)) /* should not happen */ + if (!HeapTupleIsValid(tup)) /* should not happen */ elog(ERROR, "cache lookup failed for namespace %u", schemaOid); simple_heap_delete(relation, &tup->t_self); @@ -248,9 +248,9 @@ RenameSchema(const char *oldname, const char *newname) /* make sure the new name doesn't exist */ if (HeapTupleIsValid( - SearchSysCache(NAMESPACENAME, - CStringGetDatum(newname), - 0, 0, 0))) + SearchSysCache(NAMESPACENAME, + CStringGetDatum(newname), + 0, 0, 0))) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_SCHEMA), errmsg("schema \"%s\" already exists", newname))); @@ -270,7 +270,7 @@ RenameSchema(const char *oldname, const char *newname) ereport(ERROR, (errcode(ERRCODE_RESERVED_NAME), errmsg("unacceptable schema name \"%s\"", newname), - errdetail("The prefix \"pg_\" is reserved for system schemas."))); + errdetail("The prefix \"pg_\" is reserved for system schemas."))); /* rename */ namestrcpy(&(((Form_pg_namespace) GETSTRUCT(tup))->nspname), newname); diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c index 7ce7810fbc..01544a015b 100644 --- a/src/backend/commands/sequence.c +++ b/src/backend/commands/sequence.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.99 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.100 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -68,7 +68,7 @@ static SeqTable seqtab = NULL; /* Head of list of SeqTable items */ static void init_sequence(RangeVar *relation, - SeqTable *p_elm, Relation *p_rel); + SeqTable *p_elm, Relation *p_rel); static Form_pg_sequence read_info(SeqTable elm, Relation rel, Buffer *buf); static void init_params(List *options, Form_pg_sequence new); static void do_setval(RangeVar *sequence, int64 next, bool iscalled); @@ -97,10 +97,10 @@ DefineSequence(CreateSeqStmt *seq) /* Values are NULL (or false) by default */ new.last_value = 0; new.increment_by = 0; - new.max_value = 0; + new.max_value = 0; new.min_value = 0; new.cache_value = 0; - new.is_cycled = false; + new.is_cycled = false; /* Check and set values */ init_params(seq->options, &new); @@ -299,10 +299,10 @@ DefineSequence(CreateSeqStmt *seq) /* * AlterSequence * - * Modify the defition of a sequence relation + * Modify the defition of a sequence relation */ void -AlterSequence(AlterSeqStmt *stmt) +AlterSequence(AlterSeqStmt * stmt) { SeqTable elm; Relation seqrel; @@ -324,7 +324,7 @@ AlterSequence(AlterSeqStmt *stmt) page = BufferGetPage(buf); new.increment_by = seq->increment_by; - new.max_value = seq->max_value; + new.max_value = seq->max_value; new.min_value = seq->min_value; new.cache_value = seq->cache_value; new.is_cycled = seq->is_cycled; @@ -346,9 +346,9 @@ AlterSequence(AlterSeqStmt *stmt) } /* save info in local cache */ - elm->last = new.last_value; /* last returned number */ - elm->cached = new.last_value; /* last cached number (forget cached - * values) */ + elm->last = new.last_value; /* last returned number */ + elm->cached = new.last_value; /* last cached number (forget + * cached values) */ START_CRIT_SECTION(); @@ -494,9 +494,9 @@ nextval(PG_FUNCTION_ARGS) snprintf(buf, sizeof(buf), INT64_FORMAT, maxv); ereport(ERROR, - (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("%s.nextval: reached MAXVALUE (%s)", - sequence->relname, buf))); + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("%s.nextval: reached MAXVALUE (%s)", + sequence->relname, buf))); } next = minv; } @@ -517,9 +517,9 @@ nextval(PG_FUNCTION_ARGS) snprintf(buf, sizeof(buf), INT64_FORMAT, minv); ereport(ERROR, - (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("%s.nextval: reached MINVALUE (%s)", - sequence->relname, buf))); + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("%s.nextval: reached MINVALUE (%s)", + sequence->relname, buf))); } next = maxv; } @@ -895,9 +895,9 @@ init_params(List *options, Form_pg_sequence new) errmsg("conflicting or redundant options"))); increment_by = defel; } + /* - * start is for a new sequence - * restart is for alter + * start is for a new sequence restart is for alter */ else if (strcmp(defel->defname, "start") == 0 || strcmp(defel->defname, "restart") == 0) @@ -963,9 +963,9 @@ init_params(List *options, Form_pg_sequence new) || (max_value != (DefElem *) NULL && !max_value->arg)) { if (new->increment_by > 0) - new->max_value = SEQ_MAXVALUE; /* ascending seq */ + new->max_value = SEQ_MAXVALUE; /* ascending seq */ else - new->max_value = -1; /* descending seq */ + new->max_value = -1; /* descending seq */ } else if (max_value != (DefElem *) NULL) new->max_value = defGetInt64(max_value); @@ -975,9 +975,9 @@ init_params(List *options, Form_pg_sequence new) || (min_value != (DefElem *) NULL && !min_value->arg)) { if (new->increment_by > 0) - new->min_value = 1; /* ascending seq */ + new->min_value = 1; /* ascending seq */ else - new->min_value = SEQ_MINVALUE; /* descending seq */ + new->min_value = SEQ_MINVALUE; /* descending seq */ } else if (min_value != (DefElem *) NULL) new->min_value = defGetInt64(min_value); @@ -996,7 +996,7 @@ init_params(List *options, Form_pg_sequence new) } /* START WITH */ - if (new->last_value == 0 && last_value == (DefElem *) NULL) + if (new->last_value == 0 && last_value == (DefElem *) NULL) { if (new->increment_by > 0) new->last_value = new->min_value; /* ascending seq */ @@ -1015,8 +1015,8 @@ init_params(List *options, Form_pg_sequence new) snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("START value (%s) can't be less than MINVALUE (%s)", - bufs, bufm))); + errmsg("START value (%s) can't be less than MINVALUE (%s)", + bufs, bufm))); } if (new->last_value > new->max_value) { @@ -1027,8 +1027,8 @@ init_params(List *options, Form_pg_sequence new) snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("START value (%s) can't be greater than MAXVALUE (%s)", - bufs, bufm))); + errmsg("START value (%s) can't be greater than MAXVALUE (%s)", + bufs, bufm))); } /* CACHE */ diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index b3108053d9..6e503fdac5 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/tablecmds.c,v 1.76 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/tablecmds.c,v 1.77 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -57,18 +57,19 @@ */ typedef struct OnCommitItem { - Oid relid; /* relid of relation */ - OnCommitAction oncommit; /* what to do at end of xact */ + Oid relid; /* relid of relation */ + OnCommitAction oncommit; /* what to do at end of xact */ /* * If this entry was created during this xact, it should be deleted at * xact abort. Conversely, if this entry was deleted during this * xact, it should be removed at xact commit. We leave deleted - * entries in the list until commit so that we can roll back if needed. + * entries in the list until commit so that we can roll back if + * needed. */ bool created_in_cur_xact; bool deleted_in_cur_xact; -} OnCommitItem; +} OnCommitItem; static List *on_commits = NIL; @@ -82,14 +83,14 @@ static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass); static bool needs_toast_table(Relation rel); static void AlterTableAddCheckConstraint(Relation rel, Constraint *constr); static void AlterTableAddForeignKeyConstraint(Relation rel, - FkConstraint *fkconstraint); + FkConstraint *fkconstraint); static int transformColumnNameList(Oid relId, List *colList, - int16 *attnums, Oid *atttypids); + int16 *attnums, Oid *atttypids); static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, - List **attnamelist, - int16 *attnums, Oid *atttypids); -static Oid transformFkeyCheckAttrs(Relation pkrel, - int numattrs, int16 *attnums); + List **attnamelist, + int16 *attnums, Oid *atttypids); +static Oid transformFkeyCheckAttrs(Relation pkrel, + int numattrs, int16 *attnums); static void validateForeignKeyConstraint(FkConstraint *fkconstraint, Relation rel, Relation pkrel); static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint, @@ -206,8 +207,8 @@ DefineRelation(CreateStmt *stmt, char relkind) if (strcmp(check[i].ccname, cdef->name) == 0) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("duplicate CHECK constraint name \"%s\"", - cdef->name))); + errmsg("duplicate CHECK constraint name \"%s\"", + cdef->name))); } check[ncheck].ccname = cdef->name; } @@ -399,7 +400,7 @@ TruncateRelation(const RangeVar *relation) if (isOtherTempNamespace(RelationGetNamespace(rel))) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot truncate temp tables of other processes"))); + errmsg("cannot truncate temp tables of other processes"))); /* * Don't allow truncate on tables which are referenced by foreign keys @@ -435,8 +436,8 @@ TruncateRelation(const RangeVar *relation) heap_close(fkeyRel, AccessShareLock); /* - * Do the real work using the same technique as cluster, but - * without the data-copying portion + * Do the real work using the same technique as cluster, but without + * the data-copying portion */ rebuild_relation(rel, InvalidOid); @@ -570,8 +571,8 @@ MergeAttributes(List *schema, List *supers, bool istemp, if (!istemp && isTempNamespace(RelationGetNamespace(relation))) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("cannot inherit from temporary relation \"%s\"", - parent->relname))); + errmsg("cannot inherit from temporary relation \"%s\"", + parent->relname))); /* * We should have an UNDER permission flag for this, but for now, @@ -652,7 +653,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, attributeName), errdetail("%s versus %s", TypeNameToString(def->typename), - format_type_be(attribute->atttypid)))); + format_type_be(attribute->atttypid)))); def->inhcount++; /* Merge of NOT NULL constraints = OR 'em together */ def->is_not_null |= attribute->attnotnull; @@ -803,11 +804,11 @@ MergeAttributes(List *schema, List *supers, bool istemp, def->typename->typmod != newdef->typename->typmod) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("attribute \"%s\" has a type conflict", - attributeName), + errmsg("attribute \"%s\" has a type conflict", + attributeName), errdetail("%s versus %s", TypeNameToString(def->typename), - TypeNameToString(newdef->typename)))); + TypeNameToString(newdef->typename)))); /* Mark the column as locally defined */ def->is_local = true; /* Merge of NOT NULL constraints = OR 'em together */ @@ -1230,8 +1231,8 @@ renameatt(Oid myrelid, 0, 0)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" already exists", - newattname, RelationGetRelationName(targetrelation)))); + errmsg("attribute \"%s\" of relation \"%s\" already exists", + newattname, RelationGetRelationName(targetrelation)))); namestrcpy(&(attform->attname), newattname); @@ -1257,7 +1258,7 @@ renameatt(Oid myrelid, /* * Scan through index columns to see if there's any simple index - * entries for this attribute. We ignore expressional entries. + * entries for this attribute. We ignore expressional entries. */ indextup = SearchSysCache(INDEXRELID, ObjectIdGetDatum(indexoid), @@ -1270,6 +1271,7 @@ renameatt(Oid myrelid, { if (attnum != indexform->indkey[i]) continue; + /* * Found one, rename it. */ @@ -1279,6 +1281,7 @@ renameatt(Oid myrelid, 0, 0); if (!HeapTupleIsValid(atttup)) continue; /* should we raise an error? */ + /* * Update the (copied) attribute tuple. */ @@ -1366,7 +1369,7 @@ renamerel(Oid myrelid, const char *newrelname) reltup = SearchSysCacheCopy(RELOID, PointerGetDatum(myrelid), 0, 0, 0); - if (!HeapTupleIsValid(reltup)) /* shouldn't happen */ + if (!HeapTupleIsValid(reltup)) /* shouldn't happen */ elog(ERROR, "cache lookup failed for relation %u", myrelid); if (get_relname_relid(newrelname, namespaceId) != InvalidOid) @@ -1743,7 +1746,7 @@ AlterTableAddColumn(Oid myrelid, ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("child table \"%s\" has different type for column \"%s\"", - get_rel_name(childrelid), colDef->colname))); + get_rel_name(childrelid), colDef->colname))); /* * XXX if we supported NOT NULL or defaults, would need to do @@ -1782,7 +1785,7 @@ AlterTableAddColumn(Oid myrelid, if (find_inheritance_children(myrelid) != NIL) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), - errmsg("attribute must be added to child tables too"))); + errmsg("attribute must be added to child tables too"))); } /* @@ -1801,14 +1804,14 @@ AlterTableAddColumn(Oid myrelid, if (colDef->raw_default || colDef->cooked_default) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("adding columns with defaults is not implemented"), - errhint("Add the column, then use ALTER TABLE SET DEFAULT."))); + errmsg("adding columns with defaults is not implemented"), + errhint("Add the column, then use ALTER TABLE SET DEFAULT."))); if (colDef->is_not_null) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("adding NOT NULL columns is not implemented"), - errhint("Add the column, then use ALTER TABLE SET NOT NULL."))); + errhint("Add the column, then use ALTER TABLE SET NOT NULL."))); pgclass = heap_openr(RelationRelationName, RowExclusiveLock); @@ -1829,8 +1832,8 @@ AlterTableAddColumn(Oid myrelid, 0, 0)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" already exists", - colDef->colname, RelationGetRelationName(rel)))); + errmsg("attribute \"%s\" of relation \"%s\" already exists", + colDef->colname, RelationGetRelationName(rel)))); minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts; maxatts = minattnum + 1; @@ -2014,8 +2017,8 @@ AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse, if (attnum == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - colName, RelationGetRelationName(rel)))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + colName, RelationGetRelationName(rel)))); /* Prevent them from altering a system attribute */ if (attnum < 0) @@ -2057,8 +2060,8 @@ AlterTableAlterColumnDropNotNull(Oid myrelid, bool recurse, if (indexStruct->indkey[i] == attnum) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), - errmsg("attribute \"%s\" is in a primary key", - colName))); + errmsg("attribute \"%s\" is in a primary key", + colName))); } } @@ -2158,8 +2161,8 @@ AlterTableAlterColumnSetNotNull(Oid myrelid, bool recurse, if (attnum == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - colName, RelationGetRelationName(rel)))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + colName, RelationGetRelationName(rel)))); /* Prevent them from altering a system attribute */ if (attnum < 0) @@ -2286,8 +2289,8 @@ AlterTableAlterColumnDefault(Oid myrelid, bool recurse, if (attnum == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - colName, RelationGetRelationName(rel)))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + colName, RelationGetRelationName(rel)))); /* Prevent them from altering a system attribute */ if (attnum < 0) @@ -2450,8 +2453,8 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse, if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - colName, RelationGetRelationName(rel)))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + colName, RelationGetRelationName(rel)))); attrtuple = (Form_pg_attribute) GETSTRUCT(tuple); if (attrtuple->attnum < 0) @@ -2476,8 +2479,8 @@ AlterTableAlterColumnFlags(Oid myrelid, bool recurse, else ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("column datatype %s can only have storage \"plain\"", - format_type_be(attrtuple->atttypid)))); + errmsg("column datatype %s can only have storage \"plain\"", + format_type_be(attrtuple->atttypid)))); } simple_heap_update(attrelation, &tuple->t_self, tuple); @@ -2573,7 +2576,7 @@ AlterTableAlterOids(Oid myrelid, bool recurse, bool setOid) (errmsg("table \"%s\" is already WITHOUT OIDS", RelationGetRelationName(rel)))); heap_close(class_rel, RowExclusiveLock); - heap_close(rel, NoLock); /* close rel, but keep lock! */ + heap_close(rel, NoLock); /* close rel, but keep lock! */ return; } @@ -2601,8 +2604,8 @@ AlterTableAlterOids(Oid myrelid, bool recurse, bool setOid) attrel = heap_open(RelOid_pg_attribute, RowExclusiveLock); /* - * Oids are being removed from the relation, so we need - * to remove the oid pg_attribute record relating. + * Oids are being removed from the relation, so we need to remove + * the oid pg_attribute record relating. */ atttup = SearchSysCache(ATTNUM, ObjectIdGetDatum(myrelid), @@ -2621,7 +2624,7 @@ AlterTableAlterOids(Oid myrelid, bool recurse, bool setOid) heap_close(class_rel, RowExclusiveLock); - heap_close(rel, NoLock); /* close rel, but keep lock! */ + heap_close(rel, NoLock); /* close rel, but keep lock! */ } /* @@ -2663,8 +2666,8 @@ AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing, if (attnum == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - colName, RelationGetRelationName(rel)))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + colName, RelationGetRelationName(rel)))); /* Can't drop a system attribute */ /* XXX perhaps someday allow dropping OID? */ @@ -2712,7 +2715,7 @@ AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing, colName, childrelid); childatt = (Form_pg_attribute) GETSTRUCT(tuple); - if (childatt->attinhcount <= 0) /* shouldn't happen */ + if (childatt->attinhcount <= 0) /* shouldn't happen */ elog(ERROR, "relation %u has non-inherited attribute \"%s\"", childrelid, colName); childatt->attinhcount--; @@ -2731,9 +2734,9 @@ AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing, } /* - * Propagate to children if desired. Unlike most other ALTER routines, - * we have to do this one level of recursion at a time; we can't use - * find_all_inheritors to do it in one pass. + * Propagate to children if desired. Unlike most other ALTER + * routines, we have to do this one level of recursion at a time; we + * can't use find_all_inheritors to do it in one pass. */ if (recurse) { @@ -2763,7 +2766,7 @@ AlterTableDropColumn(Oid myrelid, bool recurse, bool recursing, colName, childrelid); childatt = (Form_pg_attribute) GETSTRUCT(tuple); - if (childatt->attinhcount <= 0) /* shouldn't happen */ + if (childatt->attinhcount <= 0) /* shouldn't happen */ elog(ERROR, "relation %u has non-inherited attribute \"%s\"", childrelid, colName); @@ -2882,18 +2885,18 @@ AlterTableAddConstraint(Oid myrelid, bool recurse, { if (ConstraintNameIsUsed(CONSTRAINT_RELATION, RelationGetRelid(rel), - RelationGetNamespace(rel), + RelationGetNamespace(rel), constr->name)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("constraint \"%s\" for relation \"%s\" already exists", constr->name, - RelationGetRelationName(rel)))); + RelationGetRelationName(rel)))); } else constr->name = GenerateConstraintName(CONSTRAINT_RELATION, - RelationGetRelid(rel), - RelationGetNamespace(rel), + RelationGetRelid(rel), + RelationGetNamespace(rel), &counter); /* @@ -2923,14 +2926,14 @@ AlterTableAddConstraint(Oid myrelid, bool recurse, if (fkconstraint->constr_name) { if (ConstraintNameIsUsed(CONSTRAINT_RELATION, - RelationGetRelid(rel), + RelationGetRelid(rel), RelationGetNamespace(rel), fkconstraint->constr_name)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("constraint \"%s\" for relation \"%s\" already exists", fkconstraint->constr_name, - RelationGetRelationName(rel)))); + RelationGetRelationName(rel)))); } else fkconstraint->constr_name = GenerateConstraintName(CONSTRAINT_RELATION, @@ -2959,7 +2962,7 @@ AlterTableAddConstraint(Oid myrelid, bool recurse, /* * Add a check constraint to a single table * - * Subroutine for AlterTableAddConstraint. Must already hold exclusive + * Subroutine for AlterTableAddConstraint. Must already hold exclusive * lock on the rel, and have done appropriate validity/permissions checks * for it. */ @@ -2979,13 +2982,13 @@ AlterTableAddCheckConstraint(Relation rel, Constraint *constr) Node *expr; /* - * We need to make a parse state and range - * table to allow us to do transformExpr() + * We need to make a parse state and range table to allow us to do + * transformExpr() */ pstate = make_parsestate(NULL); rte = addRangeTableEntryForRelation(pstate, RelationGetRelid(rel), - makeAlias(RelationGetRelationName(rel), NIL), + makeAlias(RelationGetRelationName(rel), NIL), false, true); addRTEtoQuery(pstate, rte, true, true); @@ -3006,8 +3009,8 @@ AlterTableAddCheckConstraint(Relation rel, Constraint *constr) if (length(pstate->p_rtable) != 1) ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), - errmsg("CHECK constraint may only reference relation \"%s\"", - RelationGetRelationName(rel)))); + errmsg("CHECK constraint may only reference relation \"%s\"", + RelationGetRelationName(rel)))); /* * No subplans or aggregates, either... @@ -3070,15 +3073,13 @@ AlterTableAddCheckConstraint(Relation rel, Constraint *constr) if (!successful) ereport(ERROR, (errcode(ERRCODE_CHECK_VIOLATION), - errmsg("CHECK constraint \"%s\" is violated at some row(s)", - constr->name))); + errmsg("CHECK constraint \"%s\" is violated at some row(s)", + constr->name))); /* - * Call AddRelationRawConstraints to do - * the real adding -- It duplicates some - * of the above, but does not check the - * validity of the constraint against - * tuples already in the table. + * Call AddRelationRawConstraints to do the real adding -- It + * duplicates some of the above, but does not check the validity of + * the constraint against tuples already in the table. */ AddRelationRawConstraints(rel, NIL, makeList1(constr)); } @@ -3086,7 +3087,7 @@ AlterTableAddCheckConstraint(Relation rel, Constraint *constr) /* * Add a foreign-key constraint to a single table * - * Subroutine for AlterTableAddConstraint. Must already hold exclusive + * Subroutine for AlterTableAddConstraint. Must already hold exclusive * lock on the rel, and have done appropriate validity/permissions checks * for it. */ @@ -3106,12 +3107,11 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint) Oid constrOid; /* - * Grab an exclusive lock on the pk table, so that - * someone doesn't delete rows out from under us. - * (Although a lesser lock would do for that purpose, - * we'll need exclusive lock anyway to add triggers to - * the pk table; trying to start with a lesser lock - * will just create a risk of deadlock.) + * Grab an exclusive lock on the pk table, so that someone doesn't + * delete rows out from under us. (Although a lesser lock would do for + * that purpose, we'll need exclusive lock anyway to add triggers to + * the pk table; trying to start with a lesser lock will just create a + * risk of deadlock.) */ pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock); @@ -3152,8 +3152,8 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint) errmsg("cannot reference temporary table from permanent table constraint"))); /* - * Look up the referencing attributes to make sure they - * exist, and record their attnums and type OIDs. + * Look up the referencing attributes to make sure they exist, and + * record their attnums and type OIDs. */ for (i = 0; i < INDEX_MAX_KEYS; i++) { @@ -3166,10 +3166,10 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint) fkattnum, fktypoid); /* - * If the attribute list for the referenced table was omitted, - * lookup the definition of the primary key and use it. Otherwise, - * validate the supplied attribute list. In either case, discover - * the index OID and the attnums and type OIDs of the attributes. + * If the attribute list for the referenced table was omitted, lookup + * the definition of the primary key and use it. Otherwise, validate + * the supplied attribute list. In either case, discover the index + * OID and the attnums and type OIDs of the attributes. */ if (fkconstraint->pk_attrs == NIL) { @@ -3208,8 +3208,8 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint) } /* - * Check that the constraint is satisfied by existing - * rows (we can skip this during table creation). + * Check that the constraint is satisfied by existing rows (we can + * skip this during table creation). */ if (!fkconstraint->skip_validation) validateForeignKeyConstraint(fkconstraint, rel, pkrel); @@ -3225,7 +3225,8 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint) RelationGetRelid(rel), fkattnum, numfks, - InvalidOid, /* not a domain constraint */ + InvalidOid, /* not a domain + * constraint */ RelationGetRelid(pkrel), pkattnum, numpks, @@ -3233,7 +3234,7 @@ AlterTableAddForeignKeyConstraint(Relation rel, FkConstraint *fkconstraint) fkconstraint->fk_del_action, fkconstraint->fk_matchtype, indexOid, - NULL, /* no check constraint */ + NULL, /* no check constraint */ NULL, NULL); @@ -3276,8 +3277,8 @@ transformColumnNameList(Oid relId, List *colList, if (attnum >= INDEX_MAX_KEYS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_COLUMNS), - errmsg("cannot have more than %d keys in a foreign key", - INDEX_MAX_KEYS))); + errmsg("cannot have more than %d keys in a foreign key", + INDEX_MAX_KEYS))); attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum; atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid; ReleaseSysCache(atttuple); @@ -3291,7 +3292,7 @@ transformColumnNameList(Oid relId, List *colList, * transformFkeyGetPrimaryKey - * * Look up the names, attnums, and types of the primary key attributes - * for the pkrel. Used when the column list in the REFERENCES specification + * for the pkrel. Used when the column list in the REFERENCES specification * is omitted. */ static int @@ -3339,12 +3340,12 @@ transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, if (indexStruct == NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("there is no PRIMARY KEY for referenced table \"%s\"", - RelationGetRelationName(pkrel)))); + errmsg("there is no PRIMARY KEY for referenced table \"%s\"", + RelationGetRelationName(pkrel)))); /* - * Now build the list of PK attributes from the indkey definition - * (we assume a primary key cannot have expressional elements) + * Now build the list of PK attributes from the indkey definition (we + * assume a primary key cannot have expressional elements) */ *attnamelist = NIL; for (i = 0; i < indexStruct->indnatts; i++) @@ -3389,7 +3390,8 @@ transformFkeyCheckAttrs(Relation pkrel, { HeapTuple indexTuple; Form_pg_index indexStruct; - int i, j; + int i, + j; indexoid = lfirsto(indexoidscan); indexTuple = SearchSysCache(INDEXRELID, @@ -3453,7 +3455,7 @@ transformFkeyCheckAttrs(Relation pkrel, ereport(ERROR, (errcode(ERRCODE_INVALID_FOREIGN_KEY), errmsg("there is no UNIQUE constraint matching given keys for referenced table \"%s\"", - RelationGetRelationName(pkrel)))); + RelationGetRelationName(pkrel)))); freeList(indexoidlist); @@ -3969,17 +3971,17 @@ AlterTableOwner(Oid relationOid, int32 newOwnerSysId) void AlterTableClusterOn(Oid relOid, const char *indexName) { - Relation rel, - pg_index; - List *index; - Oid indexOid; - HeapTuple indexTuple; - Form_pg_index indexForm; - + Relation rel, + pg_index; + List *index; + Oid indexOid; + HeapTuple indexTuple; + Form_pg_index indexForm; + rel = heap_open(relOid, AccessExclusiveLock); indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace); - + if (!OidIsValid(indexOid)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), @@ -3994,36 +3996,37 @@ AlterTableClusterOn(Oid relOid, const char *indexName) indexForm = (Form_pg_index) GETSTRUCT(indexTuple); /* - * If this is the same index the relation was previously - * clustered on, no need to do anything. + * If this is the same index the relation was previously clustered on, + * no need to do anything. */ if (indexForm->indisclustered) { ereport(NOTICE, - (errmsg("table \"%s\" is already being clustered on index \"%s\"", - NameStr(rel->rd_rel->relname), indexName))); + (errmsg("table \"%s\" is already being clustered on index \"%s\"", + NameStr(rel->rd_rel->relname), indexName))); ReleaseSysCache(indexTuple); heap_close(rel, NoLock); return; } pg_index = heap_openr(IndexRelationName, RowExclusiveLock); - + /* * Now check each index in the relation and set the bit where needed. */ - foreach (index, RelationGetIndexList(rel)) + foreach(index, RelationGetIndexList(rel)) { - HeapTuple idxtuple; - Form_pg_index idxForm; - + HeapTuple idxtuple; + Form_pg_index idxForm; + indexOid = lfirsto(index); idxtuple = SearchSysCacheCopy(INDEXRELID, - ObjectIdGetDatum(indexOid), + ObjectIdGetDatum(indexOid), 0, 0, 0); if (!HeapTupleIsValid(idxtuple)) elog(ERROR, "cache lookup failed for index %u", indexOid); idxForm = (Form_pg_index) GETSTRUCT(idxtuple); + /* * Unset the bit if set. We know it's wrong because we checked * this earlier. @@ -4100,7 +4103,7 @@ AlterTableCreateToastTable(Oid relOid, bool silent) if (shared_relation && IsUnderPostmaster) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("shared relations cannot be toasted after initdb"))); + errmsg("shared relations cannot be toasted after initdb"))); /* * Is it already toasted? @@ -4331,12 +4334,12 @@ needs_toast_table(Relation rel) void register_on_commit_action(Oid relid, OnCommitAction action) { - OnCommitItem *oc; + OnCommitItem *oc; MemoryContext oldcxt; /* - * We needn't bother registering the relation unless there is an ON COMMIT - * action we need to take. + * We needn't bother registering the relation unless there is an ON + * COMMIT action we need to take. */ if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS) return; @@ -4366,7 +4369,7 @@ remove_on_commit_action(Oid relid) foreach(l, on_commits) { - OnCommitItem *oc = (OnCommitItem *) lfirst(l); + OnCommitItem *oc = (OnCommitItem *) lfirst(l); if (oc->relid == relid) { @@ -4389,7 +4392,7 @@ PreCommit_on_commit_actions(void) foreach(l, on_commits) { - OnCommitItem *oc = (OnCommitItem *) lfirst(l); + OnCommitItem *oc = (OnCommitItem *) lfirst(l); /* Ignore entry if already dropped in this xact */ if (oc->deleted_in_cur_xact) @@ -4403,23 +4406,25 @@ PreCommit_on_commit_actions(void) break; case ONCOMMIT_DELETE_ROWS: heap_truncate(oc->relid); - CommandCounterIncrement(); /* XXX needed? */ + CommandCounterIncrement(); /* XXX needed? */ break; case ONCOMMIT_DROP: - { - ObjectAddress object; + { + ObjectAddress object; - object.classId = RelOid_pg_class; - object.objectId = oc->relid; - object.objectSubId = 0; - performDeletion(&object, DROP_CASCADE); - /* - * Note that table deletion will call remove_on_commit_action, - * so the entry should get marked as deleted. - */ - Assert(oc->deleted_in_cur_xact); - break; - } + object.classId = RelOid_pg_class; + object.objectId = oc->relid; + object.objectSubId = 0; + performDeletion(&object, DROP_CASCADE); + + /* + * Note that table deletion will call + * remove_on_commit_action, so the entry should get + * marked as deleted. + */ + Assert(oc->deleted_in_cur_xact); + break; + } } } } @@ -4442,7 +4447,7 @@ AtEOXact_on_commit_actions(bool isCommit) l = on_commits; while (l != NIL) { - OnCommitItem *oc = (OnCommitItem *) lfirst(l); + OnCommitItem *oc = (OnCommitItem *) lfirst(l); if (isCommit ? oc->deleted_in_cur_xact : oc->created_in_cur_xact) diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c index 6e5b38804f..d3e969c7e4 100644 --- a/src/backend/commands/trigger.c +++ b/src/backend/commands/trigger.c @@ -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.153 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/trigger.c,v 1.154 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -41,17 +41,17 @@ static void InsertTrigger(TriggerDesc *trigdesc, Trigger *trigger, int indx); static HeapTuple GetTupleForTrigger(EState *estate, - ResultRelInfo *relinfo, - ItemPointer tid, - CommandId cid, - TupleTableSlot **newSlot); + ResultRelInfo *relinfo, + ItemPointer tid, + CommandId cid, + TupleTableSlot **newSlot); static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, FmgrInfo *finfo, MemoryContext per_tuple_context); static void DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, - bool row_trigger, HeapTuple oldtup, HeapTuple newtup); + bool row_trigger, HeapTuple oldtup, HeapTuple newtup); static void DeferredTriggerExecute(DeferredTriggerEvent event, int itemno, - Relation rel, TriggerDesc *trigdesc, FmgrInfo *finfo, + Relation rel, TriggerDesc *trigdesc, FmgrInfo *finfo, MemoryContext per_tuple_context); @@ -97,18 +97,19 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint) else if (stmt->isconstraint) { /* - * If this trigger is a constraint (and a foreign key one) - * then we really need a constrrelid. Since we don't have one, - * we'll try to generate one from the argument information. + * If this trigger is a constraint (and a foreign key one) then we + * really need a constrrelid. Since we don't have one, we'll try + * to generate one from the argument information. * - * This is really just a workaround for a long-ago pg_dump bug - * that omitted the FROM clause in dumped CREATE CONSTRAINT TRIGGER - * commands. We don't want to bomb out completely here if we can't - * determine the correct relation, because that would prevent loading - * the dump file. Instead, NOTICE here and ERROR in the trigger. + * This is really just a workaround for a long-ago pg_dump bug that + * omitted the FROM clause in dumped CREATE CONSTRAINT TRIGGER + * commands. We don't want to bomb out completely here if we + * can't determine the correct relation, because that would + * prevent loading the dump file. Instead, NOTICE here and ERROR + * in the trigger. */ - bool needconstrrelid = false; - void *elem = NULL; + bool needconstrrelid = false; + void *elem = NULL; if (strncmp(strVal(llast(stmt->funcname)), "RI_FKey_check_", 14) == 0) { @@ -265,8 +266,8 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint) if (namestrcmp(&(pg_trigger->tgname), trigname) == 0) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("trigger \"%s\" for relation \"%s\" already exists", - trigname, stmt->relation->relname))); + errmsg("trigger \"%s\" for relation \"%s\" already exists", + trigname, stmt->relation->relname))); found++; } systable_endscan(tgscan); @@ -280,7 +281,7 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint) if (funcrettype != TRIGGEROID) { /* - * We allow OPAQUE just so we can load old dump files. When we + * We allow OPAQUE just so we can load old dump files. When we * see a trigger function declared OPAQUE, change it to TRIGGER. */ if (funcrettype == OPAQUEOID) @@ -480,8 +481,8 @@ DropTrigger(Oid relid, const char *trigname, DropBehavior behavior) if (!HeapTupleIsValid(tup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("trigger \"%s\" for relation \"%s\" does not exist", - trigname, get_rel_name(relid)))); + errmsg("trigger \"%s\" for relation \"%s\" does not exist", + trigname, get_rel_name(relid)))); if (!pg_class_ownercheck(relid, GetUserId())) aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, @@ -576,7 +577,7 @@ RemoveTriggerById(Oid trigOid) elog(ERROR, "cache lookup failed for relation %u", relid); classForm = (Form_pg_class) GETSTRUCT(tuple); - if (classForm->reltriggers == 0) /* should not happen */ + if (classForm->reltriggers == 0) /* should not happen */ elog(ERROR, "relation \"%s\" has reltriggers = 0", RelationGetRelationName(rel)); classForm->reltriggers--; @@ -650,8 +651,8 @@ renametrig(Oid relid, if (HeapTupleIsValid(tuple = systable_getnext(tgscan))) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("trigger \"%s\" for relation \"%s\" already exists", - newname, RelationGetRelationName(targetrel)))); + errmsg("trigger \"%s\" for relation \"%s\" already exists", + newname, RelationGetRelationName(targetrel)))); systable_endscan(tgscan); /* @@ -693,8 +694,8 @@ renametrig(Oid relid, { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("trigger \"%s\" for relation \"%s\" does not exist", - oldname, RelationGetRelationName(targetrel)))); + errmsg("trigger \"%s\" for relation \"%s\" does not exist", + oldname, RelationGetRelationName(targetrel)))); } systable_endscan(tgscan); @@ -762,7 +763,7 @@ RelationBuildTriggers(Relation relation) build->tgoid = HeapTupleGetOid(htup); build->tgname = DatumGetCString(DirectFunctionCall1(nameout, - NameGetDatum(&pg_trigger->tgname))); + NameGetDatum(&pg_trigger->tgname))); build->tgfoid = pg_trigger->tgfoid; build->tgtype = pg_trigger->tgtype; build->tgenabled = pg_trigger->tgenabled; @@ -927,8 +928,8 @@ CopyTriggerDesc(TriggerDesc *trigdesc) trigger->tgname = pstrdup(trigger->tgname); if (trigger->tgnargs > 0) { - char **newargs; - int16 j; + char **newargs; + int16 j; newargs = (char **) palloc(trigger->tgnargs * sizeof(char *)); for (j = 0; j < trigger->tgnargs; j++) @@ -1101,7 +1102,7 @@ equalTriggerDescs(TriggerDesc *trigdesc1, TriggerDesc *trigdesc2) return false; return true; } -#endif /* NOT_USED */ +#endif /* NOT_USED */ /* * Call a trigger function. @@ -1166,10 +1167,10 @@ ExecCallTriggerFunc(TriggerData *trigdata, void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo) { - TriggerDesc *trigdesc; - int ntrigs; - int *tgindx; - int i; + TriggerDesc *trigdesc; + int ntrigs; + int *tgindx; + int i; TriggerData LocTriggerData; trigdesc = relinfo->ri_TrigDesc; @@ -1190,10 +1191,10 @@ ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo) LocTriggerData.type = T_TriggerData; LocTriggerData.tg_event = TRIGGER_EVENT_INSERT | - TRIGGER_EVENT_BEFORE; - LocTriggerData.tg_relation = relinfo->ri_RelationDesc; - LocTriggerData.tg_newtuple = NULL; - LocTriggerData.tg_trigtuple = NULL; + TRIGGER_EVENT_BEFORE; + LocTriggerData.tg_relation = relinfo->ri_RelationDesc; + LocTriggerData.tg_newtuple = NULL; + LocTriggerData.tg_trigtuple = NULL; for (i = 0; i < ntrigs; i++) { Trigger *trigger = &trigdesc->triggers[tgindx[i]]; @@ -1209,7 +1210,7 @@ ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo) if (newtuple) ereport(ERROR, (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("BEFORE STATEMENT trigger cannot return a value"))); + errmsg("BEFORE STATEMENT trigger cannot return a value"))); } } @@ -1242,8 +1243,8 @@ ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, LocTriggerData.type = T_TriggerData; LocTriggerData.tg_event = TRIGGER_EVENT_INSERT | - TRIGGER_EVENT_ROW | - TRIGGER_EVENT_BEFORE; + TRIGGER_EVENT_ROW | + TRIGGER_EVENT_BEFORE; LocTriggerData.tg_relation = relinfo->ri_RelationDesc; LocTriggerData.tg_newtuple = NULL; for (i = 0; i < ntrigs; i++) @@ -1279,10 +1280,10 @@ ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, void ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo) { - TriggerDesc *trigdesc; - int ntrigs; - int *tgindx; - int i; + TriggerDesc *trigdesc; + int ntrigs; + int *tgindx; + int i; TriggerData LocTriggerData; trigdesc = relinfo->ri_TrigDesc; @@ -1303,10 +1304,10 @@ ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo) LocTriggerData.type = T_TriggerData; LocTriggerData.tg_event = TRIGGER_EVENT_DELETE | - TRIGGER_EVENT_BEFORE; - LocTriggerData.tg_relation = relinfo->ri_RelationDesc; - LocTriggerData.tg_newtuple = NULL; - LocTriggerData.tg_trigtuple = NULL; + TRIGGER_EVENT_BEFORE; + LocTriggerData.tg_relation = relinfo->ri_RelationDesc; + LocTriggerData.tg_newtuple = NULL; + LocTriggerData.tg_trigtuple = NULL; for (i = 0; i < ntrigs; i++) { Trigger *trigger = &trigdesc->triggers[tgindx[i]]; @@ -1322,7 +1323,7 @@ ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo) if (newtuple) ereport(ERROR, (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("BEFORE STATEMENT trigger cannot return a value"))); + errmsg("BEFORE STATEMENT trigger cannot return a value"))); } } @@ -1361,8 +1362,8 @@ ExecBRDeleteTriggers(EState *estate, ResultRelInfo *relinfo, LocTriggerData.type = T_TriggerData; LocTriggerData.tg_event = TRIGGER_EVENT_DELETE | - TRIGGER_EVENT_ROW | - TRIGGER_EVENT_BEFORE; + TRIGGER_EVENT_ROW | + TRIGGER_EVENT_BEFORE; LocTriggerData.tg_relation = relinfo->ri_RelationDesc; LocTriggerData.tg_newtuple = NULL; for (i = 0; i < ntrigs; i++) @@ -1408,10 +1409,10 @@ ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo, void ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo) { - TriggerDesc *trigdesc; - int ntrigs; - int *tgindx; - int i; + TriggerDesc *trigdesc; + int ntrigs; + int *tgindx; + int i; TriggerData LocTriggerData; trigdesc = relinfo->ri_TrigDesc; @@ -1432,10 +1433,10 @@ ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo) LocTriggerData.type = T_TriggerData; LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE | - TRIGGER_EVENT_BEFORE; - LocTriggerData.tg_relation = relinfo->ri_RelationDesc; - LocTriggerData.tg_newtuple = NULL; - LocTriggerData.tg_trigtuple = NULL; + TRIGGER_EVENT_BEFORE; + LocTriggerData.tg_relation = relinfo->ri_RelationDesc; + LocTriggerData.tg_newtuple = NULL; + LocTriggerData.tg_trigtuple = NULL; for (i = 0; i < ntrigs; i++) { Trigger *trigger = &trigdesc->triggers[tgindx[i]]; @@ -1451,7 +1452,7 @@ ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo) if (newtuple) ereport(ERROR, (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("BEFORE STATEMENT trigger cannot return a value"))); + errmsg("BEFORE STATEMENT trigger cannot return a value"))); } } @@ -1498,8 +1499,8 @@ ExecBRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, LocTriggerData.type = T_TriggerData; LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE | - TRIGGER_EVENT_ROW | - TRIGGER_EVENT_BEFORE; + TRIGGER_EVENT_ROW | + TRIGGER_EVENT_BEFORE; LocTriggerData.tg_relation = relinfo->ri_RelationDesc; for (i = 0; i < ntrigs; i++) { @@ -1639,19 +1640,20 @@ ltrmark:; * ---------- */ -typedef struct DeferredTriggersData { - /* Internal data is held in a per-transaction memory context */ - MemoryContext deftrig_cxt; - /* ALL DEFERRED or ALL IMMEDIATE */ - bool deftrig_all_isset; - bool deftrig_all_isdeferred; - /* Per trigger state */ - List *deftrig_trigstates; - /* List of pending deferred triggers. Previous comment below */ - DeferredTriggerEvent deftrig_events; - DeferredTriggerEvent deftrig_events_imm; - DeferredTriggerEvent deftrig_event_tail; -} DeferredTriggersData; +typedef struct DeferredTriggersData +{ + /* Internal data is held in a per-transaction memory context */ + MemoryContext deftrig_cxt; + /* ALL DEFERRED or ALL IMMEDIATE */ + bool deftrig_all_isset; + bool deftrig_all_isdeferred; + /* Per trigger state */ + List *deftrig_trigstates; + /* List of pending deferred triggers. Previous comment below */ + DeferredTriggerEvent deftrig_events; + DeferredTriggerEvent deftrig_events_imm; + DeferredTriggerEvent deftrig_event_tail; +} DeferredTriggersData; /* ---------- * deftrig_events, deftrig_event_tail: @@ -1661,8 +1663,8 @@ typedef struct DeferredTriggersData { * Because this can grow pretty large, we don't use separate List nodes, * but instead thread the list through the dte_next fields of the member * nodes. Saves just a few bytes per entry, but that adds up. - * - * deftrig_events_imm holds the tail pointer as of the last + * + * deftrig_events_imm holds the tail pointer as of the last * deferredTriggerInvokeEvents call; we can use this to avoid rescanning * entries unnecessarily. It is NULL if deferredTriggerInvokeEvents * hasn't run since the last state change. @@ -1674,7 +1676,7 @@ typedef struct DeferredTriggersData { typedef DeferredTriggersData *DeferredTriggers; -static DeferredTriggers deferredTriggers; +static DeferredTriggers deferredTriggers; /* ---------- * deferredTriggerCheckState() @@ -1783,7 +1785,7 @@ deferredTriggerAddEvent(DeferredTriggerEvent event) */ static void DeferredTriggerExecute(DeferredTriggerEvent event, int itemno, - Relation rel, TriggerDesc *trigdesc, FmgrInfo *finfo, + Relation rel, TriggerDesc *trigdesc, FmgrInfo *finfo, MemoryContext per_tuple_context) { Oid tgoid = event->dte_item[itemno].dti_tgoid; @@ -1817,7 +1819,7 @@ DeferredTriggerExecute(DeferredTriggerEvent event, int itemno, */ LocTriggerData.type = T_TriggerData; LocTriggerData.tg_event = (event->dte_event & TRIGGER_EVENT_OPMASK) | - (event->dte_event & TRIGGER_EVENT_ROW); + (event->dte_event & TRIGGER_EVENT_ROW); LocTriggerData.tg_relation = rel; LocTriggerData.tg_trigger = NULL; @@ -1899,12 +1901,12 @@ deferredTriggerInvokeEvents(bool immediate_only) * are going to discard the whole event queue on return anyway, so no * need to bother with "retail" pfree's. * - * If immediate_only is true, we need only scan from where the end of - * the queue was at the previous deferredTriggerInvokeEvents call; - * any non-deferred events before that point are already fired. - * (But if the deferral state changes, we must reset the saved position - * to the beginning of the queue, so as to process all events once with - * the new states. See DeferredTriggerSetState.) + * If immediate_only is true, we need only scan from where the end of the + * queue was at the previous deferredTriggerInvokeEvents call; any + * non-deferred events before that point are already fired. (But if + * the deferral state changes, we must reset the saved position to the + * beginning of the queue, so as to process all events once with the + * new states. See DeferredTriggerSetState.) */ /* Make a per-tuple memory context for trigger function calls */ @@ -1916,9 +1918,9 @@ deferredTriggerInvokeEvents(bool immediate_only) ALLOCSET_DEFAULT_MAXSIZE); /* - * If immediate_only is true, then the only events that could need firing - * are those since deftrig_events_imm. (But if deftrig_events_imm is - * NULL, we must scan the entire list.) + * If immediate_only is true, then the only events that could need + * firing are those since deftrig_events_imm. (But if + * deftrig_events_imm is NULL, we must scan the entire list.) */ if (immediate_only && deferredTriggers->deftrig_events_imm != NULL) { @@ -1984,17 +1986,18 @@ deferredTriggerInvokeEvents(bool immediate_only) rel = heap_open(event->dte_relid, NoLock); /* - * Copy relation's trigger info so that we have a stable - * copy no matter what the called triggers do. + * Copy relation's trigger info so that we have a + * stable copy no matter what the called triggers do. */ trigdesc = CopyTriggerDesc(rel->trigdesc); - if (trigdesc == NULL) /* should not happen */ + if (trigdesc == NULL) /* should not happen */ elog(ERROR, "relation %u has no triggers", event->dte_relid); /* - * Allocate space to cache fmgr lookup info for triggers. + * Allocate space to cache fmgr lookup info for + * triggers. */ finfo = (FmgrInfo *) palloc0(trigdesc->numtriggers * sizeof(FmgrInfo)); @@ -2089,21 +2092,23 @@ void DeferredTriggerBeginXact(void) { /* - * This will be changed to a special context when - * the nested transactions project moves forward. + * This will be changed to a special context when the nested + * transactions project moves forward. */ MemoryContext cxt = TopTransactionContext; + deferredTriggers = (DeferredTriggers) MemoryContextAlloc(TopTransactionContext, - sizeof(DeferredTriggersData)); + sizeof(DeferredTriggersData)); /* * Create the per transaction memory context */ deferredTriggers->deftrig_cxt = AllocSetContextCreate(cxt, - "DeferredTriggerXact", - ALLOCSET_DEFAULT_MINSIZE, - ALLOCSET_DEFAULT_INITSIZE, - ALLOCSET_DEFAULT_MAXSIZE); + "DeferredTriggerXact", + ALLOCSET_DEFAULT_MINSIZE, + ALLOCSET_DEFAULT_INITSIZE, + ALLOCSET_DEFAULT_MAXSIZE); + /* * If unspecified, constraints default to IMMEDIATE, per SQL */ @@ -2174,7 +2179,7 @@ DeferredTriggerAbortXact(void) * Ignore call if we aren't in a transaction. */ if (deferredTriggers == NULL) - return; + return; /* * Forget everything we know about deferred triggers. @@ -2255,7 +2260,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt) if (strlen(cname) == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), - errmsg("unnamed constraints cannot be set explicitly"))); + errmsg("unnamed constraints cannot be set explicitly"))); /* * Setup to scan pg_trigger by tgconstrname ... @@ -2304,7 +2309,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt) if (!found) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("constraint \"%s\" does not exist", cname))); + errmsg("constraint \"%s\" does not exist", cname))); } heap_close(tgrel, AccessShareLock); @@ -2349,9 +2354,10 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt) * CONSTRAINTS command applies retroactively. This happens "for free" * since we have already made the necessary modifications to the * constraints, and deferredTriggerEndQuery() is called by - * finish_xact_command(). But we must reset deferredTriggerInvokeEvents' - * tail pointer to make it rescan the entire list, in case some deferred - * events are now immediately invokable. + * finish_xact_command(). But we must reset + * deferredTriggerInvokeEvents' tail pointer to make it rescan the + * entire list, in case some deferred events are now immediately + * invokable. */ deferredTriggers->deftrig_events_imm = NULL; } @@ -2416,7 +2422,7 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, bool row_trigger, */ for (i = 0; i < ntriggers; i++) { - Trigger *trigger = &trigdesc->triggers[tgindx[i]]; + Trigger *trigger = &trigdesc->triggers[tgindx[i]]; if (trigger->tgenabled) n_enabled_triggers++; @@ -2455,7 +2461,7 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, bool row_trigger, ev_item = &(new_event->dte_item[i]); ev_item->dti_tgoid = trigger->tgoid; - ev_item->dti_state = + ev_item->dti_state = ((trigger->tgdeferrable) ? TRIGGER_DEFERRED_DEFERRABLE : 0) | ((trigger->tginitdeferred) ? @@ -2464,9 +2470,7 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, bool row_trigger, if (row_trigger && (trigdesc->n_before_row[event] > 0)) ev_item->dti_state |= TRIGGER_DEFERRED_HAS_BEFORE; else if (!row_trigger && (trigdesc->n_before_statement[event] > 0)) - { ev_item->dti_state |= TRIGGER_DEFERRED_HAS_BEFORE; - } } MemoryContextSwitchTo(oldcxt); diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c index 275143c151..57bc7c5f71 100644 --- a/src/backend/commands/typecmds.c +++ b/src/backend/commands/typecmds.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/typecmds.c,v 1.40 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/typecmds.c,v 1.41 2003/08/04 00:43:17 momjian Exp $ * * DESCRIPTION * The "DefineFoo" routines take the parse tree and pick out the @@ -66,11 +66,11 @@ /* result structure for get_rels_with_domain() */ typedef struct { - Relation rel; /* opened and locked relation */ - int natts; /* number of attributes of interest */ - int *atts; /* attribute numbers */ + Relation rel; /* opened and locked relation */ + int natts; /* number of attributes of interest */ + int *atts; /* attribute numbers */ /* atts[] is of allocated length RelationGetNumberOfAttributes(rel) */ -} RelToCheck; +} RelToCheck; static Oid findTypeInputFunction(List *procname, Oid typeOid); @@ -80,9 +80,9 @@ static Oid findTypeSendFunction(List *procname, Oid typeOid); static List *get_rels_with_domain(Oid domainOid, LOCKMODE lockmode); static void domainOwnerCheck(HeapTuple tup, TypeName *typename); static char *domainAddConstraint(Oid domainOid, Oid domainNamespace, - Oid baseTypeOid, - int typMod, Constraint *constr, - int *counter, char *domainName); + Oid baseTypeOid, + int typMod, Constraint *constr, + int *counter, char *domainName); /* @@ -105,7 +105,7 @@ DefineType(List *names, List *parameters) bool byValue = false; char delimiter = DEFAULT_TYPDELIM; char alignment = 'i'; /* default alignment */ - char storage = 'p'; /* default TOAST storage method */ + char storage = 'p'; /* default TOAST storage method */ Oid inputOid; Oid outputOid; Oid receiveOid = InvalidOid; @@ -237,8 +237,8 @@ DefineType(List *names, List *parameters) /* * Look to see if type already exists (presumably as a shell; if not, - * TypeCreate will complain). If it doesn't, create it as a shell, - * so that the OID is known for use in the I/O function definitions. + * TypeCreate will complain). If it doesn't, create it as a shell, so + * that the OID is known for use in the I/O function definitions. */ typoid = GetSysCacheOid(TYPENAMENSP, CStringGetDatum(typeName), @@ -492,7 +492,7 @@ DefineDomain(CreateDomainStmt *stmt) List *listptr; Oid basetypeoid; Oid domainoid; - Form_pg_type baseType; + Form_pg_type baseType; int counter = 0; /* Convert list of names to a name and namespace */ @@ -508,10 +508,11 @@ DefineDomain(CreateDomainStmt *stmt) /* * Domainnames, unlike typenames don't need to account for the '_' - * prefix. So they can be one character longer. (This test is presently - * useless since the parser will have truncated the name to fit. But - * leave it here since we may someday support arrays of domains, in - * which case we'll be back to needing to enforce NAMEDATALEN-2.) + * prefix. So they can be one character longer. (This test is + * presently useless since the parser will have truncated the name to + * fit. But leave it here since we may someday support arrays of + * domains, in which case we'll be back to needing to enforce + * NAMEDATALEN-2.) */ if (strlen(domainName) > (NAMEDATALEN - 1)) ereport(ERROR, @@ -581,8 +582,8 @@ DefineDomain(CreateDomainStmt *stmt) basetypelem = baseType->typelem; /* - * Run through constraints manually to avoid the additional - * processing conducted by DefineRelation() and friends. + * Run through constraints manually to avoid the additional processing + * conducted by DefineRelation() and friends. */ foreach(listptr, schema) { @@ -594,7 +595,7 @@ DefineDomain(CreateDomainStmt *stmt) if (IsA(newConstraint, FkConstraint)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("FOREIGN KEY constraints not supported for domains"))); + errmsg("FOREIGN KEY constraints not supported for domains"))); /* otherwise it should be a plain Constraint */ if (!IsA(newConstraint, Constraint)) @@ -606,6 +607,7 @@ DefineDomain(CreateDomainStmt *stmt) switch (constr->contype) { case CONSTR_DEFAULT: + /* * The inherited default value may be overridden by the * user with the DEFAULT statement. @@ -643,7 +645,7 @@ DefineDomain(CreateDomainStmt *stmt) if (nullDefined && !typNotNull) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("conflicting NULL/NOT NULL constraints"))); + errmsg("conflicting NULL/NOT NULL constraints"))); typNotNull = true; nullDefined = true; break; @@ -652,41 +654,42 @@ DefineDomain(CreateDomainStmt *stmt) if (nullDefined && typNotNull) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("conflicting NULL/NOT NULL constraints"))); + errmsg("conflicting NULL/NOT NULL constraints"))); typNotNull = false; nullDefined = true; - break; + break; + + case CONSTR_CHECK: - case CONSTR_CHECK: /* - * Check constraints are handled after domain creation, as they - * require the Oid of the domain + * Check constraints are handled after domain creation, as + * they require the Oid of the domain */ - break; + break; /* * All else are error cases */ - case CONSTR_UNIQUE: - ereport(ERROR, + case CONSTR_UNIQUE: + ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("UNIQUE constraints not supported for domains"))); - break; + errmsg("UNIQUE constraints not supported for domains"))); + break; - case CONSTR_PRIMARY: - ereport(ERROR, + case CONSTR_PRIMARY: + ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("PRIMARY KEY constraints not supported for domains"))); - break; + break; - case CONSTR_ATTR_DEFERRABLE: - case CONSTR_ATTR_NOT_DEFERRABLE: - case CONSTR_ATTR_DEFERRED: - case CONSTR_ATTR_IMMEDIATE: - ereport(ERROR, + case CONSTR_ATTR_DEFERRABLE: + case CONSTR_ATTR_NOT_DEFERRABLE: + case CONSTR_ATTR_DEFERRED: + case CONSTR_ATTR_IMMEDIATE: + ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("deferrability constraints not supported for domains"))); - break; + break; default: elog(ERROR, "unrecognized constraint subtype: %d", @@ -715,15 +718,16 @@ DefineDomain(CreateDomainStmt *stmt) basetypeoid, /* base type ID */ defaultValue, /* default type value (text) */ defaultValueBin, /* default type value (binary) */ - byValue, /* passed by value */ - alignment, /* required alignment */ - storage, /* TOAST strategy */ - stmt->typename->typmod, /* typeMod value */ - typNDims, /* Array dimensions for base type */ - typNotNull); /* Type NOT NULL */ + byValue, /* passed by value */ + alignment, /* required alignment */ + storage, /* TOAST strategy */ + stmt->typename->typmod, /* typeMod value */ + typNDims, /* Array dimensions for base type */ + typNotNull); /* Type NOT NULL */ /* - * Process constraints which refer to the domain ID returned by TypeCreate + * Process constraints which refer to the domain ID returned by + * TypeCreate */ foreach(listptr, schema) { @@ -733,16 +737,16 @@ DefineDomain(CreateDomainStmt *stmt) switch (constr->contype) { - case CONSTR_CHECK: + case CONSTR_CHECK: domainAddConstraint(domainoid, domainNamespace, basetypeoid, stmt->typename->typmod, constr, &counter, domainName); - break; + break; - /* Other constraint types were fully processed above */ + /* Other constraint types were fully processed above */ default: - break; + break; } } @@ -834,8 +838,8 @@ findTypeInputFunction(List *procname, Oid typeOid) * Input functions can take a single argument of type CSTRING, or * three arguments (string, element OID, typmod). * - * For backwards compatibility we allow OPAQUE in place of CSTRING; - * if we see this, we issue a NOTICE and fix up the pg_proc entry. + * For backwards compatibility we allow OPAQUE in place of CSTRING; if we + * see this, we issue a NOTICE and fix up the pg_proc entry. */ MemSet(argList, 0, FUNC_MAX_ARGS * sizeof(Oid)); @@ -874,9 +878,10 @@ findTypeInputFunction(List *procname, Oid typeOid) (errmsg("changing argument type of function %s from OPAQUE to CSTRING", NameListToString(procname)))); SetFunctionArgType(procOid, 0, CSTRINGOID); + /* - * Need CommandCounterIncrement since DefineType will likely - * try to alter the pg_proc tuple again. + * Need CommandCounterIncrement since DefineType will likely try + * to alter the pg_proc tuple again. */ CommandCounterIncrement(); @@ -905,8 +910,8 @@ findTypeOutputFunction(List *procname, Oid typeOid) * arguments (data value, element OID). * * For backwards compatibility we allow OPAQUE in place of the actual - * type name; if we see this, we issue a NOTICE and fix up the - * pg_proc entry. + * type name; if we see this, we issue a NOTICE and fix up the pg_proc + * entry. */ MemSet(argList, 0, FUNC_MAX_ARGS * sizeof(Oid)); @@ -940,12 +945,13 @@ findTypeOutputFunction(List *procname, Oid typeOid) { /* Found, but must complain and fix the pg_proc entry */ ereport(NOTICE, - (errmsg("changing argument type of function %s from OPAQUE to %s", - NameListToString(procname), format_type_be(typeOid)))); + (errmsg("changing argument type of function %s from OPAQUE to %s", + NameListToString(procname), format_type_be(typeOid)))); SetFunctionArgType(procOid, 0, typeOid); + /* - * Need CommandCounterIncrement since DefineType will likely - * try to alter the pg_proc tuple again. + * Need CommandCounterIncrement since DefineType will likely try + * to alter the pg_proc tuple again. */ CommandCounterIncrement(); @@ -1050,7 +1056,7 @@ DefineCompositeType(const RangeVar *typevar, List *coldeflist) if (coldeflist == NIL) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("composite type must have at least one attribute"))); + errmsg("composite type must have at least one attribute"))); /* * now create the parameters for keys/inheritance etc. All of them are @@ -1072,7 +1078,7 @@ DefineCompositeType(const RangeVar *typevar, List *coldeflist) /* * AlterDomainDefault * - * Routine implementing ALTER DOMAIN SET/DROP DEFAULT statements. + * Routine implementing ALTER DOMAIN SET/DROP DEFAULT statements. */ void AlterDomainDefault(List *names, Node *defaultRaw) @@ -1083,12 +1089,12 @@ AlterDomainDefault(List *names, Node *defaultRaw) ParseState *pstate; Relation rel; char *defaultValue; - Node *defaultExpr = NULL; /* NULL if no default specified */ + Node *defaultExpr = NULL; /* NULL if no default specified */ Datum new_record[Natts_pg_type]; char new_record_nulls[Natts_pg_type]; char new_record_repl[Natts_pg_type]; HeapTuple newtuple; - Form_pg_type typTup; + Form_pg_type typTup; /* Make a TypeName so we can use standard type lookup machinery */ typename = makeNode(TypeName); @@ -1113,7 +1119,7 @@ AlterDomainDefault(List *names, Node *defaultRaw) if (!HeapTupleIsValid(tup)) elog(ERROR, "cache lookup failed for type %u", domainoid); - /* Doesn't return if user isn't allowed to alter the domain */ + /* Doesn't return if user isn't allowed to alter the domain */ domainOwnerCheck(tup, typename); /* Setup new tuple */ @@ -1129,9 +1135,10 @@ AlterDomainDefault(List *names, Node *defaultRaw) { /* Create a dummy ParseState for transformExpr */ pstate = make_parsestate(NULL); + /* - * Cook the colDef->raw_expr into an expression. Note: - * Name is strictly for error message + * Cook the colDef->raw_expr into an expression. Note: Name is + * strictly for error message */ defaultExpr = cookDefault(pstate, defaultRaw, typTup->typbasetype, @@ -1139,27 +1146,29 @@ AlterDomainDefault(List *names, Node *defaultRaw) NameStr(typTup->typname)); /* - * Expression must be stored as a nodeToString result, but - * we also require a valid textual representation (mainly - * to make life easier for pg_dump). + * Expression must be stored as a nodeToString result, but we also + * require a valid textual representation (mainly to make life + * easier for pg_dump). */ defaultValue = deparse_expression(defaultExpr, - deparse_context_for(NameStr(typTup->typname), - InvalidOid), + deparse_context_for(NameStr(typTup->typname), + InvalidOid), false, false); + /* * Form an updated tuple with the new default and write it back. */ new_record[Anum_pg_type_typdefaultbin - 1] = DirectFunctionCall1(textin, - CStringGetDatum( - nodeToString(defaultExpr))); + CStringGetDatum( + nodeToString(defaultExpr))); new_record_repl[Anum_pg_type_typdefaultbin - 1] = 'r'; new_record[Anum_pg_type_typdefault - 1] = DirectFunctionCall1(textin, - CStringGetDatum(defaultValue)); + CStringGetDatum(defaultValue)); new_record_repl[Anum_pg_type_typdefault - 1] = 'r'; } - else /* Default is NULL, drop it */ + else +/* Default is NULL, drop it */ { new_record_nulls[Anum_pg_type_typdefaultbin - 1] = 'n'; new_record_repl[Anum_pg_type_typdefaultbin - 1] = 'r'; @@ -1168,7 +1177,7 @@ AlterDomainDefault(List *names, Node *defaultRaw) } newtuple = heap_modifytuple(tup, rel, - new_record, new_record_nulls, new_record_repl); + new_record, new_record_nulls, new_record_repl); simple_heap_update(rel, &tup->t_self, newtuple); @@ -1178,7 +1187,7 @@ AlterDomainDefault(List *names, Node *defaultRaw) GenerateTypeDependencies(typTup->typnamespace, domainoid, typTup->typrelid, - 0, /* relation kind is n/a */ + 0, /* relation kind is n/a */ typTup->typinput, typTup->typoutput, typTup->typreceive, @@ -1186,7 +1195,7 @@ AlterDomainDefault(List *names, Node *defaultRaw) typTup->typelem, typTup->typbasetype, defaultExpr, - true); /* Rebuild is true */ + true); /* Rebuild is true */ /* Clean up */ heap_close(rel, NoLock); @@ -1196,7 +1205,7 @@ AlterDomainDefault(List *names, Node *defaultRaw) /* * AlterDomainNotNull * - * Routine implementing ALTER DOMAIN SET/DROP NOT NULL statements. + * Routine implementing ALTER DOMAIN SET/DROP NOT NULL statements. */ void AlterDomainNotNull(List *names, bool notNull) @@ -1205,7 +1214,7 @@ AlterDomainNotNull(List *names, bool notNull) Oid domainoid; Relation typrel; HeapTuple tup; - Form_pg_type typTup; + Form_pg_type typTup; /* Make a TypeName so we can use standard type lookup machinery */ typename = makeNode(TypeName); @@ -1231,7 +1240,7 @@ AlterDomainNotNull(List *names, bool notNull) elog(ERROR, "cache lookup failed for type %u", domainoid); typTup = (Form_pg_type) GETSTRUCT(tup); - /* Doesn't return if user isn't allowed to alter the domain */ + /* Doesn't return if user isn't allowed to alter the domain */ domainOwnerCheck(tup, typename); /* Is the domain already set to the desired constraint? */ @@ -1248,15 +1257,15 @@ AlterDomainNotNull(List *names, bool notNull) /* Adding a NOT NULL constraint requires checking existing columns */ if (notNull) { - List *rels; - List *rt; + List *rels; + List *rt; /* Fetch relation list with attributes based on this domain */ /* ShareLock is sufficient to prevent concurrent data changes */ rels = get_rels_with_domain(domainoid, ShareLock); - foreach (rt, rels) + foreach(rt, rels) { RelToCheck *rtc = (RelToCheck *) lfirst(rt); Relation testrel = rtc->rel; @@ -1268,14 +1277,14 @@ AlterDomainNotNull(List *names, bool notNull) scan = heap_beginscan(testrel, SnapshotNow, 0, NULL); while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) { - int i; + int i; /* Test attributes that are of the domain */ for (i = 0; i < rtc->natts; i++) { - int attnum = rtc->atts[i]; - Datum d; - bool isNull; + int attnum = rtc->atts[i]; + Datum d; + bool isNull; d = heap_getattr(tuple, attnum, tupdesc, &isNull); @@ -1284,7 +1293,7 @@ AlterDomainNotNull(List *names, bool notNull) (errcode(ERRCODE_NOT_NULL_VIOLATION), errmsg("relation \"%s\" attribute \"%s\" contains NULL values", RelationGetRelationName(testrel), - NameStr(tupdesc->attrs[attnum - 1]->attname)))); + NameStr(tupdesc->attrs[attnum - 1]->attname)))); } } heap_endscan(scan); @@ -1295,7 +1304,7 @@ AlterDomainNotNull(List *names, bool notNull) } /* - * Okay to update pg_type row. We can scribble on typTup because it's + * Okay to update pg_type row. We can scribble on typTup because it's * a copy. */ typTup->typnotnull = notNull; @@ -1321,7 +1330,7 @@ AlterDomainDropConstraint(List *names, const char *constrName, DropBehavior beha Oid domainoid; HeapTuple tup; Relation rel; - Form_pg_type typTup; + Form_pg_type typTup; Relation conrel; SysScanDesc conscan; ScanKeyData key[1]; @@ -1350,7 +1359,7 @@ AlterDomainDropConstraint(List *names, const char *constrName, DropBehavior beha if (!HeapTupleIsValid(tup)) elog(ERROR, "cache lookup failed for type %u", domainoid); - /* Doesn't return if user isn't allowed to alter the domain */ + /* Doesn't return if user isn't allowed to alter the domain */ domainOwnerCheck(tup, typename); /* Grab an appropriate lock on the pg_constraint relation */ @@ -1403,15 +1412,15 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) Oid domainoid; Relation typrel; HeapTuple tup; - Form_pg_type typTup; - List *rels; - List *rt; - EState *estate; + Form_pg_type typTup; + List *rels; + List *rt; + EState *estate; ExprContext *econtext; - char *ccbin; - Expr *expr; - ExprState *exprstate; - int counter = 0; + char *ccbin; + Expr *expr; + ExprState *exprstate; + int counter = 0; Constraint *constr; /* Make a TypeName so we can use standard type lookup machinery */ @@ -1438,14 +1447,14 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) elog(ERROR, "cache lookup failed for type %u", domainoid); typTup = (Form_pg_type) GETSTRUCT(tup); - /* Doesn't return if user isn't allowed to alter the domain */ + /* Doesn't return if user isn't allowed to alter the domain */ domainOwnerCheck(tup, typename); /* Check for unsupported constraint types */ if (IsA(newConstraint, FkConstraint)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("FOREIGN KEY constraints not supported for domains"))); + errmsg("FOREIGN KEY constraints not supported for domains"))); /* otherwise it should be a plain Constraint */ if (!IsA(newConstraint, Constraint)) @@ -1469,20 +1478,20 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) errmsg("use ALTER DOMAIN .. [ SET | DROP ] NOT NULL instead"))); break; - case CONSTR_CHECK: + case CONSTR_CHECK: /* processed below */ - break; + break; case CONSTR_UNIQUE: ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("UNIQUE constraints not supported for domains"))); + errmsg("UNIQUE constraints not supported for domains"))); break; case CONSTR_PRIMARY: ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("PRIMARY KEY constraints not supported for domains"))); + errmsg("PRIMARY KEY constraints not supported for domains"))); break; case CONSTR_ATTR_DEFERRABLE: @@ -1501,18 +1510,18 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) } /* - * Since all other constraint types throw errors, this must be - * a check constraint. First, process the constraint expression - * and add an entry to pg_constraint. + * Since all other constraint types throw errors, this must be a check + * constraint. First, process the constraint expression and add an + * entry to pg_constraint. */ ccbin = domainAddConstraint(HeapTupleGetOid(tup), typTup->typnamespace, typTup->typbasetype, typTup->typtypmod, - constr, &counter, NameStr(typTup->typname)); + constr, &counter, NameStr(typTup->typname)); /* - * Test all values stored in the attributes based on the domain - * the constraint is being added to. + * Test all values stored in the attributes based on the domain the + * constraint is being added to. */ expr = (Expr *) stringToNode(ccbin); @@ -1528,7 +1537,7 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) rels = get_rels_with_domain(domainoid, ShareLock); - foreach (rt, rels) + foreach(rt, rels) { RelToCheck *rtc = (RelToCheck *) lfirst(rt); Relation testrel = rtc->rel; @@ -1540,15 +1549,15 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) scan = heap_beginscan(testrel, SnapshotNow, 0, NULL); while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) { - int i; + int i; /* Test attributes that are of the domain */ for (i = 0; i < rtc->natts; i++) { - int attnum = rtc->atts[i]; - Datum d; - bool isNull; - Datum conResult; + int attnum = rtc->atts[i]; + Datum d; + bool isNull; + Datum conResult; d = heap_getattr(tuple, attnum, tupdesc, &isNull); @@ -1564,7 +1573,7 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) (errcode(ERRCODE_CHECK_VIOLATION), errmsg("relation \"%s\" attribute \"%s\" contains values that violate the new constraint", RelationGetRelationName(testrel), - NameStr(tupdesc->attrs[attnum - 1]->attname)))); + NameStr(tupdesc->attrs[attnum - 1]->attname)))); } ResetExprContext(econtext); @@ -1610,7 +1619,7 @@ AlterDomainAddConstraint(List *names, Node *newConstraint) static List * get_rels_with_domain(Oid domainOid, LOCKMODE lockmode) { - List *result = NIL; + List *result = NIL; Relation depRel; ScanKeyData key[2]; SysScanDesc depScan; @@ -1634,10 +1643,10 @@ get_rels_with_domain(Oid domainOid, LOCKMODE lockmode) while (HeapTupleIsValid(depTup = systable_getnext(depScan))) { - Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup); + Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup); RelToCheck *rtc = NULL; List *rellist; - Form_pg_attribute pg_att; + Form_pg_attribute pg_att; int ptr; /* Ignore dependees that aren't user columns of tables */ @@ -1675,10 +1684,10 @@ get_rels_with_domain(Oid domainOid, LOCKMODE lockmode) } /* - * Confirm column has not been dropped, and is of the expected type. - * This defends against an ALTER DROP COLUMN occuring just before - * we acquired lock ... but if the whole table were dropped, we'd - * still have a problem. + * Confirm column has not been dropped, and is of the expected + * type. This defends against an ALTER DROP COLUMN occuring just + * before we acquired lock ... but if the whole table were + * dropped, we'd still have a problem. */ if (pg_depend->objsubid > RelationGetNumberOfAttributes(rtc->rel)) continue; @@ -1687,16 +1696,16 @@ get_rels_with_domain(Oid domainOid, LOCKMODE lockmode) continue; /* - * Okay, add column to result. We store the columns in column-number - * order; this is just a hack to improve predictability of regression - * test output ... + * Okay, add column to result. We store the columns in + * column-number order; this is just a hack to improve + * predictability of regression test output ... */ Assert(rtc->natts < RelationGetNumberOfAttributes(rtc->rel)); ptr = rtc->natts++; - while (ptr > 0 && rtc->atts[ptr-1] > pg_depend->objsubid) + while (ptr > 0 && rtc->atts[ptr - 1] > pg_depend->objsubid) { - rtc->atts[ptr] = rtc->atts[ptr-1]; + rtc->atts[ptr] = rtc->atts[ptr - 1]; ptr--; } rtc->atts[ptr] = pg_depend->objsubid; @@ -1719,7 +1728,7 @@ get_rels_with_domain(Oid domainOid, LOCKMODE lockmode) static void domainOwnerCheck(HeapTuple tup, TypeName *typename) { - Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup); + Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup); /* Check that this is actually a domain */ if (typTup->typtype != 'd') @@ -1746,7 +1755,7 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid, char *ccsrc; char *ccbin; ParseState *pstate; - CoerceToDomainValue *domVal; + CoerceToDomainValue *domVal; /* * Assign or validate constraint name @@ -1759,8 +1768,8 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid, constr->name)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("constraint \"%s\" for domain \"%s\" already exists", - constr->name, domainName))); + errmsg("constraint \"%s\" for domain \"%s\" already exists", + constr->name, domainName))); } else constr->name = GenerateConstraintName(CONSTRAINT_DOMAIN, @@ -1775,10 +1784,10 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid, /* * Set up a CoerceToDomainValue to represent the occurrence of VALUE - * in the expression. Note that it will appear to have the type of the - * base type, not the domain. This seems correct since within the - * check expression, we should not assume the input value can be considered - * a member of the domain. + * in the expression. Note that it will appear to have the type of + * the base type, not the domain. This seems correct since within the + * check expression, we should not assume the input value can be + * considered a member of the domain. */ domVal = makeNode(CoerceToDomainValue); domVal->typeId = baseTypeOid; @@ -1841,13 +1850,13 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid, /* * Store the constraint in pg_constraint */ - CreateConstraintEntry(constr->name, /* Constraint Name */ - domainNamespace, /* namespace */ + CreateConstraintEntry(constr->name, /* Constraint Name */ + domainNamespace, /* namespace */ CONSTRAINT_CHECK, /* Constraint Type */ false, /* Is Deferrable */ false, /* Is Deferred */ - InvalidOid, /* not a relation constraint */ - NULL, + InvalidOid, /* not a relation constraint */ + NULL, 0, domainOid, /* domain constraint */ InvalidOid, /* Foreign key fields */ @@ -1857,13 +1866,13 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid, ' ', ' ', InvalidOid, - expr, /* Tree form check constraint */ + expr, /* Tree form check constraint */ ccbin, /* Binary form check constraint */ - ccsrc); /* Source form check constraint */ + ccsrc); /* Source form check constraint */ /* - * Return the compiled constraint expression so the calling routine can - * perform any additional required tests. + * Return the compiled constraint expression so the calling routine + * can perform any additional required tests. */ return ccbin; } @@ -1893,7 +1902,7 @@ GetDomainConstraints(Oid typeOid) Form_pg_type typTup; ScanKeyData key[1]; SysScanDesc scan; - + tup = SearchSysCache(TYPEOID, ObjectIdGetDatum(typeOid), 0, 0, 0); @@ -1915,17 +1924,20 @@ GetDomainConstraints(Oid typeOid) while (HeapTupleIsValid(conTup = systable_getnext(scan))) { - Form_pg_constraint c = (Form_pg_constraint) GETSTRUCT(conTup); - Datum val; - bool isNull; - Expr *check_expr; + Form_pg_constraint c = (Form_pg_constraint) GETSTRUCT(conTup); + Datum val; + bool isNull; + Expr *check_expr; DomainConstraintState *r; /* Ignore non-CHECK constraints (presently, shouldn't be any) */ if (c->contype != CONSTRAINT_CHECK) continue; - /* Not expecting conbin to be NULL, but we'll test for it anyway */ + /* + * Not expecting conbin to be NULL, but we'll test for it + * anyway + */ val = fastgetattr(conTup, Anum_pg_constraint_conbin, conRel->rd_att, &isNull); if (isNull) @@ -1945,8 +1957,8 @@ GetDomainConstraints(Oid typeOid) r->check_expr = ExecInitExpr(check_expr, NULL); /* - * use lcons() here because constraints of lower domains should - * be applied earlier. + * use lcons() here because constraints of lower domains + * should be applied earlier. */ result = lcons(r, result); } @@ -2003,7 +2015,7 @@ AlterTypeOwner(List *names, AclId newOwnerSysId) Oid typeOid; Relation rel; HeapTuple tup; - Form_pg_type typTup; + Form_pg_type typTup; /* Make a TypeName so we can use standard type lookup machinery */ typename = makeNode(TypeName); diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index 36416a5232..117eef1e75 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/commands/user.c,v 1.122 2003/08/01 00:15:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/user.c,v 1.123 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -146,12 +146,12 @@ write_group_file(Relation grel) if (fp == NULL) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not write temp file \"%s\": %m", tempname))); + errmsg("could not write temp file \"%s\": %m", tempname))); /* - * Read pg_group and write the file. Note we use SnapshotSelf to ensure - * we see all effects of current transaction. (Perhaps could do a - * CommandCounterIncrement beforehand, instead?) + * Read pg_group and write the file. Note we use SnapshotSelf to + * ensure we see all effects of current transaction. (Perhaps could + * do a CommandCounterIncrement beforehand, instead?) */ scan = heap_beginscan(grel, SnapshotSelf, 0, NULL); while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) @@ -212,7 +212,7 @@ write_group_file(Relation grel) if (usename[j] != '\0') { ereport(LOG, - (errmsg("invalid user name \"%s\"", usename))); + (errmsg("invalid user name \"%s\"", usename))); continue; } @@ -245,7 +245,7 @@ write_group_file(Relation grel) if (ferror(fp)) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not write temp file \"%s\": %m", tempname))); + errmsg("could not write temp file \"%s\": %m", tempname))); FreeFile(fp); /* @@ -294,12 +294,12 @@ write_user_file(Relation urel) if (fp == NULL) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not write temp file \"%s\": %m", tempname))); + errmsg("could not write temp file \"%s\": %m", tempname))); /* - * Read pg_shadow and write the file. Note we use SnapshotSelf to ensure - * we see all effects of current transaction. (Perhaps could do a - * CommandCounterIncrement beforehand, instead?) + * Read pg_shadow and write the file. Note we use SnapshotSelf to + * ensure we see all effects of current transaction. (Perhaps could + * do a CommandCounterIncrement beforehand, instead?) */ scan = heap_beginscan(urel, SnapshotSelf, 0, NULL); while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) @@ -376,7 +376,7 @@ write_user_file(Relation urel) if (ferror(fp)) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not write temp file \"%s\": %m", tempname))); + errmsg("could not write temp file \"%s\": %m", tempname))); FreeFile(fp); /* @@ -430,10 +430,10 @@ AtEOXact_UpdatePasswordFile(bool isCommit) Relation urel = NULL; Relation grel = NULL; - if (! (user_file_update_needed || group_file_update_needed)) + if (!(user_file_update_needed || group_file_update_needed)) return; - if (! isCommit) + if (!isCommit) { user_file_update_needed = false; group_file_update_needed = false; @@ -441,12 +441,12 @@ AtEOXact_UpdatePasswordFile(bool isCommit) } /* - * We use ExclusiveLock to ensure that only one backend writes the flat - * file(s) at a time. That's sufficient because it's okay to allow plain - * reads of the tables in parallel. There is some chance of a deadlock - * here (if we were triggered by a user update of pg_shadow or pg_group, - * which likely won't have gotten a strong enough lock), so get the locks - * we need before writing anything. + * We use ExclusiveLock to ensure that only one backend writes the + * flat file(s) at a time. That's sufficient because it's okay to + * allow plain reads of the tables in parallel. There is some chance + * of a deadlock here (if we were triggered by a user update of + * pg_shadow or pg_group, which likely won't have gotten a strong + * enough lock), so get the locks we need before writing anything. */ if (user_file_update_needed) urel = heap_openr(ShadowRelationName, ExclusiveLock); @@ -1088,7 +1088,7 @@ DropUser(DropUserStmt *stmt) ereport(ERROR, (errcode(ERRCODE_OBJECT_IN_USE), errmsg("user \"%s\" cannot be dropped", user), - errdetail("The user owns database \"%s\".", dbname))); + errdetail("The user owns database \"%s\".", dbname))); } heap_endscan(scan); @@ -1172,10 +1172,10 @@ RenameUser(const char *oldname, const char *newname) errmsg("user \"%s\" does not exist", oldname))); /* - * XXX Client applications probably store the session user - * somewhere, so renaming it could cause confusion. On the other - * hand, there may not be an actual problem besides a little - * confusion, so think about this and decide. + * XXX Client applications probably store the session user somewhere, + * so renaming it could cause confusion. On the other hand, there may + * not be an actual problem besides a little confusion, so think about + * this and decide. */ if (((Form_pg_shadow) GETSTRUCT(tup))->usesysid == GetSessionUserId()) ereport(ERROR, @@ -1221,14 +1221,14 @@ CheckPgUserAclNotNull(void) htup = SearchSysCache(RELOID, ObjectIdGetDatum(RelOid_pg_shadow), 0, 0, 0); - if (!HeapTupleIsValid(htup)) /* should not happen, we hope */ + if (!HeapTupleIsValid(htup)) /* should not happen, we hope */ elog(ERROR, "cache lookup failed for relation %u", RelOid_pg_shadow); if (heap_attisnull(htup, Anum_pg_class_relacl)) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("before using passwords you must revoke permissions on %s", - ShadowRelationName), + errmsg("before using passwords you must revoke permissions on %s", + ShadowRelationName), errdetail("This restriction is to prevent unprivileged users from reading the passwords."), errhint("Try 'REVOKE ALL ON \"%s\" FROM PUBLIC'.", ShadowRelationName))); diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index e73ace27c2..9dc0d9a899 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -13,7 +13,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.257 2003/07/20 21:56:34 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.258 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -287,24 +287,25 @@ vacuum(VacuumStmt *vacstmt) if (vacstmt->vacuum) { - if (! vacuum_rel(relid, vacstmt, RELKIND_RELATION)) - all_rels = false; /* forget about updating dbstats */ + if (!vacuum_rel(relid, vacstmt, RELKIND_RELATION)) + all_rels = false; /* forget about updating dbstats */ } if (vacstmt->analyze) { MemoryContext old_context = NULL; /* - * If we vacuumed, use new transaction for analyze. - * Otherwise, we can use the outer transaction, but we still - * need to call analyze_rel in a memory context that will be - * cleaned up on return (else we leak memory while processing - * multiple tables). + * If we vacuumed, use new transaction for analyze. Otherwise, + * we can use the outer transaction, but we still need to call + * analyze_rel in a memory context that will be cleaned up on + * return (else we leak memory while processing multiple + * tables). */ if (vacstmt->vacuum) { StartTransactionCommand(); - SetQuerySnapshot(); /* might be needed for functions in indexes */ + SetQuerySnapshot(); /* might be needed for functions + * in indexes */ } else old_context = MemoryContextSwitchTo(anl_context); @@ -734,7 +735,8 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind) /* Begin a transaction for vacuuming this relation */ StartTransactionCommand(); - SetQuerySnapshot(); /* might be needed for functions in indexes */ + SetQuerySnapshot(); /* might be needed for functions in + * indexes */ /* * Check for user-requested abort. Note we want this to be inside a @@ -812,7 +814,8 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind) { relation_close(onerel, lmode); CommitTransactionCommand(); - return true; /* assume no long-lived data in temp tables */ + return true; /* assume no long-lived data in temp + * tables */ } /* @@ -860,7 +863,7 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind) */ if (toast_relid != InvalidOid) { - if (! vacuum_rel(toast_relid, vacstmt, RELKIND_TOASTVALUE)) + if (!vacuum_rel(toast_relid, vacstmt, RELKIND_TOASTVALUE)) result = false; /* failed to vacuum the TOAST table? */ } @@ -1087,8 +1090,8 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, if (PageIsNew(page)) { ereport(WARNING, - (errmsg("relation \"%s\" page %u is uninitialized --- fixing", - relname, blkno))); + (errmsg("relation \"%s\" page %u is uninitialized --- fixing", + relname, blkno))); PageInit(page, BufferGetPageSize(buf), 0); vacpage->free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower; free_space += vacpage->free; @@ -1314,7 +1317,8 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, /* * Include the page in empty_end_pages if it will be empty after - * vacuuming; this is to keep us from using it as a move destination. + * vacuuming; this is to keep us from using it as a move + * destination. */ if (notup) { @@ -1382,9 +1386,9 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, RelationGetRelationName(onerel), tups_vacuumed, num_tuples, nblocks), errdetail("%.0f dead tuples cannot be removed yet.\n" - "Nonremovable tuples range from %lu to %lu bytes long.\n" + "Nonremovable tuples range from %lu to %lu bytes long.\n" "There were %.0f unused item pointers.\n" - "Total free space (including removable tuples) is %.0f bytes.\n" + "Total free space (including removable tuples) is %.0f bytes.\n" "%u pages are or will become empty, including %u at the end of the table.\n" "%u pages containing %.0f free bytes are potential move destinations.\n" "%s", @@ -2380,8 +2384,8 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, /* * It'd be cleaner to make this report at the bottom of this routine, * but then the rusage would double-count the second pass of index - * vacuuming. So do it here and ignore the relatively small amount - * of processing that occurs below. + * vacuuming. So do it here and ignore the relatively small amount of + * processing that occurs below. */ ereport(elevel, (errmsg("\"%s\": moved %u tuples, truncated %u to %u pages", @@ -2735,7 +2739,7 @@ vacuum_index(VacPageList vacpagelist, Relation indrel, stats->num_index_tuples, stats->num_pages), errdetail("%.0f index tuples were removed.\n" - "%u index pages have been deleted, %u are currently reusable.\n" + "%u index pages have been deleted, %u are currently reusable.\n" "%s", stats->tuples_removed, stats->pages_deleted, stats->pages_free, @@ -2752,7 +2756,7 @@ vacuum_index(VacPageList vacpagelist, Relation indrel, ereport(WARNING, (errmsg("index \"%s\" contains %.0f tuples, but table contains %.0f tuples", RelationGetRelationName(indrel), - stats->num_index_tuples, num_tuples + keep_tuples), + stats->num_index_tuples, num_tuples + keep_tuples), errhint("Rebuild the index with REINDEX."))); } @@ -2837,13 +2841,14 @@ vac_update_fsm(Relation onerel, VacPageList fraged_pages, /* * We only report pages with free space at least equal to the average - * request size --- this avoids cluttering FSM with uselessly-small bits - * of space. Although FSM would discard pages with little free space - * anyway, it's important to do this prefiltering because (a) it reduces - * the time spent holding the FSM lock in RecordRelationFreeSpace, and - * (b) FSM uses the number of pages reported as a statistic for guiding - * space management. If we didn't threshold our reports the same way - * vacuumlazy.c does, we'd be skewing that statistic. + * request size --- this avoids cluttering FSM with uselessly-small + * bits of space. Although FSM would discard pages with little free + * space anyway, it's important to do this prefiltering because (a) it + * reduces the time spent holding the FSM lock in + * RecordRelationFreeSpace, and (b) FSM uses the number of pages + * reported as a statistic for guiding space management. If we didn't + * threshold our reports the same way vacuumlazy.c does, we'd be + * skewing that statistic. */ threshold = GetAvgFSMRequestSize(&onerel->rd_node); diff --git a/src/backend/commands/vacuumlazy.c b/src/backend/commands/vacuumlazy.c index f0be98a23e..65af960be8 100644 --- a/src/backend/commands/vacuumlazy.c +++ b/src/backend/commands/vacuumlazy.c @@ -31,7 +31,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/vacuumlazy.c,v 1.29 2003/07/20 21:56:34 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/vacuumlazy.c,v 1.30 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -79,7 +79,7 @@ typedef struct LVRelStats bool fs_is_heap; /* are we using heap organization? */ int num_free_pages; /* current # of entries */ int max_free_pages; /* # slots allocated in array */ - PageFreeSpaceInfo *free_pages; /* array or heap of blkno/avail */ + PageFreeSpaceInfo *free_pages; /* array or heap of blkno/avail */ } LVRelStats; @@ -162,7 +162,7 @@ lazy_vacuum_rel(Relation onerel, VacuumStmt *vacstmt) */ possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages; if (possibly_freeable >= REL_TRUNCATE_MINIMUM || - possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION) + possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION) lazy_truncate_heap(onerel, vacrelstats); /* Update shared free space map with final free space info */ @@ -659,7 +659,7 @@ lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats) stats->num_index_tuples, stats->num_pages), errdetail("%.0f index tuples were removed.\n" - "%u index pages have been deleted, %u are currently reusable.\n" + "%u index pages have been deleted, %u are currently reusable.\n" "%s", stats->tuples_removed, stats->pages_deleted, stats->pages_free, @@ -966,16 +966,18 @@ lazy_record_free_space(LVRelStats *vacrelstats, /* * A page with less than stats->threshold free space will be forgotten * immediately, and never passed to the free space map. Removing the - * uselessly small entries early saves cycles, and in particular reduces - * the amount of time we spend holding the FSM lock when we finally call - * RecordRelationFreeSpace. Since the FSM will probably drop pages with - * little free space anyway, there's no point in making this really small. + * uselessly small entries early saves cycles, and in particular + * reduces the amount of time we spend holding the FSM lock when we + * finally call RecordRelationFreeSpace. Since the FSM will probably + * drop pages with little free space anyway, there's no point in + * making this really small. * - * XXX Is it worth trying to measure average tuple size, and using that to - * adjust the threshold? Would be worthwhile if FSM has no stats yet - * for this relation. But changing the threshold as we scan the rel - * might lead to bizarre behavior, too. Also, it's probably better if - * vacuum.c has the same thresholding behavior as we do here. + * XXX Is it worth trying to measure average tuple size, and using that + * to adjust the threshold? Would be worthwhile if FSM has no stats + * yet for this relation. But changing the threshold as we scan the + * rel might lead to bizarre behavior, too. Also, it's probably + * better if vacuum.c has the same thresholding behavior as we do + * here. */ if (avail < vacrelstats->threshold) return; @@ -996,7 +998,7 @@ lazy_record_free_space(LVRelStats *vacrelstats, /*---------- * The rest of this routine works with "heap" organization of the * free space arrays, wherein we maintain the heap property - * avail[(j-1) div 2] <= avail[j] for 0 < j < n. + * avail[(j-1) div 2] <= avail[j] for 0 < j < n. * In particular, the zero'th element always has the smallest available * space and can be discarded to make room for a new page with more space. * See Knuth's discussion of heap-based priority queues, sec 5.2.3; diff --git a/src/backend/commands/variable.c b/src/backend/commands/variable.c index e0b041636e..07dfca13c8 100644 --- a/src/backend/commands/variable.c +++ b/src/backend/commands/variable.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.85 2003/07/29 00:03:18 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.86 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -34,7 +34,7 @@ * to duplicate the test in AC_STRUCT_TIMEZONE. */ #ifdef HAVE_TZNAME -#ifndef tzname /* For SGI. */ +#ifndef tzname /* For SGI. */ extern char *tzname[]; #endif #endif @@ -273,12 +273,11 @@ static void clear_tz(void) { /* - * unsetenv() works fine, but is BSD, not POSIX, and is not - * available under Solaris, among others. Apparently putenv() - * called as below clears the process-specific environment - * variables. Other reasonable arguments to putenv() (e.g. - * "TZ=", "TZ", "") result in a core dump (under Linux - * anyway). - thomas 1998-01-26 + * unsetenv() works fine, but is BSD, not POSIX, and is not available + * under Solaris, among others. Apparently putenv() called as below + * clears the process-specific environment variables. Other + * reasonable arguments to putenv() (e.g. "TZ=", "TZ", "") result in a + * core dump (under Linux anyway). - thomas 1998-01-26 */ if (tzbuf[0] == 'T') { @@ -298,14 +297,14 @@ clear_tz(void) * * If tzname[1] is a nonempty string, *or* the global timezone variable is * not zero, then tzset must have recognized the TZ value as something - * different from UTC. Return true. + * different from UTC. Return true. * * Otherwise, check to see if the TZ name is a known spelling of "UTC" * (ie, appears in our internal tables as a timezone equivalent to UTC). * If so, accept it. * * This will reject nonstandard spellings of UTC unless tzset() chose to - * set tzname[1] as well as tzname[0]. The glibc version of tzset() will + * set tzname[1] as well as tzname[0]. The glibc version of tzset() will * do so, but on other systems we may be tightening the spec a little. * * Another problem is that on some platforms (eg HPUX), if tzset thinks the @@ -337,8 +336,8 @@ tzset_succeeded(const char *tz) return true; /* - * Check for known spellings of "UTC". Note we must downcase the input - * before passing it to DecodePosixTimezone(). + * Check for known spellings of "UTC". Note we must downcase the + * input before passing it to DecodePosixTimezone(). */ StrNCpy(tztmp, tz, sizeof(tztmp)); for (cp = tztmp; *cp; cp++) @@ -368,7 +367,7 @@ tz_acceptable(void) /* * To detect leap-second timekeeping, compute the time_t value for - * local midnight, 2000-01-01. Insist that this be a multiple of 60; + * local midnight, 2000-01-01. Insist that this be a multiple of 60; * any partial-minute offset has to be due to leap seconds. */ MemSet(&tt, 0, sizeof(tt)); @@ -399,7 +398,7 @@ assign_timezone(const char *value, bool doit, bool interactive) */ if (!have_saved_tz) { - char *orig_tz = getenv("TZ"); + char *orig_tz = getenv("TZ"); if (orig_tz) StrNCpy(orig_tzbuf, orig_tz, sizeof(orig_tzbuf)); @@ -434,9 +433,9 @@ assign_timezone(const char *value, bool doit, bool interactive) /* * Try to parse it. XXX an invalid interval format will result in - * ereport, which is not desirable for GUC. We did what we could to - * guard against this in flatten_set_variable_args, but a string - * coming in from postgresql.conf might contain anything. + * ereport, which is not desirable for GUC. We did what we could + * to guard against this in flatten_set_variable_args, but a + * string coming in from postgresql.conf might contain anything. */ interval = DatumGetIntervalP(DirectFunctionCall3(interval_in, CStringGetDatum(val), @@ -455,7 +454,7 @@ assign_timezone(const char *value, bool doit, bool interactive) if (doit) { /* Here we change from SQL to Unix sign convention */ - CTimeZone = - interval->time; + CTimeZone = -interval->time; HasCTZSet = true; } pfree(interval); @@ -471,22 +470,22 @@ assign_timezone(const char *value, bool doit, bool interactive) if (doit) { /* Here we change from SQL to Unix sign convention */ - CTimeZone = - hours * 3600; + CTimeZone = -hours * 3600; HasCTZSet = true; } } else if (strcasecmp(value, "UNKNOWN") == 0) { /* - * UNKNOWN is the value shown as the "default" for TimeZone - * in guc.c. We interpret it as meaning the original TZ - * inherited from the environment. Note that if there is an - * original TZ setting, we will return that rather than UNKNOWN - * as the canonical spelling. + * UNKNOWN is the value shown as the "default" for TimeZone in + * guc.c. We interpret it as meaning the original TZ + * inherited from the environment. Note that if there is an + * original TZ setting, we will return that rather than + * UNKNOWN as the canonical spelling. */ if (doit) { - bool ok; + bool ok; /* Revert to original setting of TZ, whatever it was */ if (orig_tzbuf[0]) @@ -516,14 +515,14 @@ assign_timezone(const char *value, bool doit, bool interactive) * Otherwise assume it is a timezone name. * * We have to actually apply the change before we can have any - * hope of checking it. So, save the old value in case we have - * to back out. Note that it's possible the old setting is in - * tzbuf, so we'd better copy it. + * hope of checking it. So, save the old value in case we + * have to back out. Note that it's possible the old setting + * is in tzbuf, so we'd better copy it. */ - char save_tzbuf[TZBUF_LEN]; - char *save_tz; - bool known, - acceptable; + char save_tzbuf[TZBUF_LEN]; + char *save_tz; + bool known, + acceptable; save_tz = getenv("TZ"); if (save_tz) @@ -563,8 +562,8 @@ assign_timezone(const char *value, bool doit, bool interactive) { ereport(interactive ? ERROR : LOG, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("timezone \"%s\" appears to use leap seconds", - value), + errmsg("timezone \"%s\" appears to use leap seconds", + value), errdetail("PostgreSQL does not support leap seconds"))); return NULL; } @@ -609,7 +608,7 @@ show_timezone(void) Interval interval; interval.month = 0; - interval.time = - CTimeZone; + interval.time = -CTimeZone; tzn = DatumGetCString(DirectFunctionCall1(interval_out, IntervalPGetDatum(&interval))); @@ -703,16 +702,16 @@ assign_client_encoding(const char *value, bool doit, bool interactive) /* * Note: if we are in startup phase then SetClientEncoding may not be * able to really set the encoding. In this case we will assume that - * the encoding is okay, and InitializeClientEncoding() will fix things - * once initialization is complete. + * the encoding is okay, and InitializeClientEncoding() will fix + * things once initialization is complete. */ if (SetClientEncoding(encoding, doit) < 0) { if (interactive) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("conversion between %s and %s is not supported", - value, GetDatabaseEncodingName()))); + errmsg("conversion between %s and %s is not supported", + value, GetDatabaseEncodingName()))); return NULL; } return value; @@ -758,12 +757,12 @@ assign_session_authorization(const char *value, bool doit, bool interactive) /* not a saved ID, so look it up */ HeapTuple userTup; - if (! IsTransactionState()) + if (!IsTransactionState()) { /* * Can't do catalog lookups, so fail. The upshot of this is - * that session_authorization cannot be set in postgresql.conf, - * which seems like a good thing anyway. + * that session_authorization cannot be set in + * postgresql.conf, which seems like a good thing anyway. */ return NULL; } @@ -782,7 +781,7 @@ assign_session_authorization(const char *value, bool doit, bool interactive) usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid; is_superuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper; - + ReleaseSysCache(userTup); } diff --git a/src/backend/commands/view.c b/src/backend/commands/view.c index e12ae0af68..9c3b372b3f 100644 --- a/src/backend/commands/view.c +++ b/src/backend/commands/view.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/view.c,v 1.75 2003/08/01 00:15:20 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/view.c,v 1.76 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -190,8 +190,8 @@ checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc) newattr->atttypmod != oldattr->atttypmod) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), - errmsg("cannot change datatype of view column \"%s\"", - NameStr(oldattr->attname)))); + errmsg("cannot change datatype of view column \"%s\"", + NameStr(oldattr->attname)))); /* We can ignore the remaining attributes of an attribute... */ } diff --git a/src/backend/executor/execAmi.c b/src/backend/executor/execAmi.c index 61974827b3..9267d362dd 100644 --- a/src/backend/executor/execAmi.c +++ b/src/backend/executor/execAmi.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/executor/execAmi.c,v 1.72 2003/07/21 17:05:00 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execAmi.c,v 1.73 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -48,7 +48,7 @@ * ---------------------------------------------------------------- */ void -ExecReScan(PlanState *node, ExprContext *exprCtxt) +ExecReScan(PlanState * node, ExprContext *exprCtxt) { /* If collecting timing stats, update them */ if (node->instrument) @@ -61,7 +61,7 @@ ExecReScan(PlanState *node, ExprContext *exprCtxt) foreach(lst, node->initPlan) { - SubPlanState *sstate = (SubPlanState *) lfirst(lst); + SubPlanState *sstate = (SubPlanState *) lfirst(lst); PlanState *splan = sstate->planstate; if (splan->plan->extParam != NULL) /* don't care about child @@ -72,7 +72,7 @@ ExecReScan(PlanState *node, ExprContext *exprCtxt) } foreach(lst, node->subPlan) { - SubPlanState *sstate = (SubPlanState *) lfirst(lst); + SubPlanState *sstate = (SubPlanState *) lfirst(lst); PlanState *splan = sstate->planstate; if (splan->plan->extParam != NULL) @@ -177,7 +177,7 @@ ExecReScan(PlanState *node, ExprContext *exprCtxt) * Marks the current scan position. */ void -ExecMarkPos(PlanState *node) +ExecMarkPos(PlanState * node) { switch (nodeTag(node)) { @@ -218,7 +218,7 @@ ExecMarkPos(PlanState *node) * restores the scan position previously saved with ExecMarkPos() */ void -ExecRestrPos(PlanState *node) +ExecRestrPos(PlanState * node) { switch (nodeTag(node)) { @@ -302,16 +302,16 @@ ExecSupportsBackwardScan(Plan *node) return false; case T_Append: - { - List *l; - - foreach(l, ((Append *) node)->appendplans) { - if (!ExecSupportsBackwardScan((Plan *) lfirst(l))) - return false; + List *l; + + foreach(l, ((Append *) node)->appendplans) + { + if (!ExecSupportsBackwardScan((Plan *) lfirst(l))) + return false; + } + return true; } - return true; - } case T_SeqScan: case T_IndexScan: diff --git a/src/backend/executor/execGrouping.c b/src/backend/executor/execGrouping.c index 3f9c6d0d47..8b0962ba9b 100644 --- a/src/backend/executor/execGrouping.c +++ b/src/backend/executor/execGrouping.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execGrouping.c,v 1.4 2003/07/21 17:05:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execGrouping.c,v 1.5 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -249,7 +249,7 @@ execTuplesHashPrepare(TupleDesc tupdesc, eq_function = oprfuncid(optup); ReleaseSysCache(optup); hash_function = get_op_hash_function(eq_opr); - if (!OidIsValid(hash_function)) /* should not happen */ + if (!OidIsValid(hash_function)) /* should not happen */ elog(ERROR, "could not find hash function for hash operator %u", eq_opr); fmgr_info(eq_function, &(*eqfunctions)[i]); @@ -289,8 +289,8 @@ BuildTupleHashTable(int numCols, AttrNumber *keyColIdx, int nbuckets, Size entrysize, MemoryContext tablecxt, MemoryContext tempcxt) { - TupleHashTable hashtable; - Size tabsize; + TupleHashTable hashtable; + Size tabsize; Assert(nbuckets > 0); Assert(entrysize >= sizeof(TupleHashEntryData)); @@ -411,9 +411,9 @@ LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot, * Iterator state must be initialized with ResetTupleHashIterator() macro. */ TupleHashEntry -ScanTupleHashTable(TupleHashTable hashtable, TupleHashIterator *state) +ScanTupleHashTable(TupleHashTable hashtable, TupleHashIterator * state) { - TupleHashEntry entry; + TupleHashEntry entry; entry = state->next_entry; while (entry == NULL) diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c index ded748d5bf..ae58bb130f 100644 --- a/src/backend/executor/execMain.c +++ b/src/backend/executor/execMain.c @@ -26,7 +26,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.212 2003/08/01 00:15:20 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.213 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -68,7 +68,7 @@ static void initResultRelInfo(ResultRelInfo *resultRelInfo, Index resultRelationIndex, List *rangeTable, CmdType operation); -static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate, +static TupleTableSlot *ExecutePlan(EState *estate, PlanState * planstate, CmdType operation, long numberTuples, ScanDirection direction, @@ -87,7 +87,7 @@ static void EndEvalPlanQual(EState *estate); static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation); static void ExecCheckXactReadOnly(Query *parsetree, CmdType operation); static void EvalPlanQualStart(evalPlanQual *epq, EState *estate, - evalPlanQual *priorepq); + evalPlanQual *priorepq); static void EvalPlanQualStop(evalPlanQual *epq); /* end of local decls */ @@ -100,7 +100,7 @@ static void EvalPlanQualStop(evalPlanQual *epq); * query plan * * Takes a QueryDesc previously created by CreateQueryDesc (it's not real - * clear why we bother to separate the two functions, but...). The tupDesc + * clear why we bother to separate the two functions, but...). The tupDesc * field of the QueryDesc is filled in to describe the tuples that will be * returned, and the internal fields (estate and planstate) are set up. * @@ -122,8 +122,8 @@ ExecutorStart(QueryDesc *queryDesc, bool explainOnly) Assert(queryDesc->estate == NULL); /* - * If the transaction is read-only, we need to check if any writes - * are planned to non-temporary tables. + * If the transaction is read-only, we need to check if any writes are + * planned to non-temporary tables. */ if (!explainOnly) ExecCheckXactReadOnly(queryDesc->parsetree, queryDesc->operation); @@ -362,8 +362,8 @@ ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation) /* * Otherwise, only plain-relation RTEs need to be checked here. - * Function RTEs are checked by init_fcache when the function is prepared - * for execution. Join and special RTEs need no checks. + * Function RTEs are checked by init_fcache when the function is + * prepared for execution. Join and special RTEs need no checks. */ if (rte->rtekind != RTE_RELATION) return; @@ -435,7 +435,7 @@ ExecCheckXactReadOnly(Query *parsetree, CmdType operation) if (operation == CMD_DELETE || operation == CMD_INSERT || operation == CMD_UPDATE) { - List *lp; + List *lp; foreach(lp, parsetree->rtable) { @@ -474,9 +474,9 @@ static void InitPlan(QueryDesc *queryDesc, bool explainOnly) { CmdType operation = queryDesc->operation; - Query *parseTree = queryDesc->parsetree; - Plan *plan = queryDesc->plantree; - EState *estate = queryDesc->estate; + Query *parseTree = queryDesc->parsetree; + Plan *plan = queryDesc->plantree; + EState *estate = queryDesc->estate; PlanState *planstate; List *rangeTable; Relation intoRelationDesc; @@ -484,8 +484,8 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly) TupleDesc tupType; /* - * Do permissions checks. It's sufficient to examine the query's - * top rangetable here --- subplan RTEs will be checked during + * Do permissions checks. It's sufficient to examine the query's top + * rangetable here --- subplan RTEs will be checked during * ExecInitSubPlan(). */ ExecCheckRTPerms(parseTree->rtable, operation); @@ -570,10 +570,11 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly) if (operation == CMD_SELECT && parseTree->into != NULL) { do_select_into = true; + /* - * For now, always create OIDs in SELECT INTO; this is for backwards - * compatibility with pre-7.3 behavior. Eventually we might want - * to allow the user to choose. + * For now, always create OIDs in SELECT INTO; this is for + * backwards compatibility with pre-7.3 behavior. Eventually we + * might want to allow the user to choose. */ estate->es_force_oids = true; } @@ -640,12 +641,12 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly) tupType = ExecGetResultType(planstate); /* - * Initialize the junk filter if needed. SELECT and INSERT queries need a - * filter if there are any junk attrs in the tlist. INSERT and SELECT - * INTO also need a filter if the top plan node is a scan node that's not - * doing projection (else we'll be scribbling on the scan tuple!) UPDATE - * and DELETE always need a filter, since there's always a junk 'ctid' - * attribute present --- no need to look first. + * Initialize the junk filter if needed. SELECT and INSERT queries + * need a filter if there are any junk attrs in the tlist. INSERT and + * SELECT INTO also need a filter if the top plan node is a scan node + * that's not doing projection (else we'll be scribbling on the scan + * tuple!) UPDATE and DELETE always need a filter, since there's + * always a junk 'ctid' attribute present --- no need to look first. */ { bool junk_filter_needed = false; @@ -752,8 +753,8 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly) /* * If doing SELECT INTO, initialize the "into" relation. We must wait - * till now so we have the "clean" result tuple type to create the - * new table from. + * till now so we have the "clean" result tuple type to create the new + * table from. * * If EXPLAIN, skip creating the "into" relation. */ @@ -795,16 +796,16 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly) FreeTupleDesc(tupdesc); /* - * Advance command counter so that the newly-created - * relation's catalog tuples will be visible to heap_open. + * Advance command counter so that the newly-created relation's + * catalog tuples will be visible to heap_open. */ CommandCounterIncrement(); /* - * If necessary, create a TOAST table for the into - * relation. Note that AlterTableCreateToastTable ends - * with CommandCounterIncrement(), so that the TOAST table - * will be visible for insertion. + * If necessary, create a TOAST table for the into relation. Note + * that AlterTableCreateToastTable ends with + * CommandCounterIncrement(), so that the TOAST table will be + * visible for insertion. */ AlterTableCreateToastTable(intoRelationId, true); @@ -841,19 +842,19 @@ initResultRelInfo(ResultRelInfo *resultRelInfo, ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("cannot change sequence relation \"%s\"", - RelationGetRelationName(resultRelationDesc)))); + RelationGetRelationName(resultRelationDesc)))); break; case RELKIND_TOASTVALUE: ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("cannot change toast relation \"%s\"", - RelationGetRelationName(resultRelationDesc)))); + RelationGetRelationName(resultRelationDesc)))); break; case RELKIND_VIEW: ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("cannot change view relation \"%s\"", - RelationGetRelationName(resultRelationDesc)))); + RelationGetRelationName(resultRelationDesc)))); break; } @@ -894,7 +895,7 @@ initResultRelInfo(ResultRelInfo *resultRelInfo, * ---------------------------------------------------------------- */ void -ExecEndPlan(PlanState *planstate, EState *estate) +ExecEndPlan(PlanState * planstate, EState *estate) { ResultRelInfo *resultRelInfo; int i; @@ -964,18 +965,18 @@ ExecEndPlan(PlanState *planstate, EState *estate) */ static TupleTableSlot * ExecutePlan(EState *estate, - PlanState *planstate, + PlanState * planstate, CmdType operation, long numberTuples, ScanDirection direction, DestReceiver *dest) { - JunkFilter *junkfilter; - TupleTableSlot *slot; - ItemPointer tupleid = NULL; - ItemPointerData tuple_ctid; - long current_tuple_count; - TupleTableSlot *result; + JunkFilter *junkfilter; + TupleTableSlot *slot; + ItemPointer tupleid = NULL; + ItemPointerData tuple_ctid; + long current_tuple_count; + TupleTableSlot *result; /* * initialize local variables @@ -1199,7 +1200,7 @@ lnext: ; /* * check our tuple count.. if we've processed the proper number - * then quit, else loop again and process more tuples. Zero + * then quit, else loop again and process more tuples. Zero * numberTuples means no limit. */ current_tuple_count++; @@ -1309,7 +1310,7 @@ ExecInsert(TupleTableSlot *slot, /* BEFORE ROW INSERT Triggers */ if (resultRelInfo->ri_TrigDesc && - resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0) + resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0) { HeapTuple newtuple; @@ -1686,13 +1687,13 @@ ExecConstraints(ResultRelInfo *resultRelInfo, ereport(ERROR, (errcode(ERRCODE_NOT_NULL_VIOLATION), errmsg("null value for attribute \"%s\" violates NOT NULL constraint", - NameStr(rel->rd_att->attrs[attrChk - 1]->attname)))); + NameStr(rel->rd_att->attrs[attrChk - 1]->attname)))); } } if (constr->num_check > 0) { - const char *failed; + const char *failed; if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL) ereport(ERROR, @@ -1884,10 +1885,11 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) * integrated with the Param mechanism somehow, so that the upper plan * nodes know that their children's outputs have changed. * - * Note that the stack of free evalPlanQual nodes is quite useless at - * the moment, since it only saves us from pallocing/releasing the + * Note that the stack of free evalPlanQual nodes is quite useless at the + * moment, since it only saves us from pallocing/releasing the * evalPlanQual nodes themselves. But it will be useful once we - * implement ReScan instead of end/restart for re-using PlanQual nodes. + * implement ReScan instead of end/restart for re-using PlanQual + * nodes. */ if (endNode) { @@ -1898,10 +1900,11 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) /* * Initialize new recheck query. * - * Note: if we were re-using PlanQual plans via ExecReScan, we'd need - * to instead copy down changeable state from the top plan (including - * es_result_relation_info, es_junkFilter) and reset locally changeable - * state in the epq (including es_param_exec_vals, es_evTupleNull). + * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to + * instead copy down changeable state from the top plan (including + * es_result_relation_info, es_junkFilter) and reset locally + * changeable state in the epq (including es_param_exec_vals, + * es_evTupleNull). */ EvalPlanQualStart(epq, estate, epq->next); @@ -2016,9 +2019,9 @@ EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq) /* * The epqstates share the top query's copy of unchanging state such - * as the snapshot, rangetable, result-rel info, and external Param info. - * They need their own copies of local state, including a tuple table, - * es_param_exec_vals, etc. + * as the snapshot, rangetable, result-rel info, and external Param + * info. They need their own copies of local state, including a tuple + * table, es_param_exec_vals, etc. */ epqstate->es_direction = ForwardScanDirection; epqstate->es_snapshot = estate->es_snapshot; @@ -2036,11 +2039,11 @@ EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq) epqstate->es_instrument = estate->es_instrument; epqstate->es_force_oids = estate->es_force_oids; epqstate->es_topPlan = estate->es_topPlan; + /* - * Each epqstate must have its own es_evTupleNull state, but - * all the stack entries share es_evTuple state. This allows - * sub-rechecks to inherit the value being examined by an - * outer recheck. + * Each epqstate must have its own es_evTupleNull state, but all the + * stack entries share es_evTuple state. This allows sub-rechecks to + * inherit the value being examined by an outer recheck. */ epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool)); if (priorepq == NULL) diff --git a/src/backend/executor/execProcnode.c b/src/backend/executor/execProcnode.c index f73f2d7185..1c34e1d1a4 100644 --- a/src/backend/executor/execProcnode.c +++ b/src/backend/executor/execProcnode.c @@ -12,7 +12,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execProcnode.c,v 1.37 2003/07/21 17:05:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execProcnode.c,v 1.38 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -52,7 +52,7 @@ * * ExecInitNode() notices that it is looking at a nest loop and * as the code below demonstrates, it calls ExecInitNestLoop(). * Eventually this calls ExecInitNode() on the right and left subplans - * and so forth until the entire plan is initialized. The result + * and so forth until the entire plan is initialized. The result * of ExecInitNode() is a plan state tree built with the same structure * as the underlying plan tree. * @@ -226,7 +226,7 @@ ExecInitNode(Plan *node, EState *estate) subps = NIL; foreach(subp, node->initPlan) { - SubPlan *subplan = (SubPlan *) lfirst(subp); + SubPlan *subplan = (SubPlan *) lfirst(subp); SubPlanState *sstate; Assert(IsA(subplan, SubPlan)); @@ -237,9 +237,9 @@ ExecInitNode(Plan *node, EState *estate) result->initPlan = subps; /* - * Initialize any subPlans present in this node. These were found - * by ExecInitExpr during initialization of the PlanState. Note we - * must do this after initializing initPlans, in case their arguments + * Initialize any subPlans present in this node. These were found by + * ExecInitExpr during initialization of the PlanState. Note we must + * do this after initializing initPlans, in case their arguments * contain subPlans (is that actually possible? perhaps not). */ subps = NIL; @@ -268,7 +268,7 @@ ExecInitNode(Plan *node, EState *estate) * ---------------------------------------------------------------- */ TupleTableSlot * -ExecProcNode(PlanState *node) +ExecProcNode(PlanState * node) { TupleTableSlot *result; @@ -280,7 +280,7 @@ ExecProcNode(PlanState *node) if (node == NULL) return NULL; - if (node->chgParam != NULL) /* something changed */ + if (node->chgParam != NULL) /* something changed */ ExecReScan(node, NULL); /* let ReScan handle this */ if (node->instrument) @@ -484,7 +484,7 @@ ExecCountSlotsNode(Plan *node) * ---------------------------------------------------------------- */ void -ExecEndNode(PlanState *node) +ExecEndNode(PlanState * node) { List *subp; diff --git a/src/backend/executor/execQual.c b/src/backend/executor/execQual.c index 891019f0ae..d509122f29 100644 --- a/src/backend/executor/execQual.c +++ b/src/backend/executor/execQual.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.138 2003/08/01 00:15:21 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.139 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -50,55 +50,55 @@ /* static function decls */ -static Datum ExecEvalAggref(AggrefExprState *aggref, - ExprContext *econtext, - bool *isNull); -static Datum ExecEvalArrayRef(ArrayRefExprState *astate, - ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); +static Datum ExecEvalAggref(AggrefExprState * aggref, + ExprContext *econtext, + bool *isNull); +static Datum ExecEvalArrayRef(ArrayRefExprState * astate, + ExprContext *econtext, + bool *isNull, ExprDoneCond *isDone); static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull); static Datum ExecEvalParam(Param *expression, ExprContext *econtext, - bool *isNull); -static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext, + bool *isNull); +static Datum ExecEvalFunc(FuncExprState * fcache, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext, +static Datum ExecEvalOper(FuncExprState * fcache, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext, +static Datum ExecEvalDistinct(FuncExprState * fcache, ExprContext *econtext, bool *isNull); -static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, - ExprContext *econtext, bool *isNull); +static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState * sstate, + ExprContext *econtext, bool *isNull); static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo, List *argList, ExprContext *econtext); -static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, - bool *isNull); -static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, - bool *isNull); -static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, - bool *isNull); -static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, +static Datum ExecEvalNot(BoolExprState * notclause, ExprContext *econtext, + bool *isNull); +static Datum ExecEvalOr(BoolExprState * orExpr, ExprContext *econtext, + bool *isNull); +static Datum ExecEvalAnd(BoolExprState * andExpr, ExprContext *econtext, + bool *isNull); +static Datum ExecEvalCase(CaseExprState * caseExpr, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -static Datum ExecEvalArray(ArrayExprState *astate, - ExprContext *econtext, - bool *isNull); -static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr, - ExprContext *econtext, - bool *isNull); -static Datum ExecEvalNullIf(FuncExprState *nullIfExpr, ExprContext *econtext, - bool *isNull); -static Datum ExecEvalNullTest(GenericExprState *nstate, - ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); -static Datum ExecEvalBooleanTest(GenericExprState *bstate, - ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); -static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate, +static Datum ExecEvalArray(ArrayExprState * astate, + ExprContext *econtext, + bool *isNull); +static Datum ExecEvalCoalesce(CoalesceExprState * coalesceExpr, + ExprContext *econtext, + bool *isNull); +static Datum ExecEvalNullIf(FuncExprState * nullIfExpr, ExprContext *econtext, + bool *isNull); +static Datum ExecEvalNullTest(GenericExprState * nstate, + ExprContext *econtext, + bool *isNull, ExprDoneCond *isDone); +static Datum ExecEvalBooleanTest(GenericExprState * bstate, + ExprContext *econtext, + bool *isNull, ExprDoneCond *isDone); +static Datum ExecEvalCoerceToDomain(CoerceToDomainState * cstate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -static Datum ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal, - ExprContext *econtext, bool *isNull); -static Datum ExecEvalFieldSelect(GenericExprState *fstate, - ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); +static Datum ExecEvalCoerceToDomainValue(CoerceToDomainValue * conVal, + ExprContext *econtext, bool *isNull); +static Datum ExecEvalFieldSelect(GenericExprState * fstate, + ExprContext *econtext, + bool *isNull, ExprDoneCond *isDone); /*---------- @@ -127,7 +127,7 @@ static Datum ExecEvalFieldSelect(GenericExprState *fstate, *---------- */ static Datum -ExecEvalArrayRef(ArrayRefExprState *astate, +ExecEvalArrayRef(ArrayRefExprState * astate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -301,7 +301,7 @@ ExecEvalArrayRef(ArrayRefExprState *astate, * ---------------------------------------------------------------- */ static Datum -ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, bool *isNull) +ExecEvalAggref(AggrefExprState * aggref, ExprContext *econtext, bool *isNull) { if (econtext->ecxt_aggvalues == NULL) /* safety check */ elog(ERROR, "no aggregates in this expression context"); @@ -382,8 +382,8 @@ ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull) * * XXX this is a horrid crock: since the pointer to the slot might live * longer than the current evaluation context, we are forced to copy - * the tuple and slot into a long-lived context --- we use - * the econtext's per-query memory which should be safe enough. This + * the tuple and slot into a long-lived context --- we use the + * econtext's per-query memory which should be safe enough. This * represents a serious memory leak if many such tuples are processed * in one command, however. We ought to redesign the representation * of whole-tuple datums so that this is not necessary. @@ -439,7 +439,8 @@ ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull) { /* * PARAM_EXEC params (internal executor parameters) are stored in - * the ecxt_param_exec_vals array, and can be accessed by array index. + * the ecxt_param_exec_vals array, and can be accessed by array + * index. */ ParamExecData *prm; @@ -457,9 +458,9 @@ ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull) else { /* - * All other parameter types must be sought in ecxt_param_list_info. - * NOTE: The last entry in the param array is always an - * entry with kind == PARAM_INVALID. + * All other parameter types must be sought in + * ecxt_param_list_info. NOTE: The last entry in the param array + * is always an entry with kind == PARAM_INVALID. */ ParamListInfo paramList = econtext->ecxt_param_list_info; char *thisParamName = expression->paramname; @@ -488,8 +489,8 @@ ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull) } if (!matchFound) paramList++; - } /* while */ - } /* if */ + } /* while */ + } /* if */ if (!matchFound) { @@ -605,7 +606,7 @@ GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull) * init_fcache - initialize a FuncExprState node during first use */ void -init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt) +init_fcache(Oid foid, FuncExprState * fcache, MemoryContext fcacheCxt) { AclResult aclresult; @@ -678,7 +679,7 @@ ExecEvalFuncArgs(FunctionCallInfo fcinfo, * Evaluate the arguments to a function and then the function itself. */ Datum -ExecMakeFunctionResult(FuncExprState *fcache, +ExecMakeFunctionResult(FuncExprState * fcache, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -881,7 +882,7 @@ ExecMakeFunctionResult(FuncExprState *fcache, * object. (If function returns an empty set, we just return NULL instead.) */ Tuplestorestate * -ExecMakeTableFunctionResult(ExprState *funcexpr, +ExecMakeTableFunctionResult(ExprState * funcexpr, ExprContext *econtext, TupleDesc expectedDesc, TupleDesc *returnDesc) @@ -899,14 +900,14 @@ ExecMakeTableFunctionResult(ExprState *funcexpr, bool returnsTuple = false; /* - * Normally the passed expression tree will be a FuncExprState, since the - * grammar only allows a function call at the top level of a table - * function reference. However, if the function doesn't return set then - * the planner might have replaced the function call via constant-folding - * or inlining. So if we see any other kind of expression node, execute - * it via the general ExecEvalExpr() code; the only difference is that - * we don't get a chance to pass a special ReturnSetInfo to any functions - * buried in the expression. + * Normally the passed expression tree will be a FuncExprState, since + * the grammar only allows a function call at the top level of a table + * function reference. However, if the function doesn't return set + * then the planner might have replaced the function call via + * constant-folding or inlining. So if we see any other kind of + * expression node, execute it via the general ExecEvalExpr() code; + * the only difference is that we don't get a chance to pass a special + * ReturnSetInfo to any functions buried in the expression. */ if (funcexpr && IsA(funcexpr, FuncExprState) && IsA(funcexpr->expr, FuncExpr)) @@ -924,7 +925,7 @@ ExecMakeTableFunctionResult(ExprState *funcexpr, */ if (fcache->func.fn_oid == InvalidOid) { - FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; + FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory); } @@ -933,9 +934,9 @@ ExecMakeTableFunctionResult(ExprState *funcexpr, * Evaluate the function's argument list. * * Note: ideally, we'd do this in the per-tuple context, but then the - * argument values would disappear when we reset the context in the - * inner loop. So do it in caller context. Perhaps we should make a - * separate context just to hold the evaluated arguments? + * argument values would disappear when we reset the context in + * the inner loop. So do it in caller context. Perhaps we should + * make a separate context just to hold the evaluated arguments? */ MemSet(&fcinfo, 0, sizeof(fcinfo)); fcinfo.flinfo = &(fcache->func); @@ -990,7 +991,8 @@ ExecMakeTableFunctionResult(ExprState *funcexpr, rsinfo.setDesc = NULL; /* - * Switch to short-lived context for calling the function or expression. + * Switch to short-lived context for calling the function or + * expression. */ callerContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); @@ -1004,9 +1006,9 @@ ExecMakeTableFunctionResult(ExprState *funcexpr, HeapTuple tuple; /* - * reset per-tuple memory context before each call of the - * function or expression. This cleans up any local memory the - * function may leak when called. + * reset per-tuple memory context before each call of the function + * or expression. This cleans up any local memory the function may + * leak when called. */ ResetExprContext(econtext); @@ -1157,7 +1159,7 @@ ExecMakeTableFunctionResult(ExprState *funcexpr, * ---------------------------------------------------------------- */ static Datum -ExecEvalFunc(FuncExprState *fcache, +ExecEvalFunc(FuncExprState * fcache, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -1167,7 +1169,7 @@ ExecEvalFunc(FuncExprState *fcache, */ if (fcache->func.fn_oid == InvalidOid) { - FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; + FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory); } @@ -1180,7 +1182,7 @@ ExecEvalFunc(FuncExprState *fcache, * ---------------------------------------------------------------- */ static Datum -ExecEvalOper(FuncExprState *fcache, +ExecEvalOper(FuncExprState * fcache, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -1190,7 +1192,7 @@ ExecEvalOper(FuncExprState *fcache, */ if (fcache->func.fn_oid == InvalidOid) { - OpExpr *op = (OpExpr *) fcache->xprstate.expr; + OpExpr *op = (OpExpr *) fcache->xprstate.expr; init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory); } @@ -1210,7 +1212,7 @@ ExecEvalOper(FuncExprState *fcache, * ---------------------------------------------------------------- */ static Datum -ExecEvalDistinct(FuncExprState *fcache, +ExecEvalDistinct(FuncExprState * fcache, ExprContext *econtext, bool *isNull) { @@ -1242,7 +1244,7 @@ ExecEvalDistinct(FuncExprState *fcache, if (argDone != ExprSingleResult) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("IS DISTINCT FROM does not support set arguments"))); + errmsg("IS DISTINCT FROM does not support set arguments"))); Assert(fcinfo.nargs == 2); if (fcinfo.argnull[0] && fcinfo.argnull[1]) @@ -1272,11 +1274,11 @@ ExecEvalDistinct(FuncExprState *fcache, * * Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean, * and we combine the results across all array elements using OR and AND - * (for ANY and ALL respectively). Of course we short-circuit as soon as + * (for ANY and ALL respectively). Of course we short-circuit as soon as * the result is known. */ static Datum -ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, +ExecEvalScalarArrayOp(ScalarArrayOpExprState * sstate, ExprContext *econtext, bool *isNull) { ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr; @@ -1310,12 +1312,12 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, if (argDone != ExprSingleResult) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("op ANY/ALL (array) does not support set arguments"))); + errmsg("op ANY/ALL (array) does not support set arguments"))); Assert(fcinfo.nargs == 2); /* - * If the array is NULL then we return NULL --- it's not very meaningful - * to do anything else, even if the operator isn't strict. + * If the array is NULL then we return NULL --- it's not very + * meaningful to do anything else, even if the operator isn't strict. */ if (fcinfo.argnull[1]) { @@ -1334,6 +1336,7 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr)); if (nitems <= 0) return BoolGetDatum(!useOr); + /* * If the scalar is NULL, and the function is strict, return NULL. * This is just to avoid having to test for strictness inside the @@ -1347,8 +1350,8 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, } /* - * We arrange to look up info about the element type only - * once per series of calls, assuming the element type doesn't change + * We arrange to look up info about the element type only once per + * series of calls, assuming the element type doesn't change * underneath us. */ if (sstate->element_type != ARR_ELEMTYPE(arr)) @@ -1370,8 +1373,8 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, s = (char *) ARR_DATA_PTR(arr); for (i = 0; i < nitems; i++) { - Datum elt; - Datum thisresult; + Datum elt; + Datum thisresult; /* Get array element */ elt = fetch_att(s, typbyval, typlen); @@ -1394,7 +1397,7 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, { result = BoolGetDatum(true); resultnull = false; - break; /* needn't look at any more elements */ + break; /* needn't look at any more elements */ } } else @@ -1403,7 +1406,7 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, { result = BoolGetDatum(false); resultnull = false; - break; /* needn't look at any more elements */ + break; /* needn't look at any more elements */ } } } @@ -1428,7 +1431,7 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, * ---------------------------------------------------------------- */ static Datum -ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull) +ExecEvalNot(BoolExprState * notclause, ExprContext *econtext, bool *isNull) { ExprState *clause; Datum expr_value; @@ -1456,7 +1459,7 @@ ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull) * ---------------------------------------------------------------- */ static Datum -ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull) +ExecEvalOr(BoolExprState * orExpr, ExprContext *econtext, bool *isNull) { List *clauses; List *clause; @@ -1504,7 +1507,7 @@ ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull) * ---------------------------------------------------------------- */ static Datum -ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull) +ExecEvalAnd(BoolExprState * andExpr, ExprContext *econtext, bool *isNull) { List *clauses; List *clause; @@ -1552,7 +1555,7 @@ ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull) * ---------------------------------------------------------------- */ static Datum -ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, +ExecEvalCase(CaseExprState * caseExpr, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) { List *clauses; @@ -1610,22 +1613,22 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, * ---------------------------------------------------------------- */ static Datum -ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, +ExecEvalArray(ArrayExprState * astate, ExprContext *econtext, bool *isNull) { - ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr; + ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr; ArrayType *result; - List *element; - Oid element_type = arrayExpr->element_typeid; - int ndims = arrayExpr->ndims; - int dims[MAXDIM]; - int lbs[MAXDIM]; + List *element; + Oid element_type = arrayExpr->element_typeid; + int ndims = arrayExpr->ndims; + int dims[MAXDIM]; + int lbs[MAXDIM]; if (ndims == 1) { - int nelems; - Datum *dvalues; - int i = 0; + int nelems; + Datum *dvalues; + int i = 0; nelems = length(astate->elements); @@ -1683,7 +1686,7 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, /* loop through and get data area from each element */ foreach(element, astate->elements) { - ExprState *e = (ExprState *) lfirst(element); + ExprState *e = (ExprState *) lfirst(element); bool eisnull; Datum arraydatum; ArrayType *array; @@ -1718,8 +1721,8 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, elem_ndims * sizeof(int)) != 0) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("multidimensional arrays must have array " - "expressions with matching dimensions"))); + errmsg("multidimensional arrays must have array " + "expressions with matching dimensions"))); } elem_ndatabytes = ARR_SIZE(array) - ARR_OVERHEAD(elem_ndims); @@ -1767,16 +1770,16 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, * ---------------------------------------------------------------- */ static Datum -ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext, +ExecEvalCoalesce(CoalesceExprState * coalesceExpr, ExprContext *econtext, bool *isNull) { - List *arg; + List *arg; /* Simply loop through until something NOT NULL is found */ foreach(arg, coalesceExpr->args) { - ExprState *e = (ExprState *) lfirst(arg); - Datum value; + ExprState *e = (ExprState *) lfirst(arg); + Datum value; value = ExecEvalExpr(e, econtext, isNull, NULL); if (!*isNull) @@ -1787,7 +1790,7 @@ ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext, *isNull = true; return (Datum) 0; } - + /* ---------------------------------------------------------------- * ExecEvalNullIf * @@ -1797,7 +1800,7 @@ ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext, * ---------------------------------------------------------------- */ static Datum -ExecEvalNullIf(FuncExprState *fcache, ExprContext *econtext, +ExecEvalNullIf(FuncExprState * fcache, ExprContext *econtext, bool *isNull) { Datum result; @@ -1856,7 +1859,7 @@ ExecEvalNullIf(FuncExprState *fcache, ExprContext *econtext, * ---------------------------------------------------------------- */ static Datum -ExecEvalNullTest(GenericExprState *nstate, +ExecEvalNullTest(GenericExprState * nstate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -1901,7 +1904,7 @@ ExecEvalNullTest(GenericExprState *nstate, * ---------------------------------------------------------------- */ static Datum -ExecEvalBooleanTest(GenericExprState *bstate, +ExecEvalBooleanTest(GenericExprState * bstate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -1987,7 +1990,7 @@ ExecEvalBooleanTest(GenericExprState *bstate, * datum) otherwise throw an error. */ static Datum -ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext, +ExecEvalCoerceToDomain(CoerceToDomainState * cstate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) { CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr; @@ -2009,43 +2012,44 @@ ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext, if (*isNull) ereport(ERROR, (errcode(ERRCODE_NOT_NULL_VIOLATION), - errmsg("domain %s does not allow NULL values", - format_type_be(ctest->resulttype)))); + errmsg("domain %s does not allow NULL values", + format_type_be(ctest->resulttype)))); break; case DOM_CONSTRAINT_CHECK: - { - Datum conResult; - bool conIsNull; - Datum save_datum; - bool save_isNull; + { + Datum conResult; + bool conIsNull; + Datum save_datum; + bool save_isNull; - /* - * Set up value to be returned by CoerceToDomainValue nodes. - * We must save and restore prior setting of econtext's - * domainValue fields, in case this node is itself within - * a check expression for another domain. - */ - save_datum = econtext->domainValue_datum; - save_isNull = econtext->domainValue_isNull; + /* + * Set up value to be returned by CoerceToDomainValue + * nodes. We must save and restore prior setting of + * econtext's domainValue fields, in case this node is + * itself within a check expression for another + * domain. + */ + save_datum = econtext->domainValue_datum; + save_isNull = econtext->domainValue_isNull; - econtext->domainValue_datum = result; - econtext->domainValue_isNull = *isNull; + econtext->domainValue_datum = result; + econtext->domainValue_isNull = *isNull; - conResult = ExecEvalExpr(con->check_expr, - econtext, &conIsNull, NULL); + conResult = ExecEvalExpr(con->check_expr, + econtext, &conIsNull, NULL); - if (!conIsNull && - !DatumGetBool(conResult)) - ereport(ERROR, - (errcode(ERRCODE_CHECK_VIOLATION), - errmsg("value for domain %s violates CHECK constraint \"%s\"", - format_type_be(ctest->resulttype), - con->name))); - econtext->domainValue_datum = save_datum; - econtext->domainValue_isNull = save_isNull; + if (!conIsNull && + !DatumGetBool(conResult)) + ereport(ERROR, + (errcode(ERRCODE_CHECK_VIOLATION), + errmsg("value for domain %s violates CHECK constraint \"%s\"", + format_type_be(ctest->resulttype), + con->name))); + econtext->domainValue_datum = save_datum; + econtext->domainValue_isNull = save_isNull; - break; - } + break; + } default: elog(ERROR, "unrecognized constraint type: %d", (int) con->constrainttype); @@ -2063,7 +2067,7 @@ ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext, * Return the value stored by CoerceToDomain. */ static Datum -ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal, +ExecEvalCoerceToDomainValue(CoerceToDomainValue * conVal, ExprContext *econtext, bool *isNull) { *isNull = econtext->domainValue_isNull; @@ -2077,7 +2081,7 @@ ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal, * ---------------------------------------------------------------- */ static Datum -ExecEvalFieldSelect(GenericExprState *fstate, +ExecEvalFieldSelect(GenericExprState * fstate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -2141,7 +2145,7 @@ ExecEvalFieldSelect(GenericExprState *fstate, * ---------------------------------------------------------------- */ Datum -ExecEvalExpr(ExprState *expression, +ExecEvalExpr(ExprState * expression, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -2308,7 +2312,7 @@ ExecEvalExpr(ExprState *expression, * Same as above, but get into the right allocation context explicitly. */ Datum -ExecEvalExprSwitchContext(ExprState *expression, +ExecEvalExprSwitchContext(ExprState * expression, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone) @@ -2327,7 +2331,7 @@ ExecEvalExprSwitchContext(ExprState *expression, * ExecInitExpr: prepare an expression tree for execution * * This function builds and returns an ExprState tree paralleling the given - * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr + * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr * for execution. Because the Expr tree itself is read-only as far as * ExecInitExpr and ExecEvalExpr are concerned, several different executions * of the same plan tree can occur concurrently. @@ -2337,7 +2341,7 @@ ExecEvalExprSwitchContext(ExprState *expression, * the same as the per-query context of the associated ExprContext. * * Any Aggref and SubPlan nodes found in the tree are added to the lists - * of such nodes held by the parent PlanState. Otherwise, we do very little + * of such nodes held by the parent PlanState. Otherwise, we do very little * initialization here other than building the state-node tree. Any nontrivial * work associated with initializing runtime info for a node should happen * during the first actual evaluation of that node. (This policy lets us @@ -2356,7 +2360,7 @@ ExecEvalExprSwitchContext(ExprState *expression, * This case should usually come through ExecPrepareExpr, not directly here. */ ExprState * -ExecInitExpr(Expr *node, PlanState *parent) +ExecInitExpr(Expr *node, PlanState * parent) { ExprState *state; @@ -2373,7 +2377,7 @@ ExecInitExpr(Expr *node, PlanState *parent) break; case T_Aggref: { - Aggref *aggref = (Aggref *) node; + Aggref *aggref = (Aggref *) node; AggrefExprState *astate = makeNode(AggrefExprState); if (parent && IsA(parent, AggState)) @@ -2389,8 +2393,8 @@ ExecInitExpr(Expr *node, PlanState *parent) /* * Complain if the aggregate's argument contains any * aggregates; nested agg functions are semantically - * nonsensical. (This should have been caught earlier, - * but we defend against it here anyway.) + * nonsensical. (This should have been caught + * earlier, but we defend against it here anyway.) */ if (naggs != aggstate->numaggs) ereport(ERROR, @@ -2433,41 +2437,41 @@ ExecInitExpr(Expr *node, PlanState *parent) fstate->args = (List *) ExecInitExpr((Expr *) funcexpr->args, parent); - fstate->func.fn_oid = InvalidOid; /* not initialized */ + fstate->func.fn_oid = InvalidOid; /* not initialized */ state = (ExprState *) fstate; } break; case T_OpExpr: { - OpExpr *opexpr = (OpExpr *) node; + OpExpr *opexpr = (OpExpr *) node; FuncExprState *fstate = makeNode(FuncExprState); fstate->args = (List *) ExecInitExpr((Expr *) opexpr->args, parent); - fstate->func.fn_oid = InvalidOid; /* not initialized */ + fstate->func.fn_oid = InvalidOid; /* not initialized */ state = (ExprState *) fstate; } break; case T_DistinctExpr: { - DistinctExpr *distinctexpr = (DistinctExpr *) node; + DistinctExpr *distinctexpr = (DistinctExpr *) node; FuncExprState *fstate = makeNode(FuncExprState); fstate->args = (List *) ExecInitExpr((Expr *) distinctexpr->args, parent); - fstate->func.fn_oid = InvalidOid; /* not initialized */ + fstate->func.fn_oid = InvalidOid; /* not initialized */ state = (ExprState *) fstate; } break; case T_ScalarArrayOpExpr: { - ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node; + ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node; ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState); sstate->fxprstate.args = (List *) ExecInitExpr((Expr *) opexpr->args, parent); - sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */ - sstate->element_type = InvalidOid; /* ditto */ + sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */ + sstate->element_type = InvalidOid; /* ditto */ state = (ExprState *) sstate; } break; @@ -2484,7 +2488,7 @@ ExecInitExpr(Expr *node, PlanState *parent) case T_SubPlan: { /* Keep this in sync with ExecInitExprInitPlan, below */ - SubPlan *subplan = (SubPlan *) node; + SubPlan *subplan = (SubPlan *) node; SubPlanState *sstate = makeNode(SubPlanState); if (!parent) @@ -2492,7 +2496,8 @@ ExecInitExpr(Expr *node, PlanState *parent) /* * Here we just add the SubPlanState nodes to - * parent->subPlan. The subplans will be initialized later. + * parent->subPlan. The subplans will be initialized + * later. */ parent->subPlan = lcons(sstate, parent->subPlan); sstate->sub_estate = NULL; @@ -2508,7 +2513,7 @@ ExecInitExpr(Expr *node, PlanState *parent) break; case T_FieldSelect: { - FieldSelect *fselect = (FieldSelect *) node; + FieldSelect *fselect = (FieldSelect *) node; GenericExprState *gstate = makeNode(GenericExprState); gstate->arg = ExecInitExpr(fselect->arg, parent); @@ -2517,7 +2522,7 @@ ExecInitExpr(Expr *node, PlanState *parent) break; case T_RelabelType: { - RelabelType *relabel = (RelabelType *) node; + RelabelType *relabel = (RelabelType *) node; GenericExprState *gstate = makeNode(GenericExprState); gstate->arg = ExecInitExpr(relabel->arg, parent); @@ -2552,10 +2557,10 @@ ExecInitExpr(Expr *node, PlanState *parent) break; case T_ArrayExpr: { - ArrayExpr *arrayexpr = (ArrayExpr *) node; + ArrayExpr *arrayexpr = (ArrayExpr *) node; ArrayExprState *astate = makeNode(ArrayExprState); - FastList outlist; - List *inlist; + FastList outlist; + List *inlist; FastListInit(&outlist); foreach(inlist, arrayexpr->elements) @@ -2585,8 +2590,8 @@ ExecInitExpr(Expr *node, PlanState *parent) FastListInit(&outlist); foreach(inlist, coalesceexpr->args) { - Expr *e = (Expr *) lfirst(inlist); - ExprState *estate; + Expr *e = (Expr *) lfirst(inlist); + ExprState *estate; estate = ExecInitExpr(e, parent); FastAppend(&outlist, estate); @@ -2602,7 +2607,7 @@ ExecInitExpr(Expr *node, PlanState *parent) fstate->args = (List *) ExecInitExpr((Expr *) nullifexpr->args, parent); - fstate->func.fn_oid = InvalidOid; /* not initialized */ + fstate->func.fn_oid = InvalidOid; /* not initialized */ state = (ExprState *) fstate; } break; @@ -2617,7 +2622,7 @@ ExecInitExpr(Expr *node, PlanState *parent) break; case T_BooleanTest: { - BooleanTest *btest = (BooleanTest *) node; + BooleanTest *btest = (BooleanTest *) node; GenericExprState *gstate = makeNode(GenericExprState); gstate->arg = ExecInitExpr(btest->arg, parent); @@ -2626,7 +2631,7 @@ ExecInitExpr(Expr *node, PlanState *parent) break; case T_CoerceToDomain: { - CoerceToDomain *ctest = (CoerceToDomain *) node; + CoerceToDomain *ctest = (CoerceToDomain *) node; CoerceToDomainState *cstate = makeNode(CoerceToDomainState); cstate->arg = ExecInitExpr(ctest->arg, parent); @@ -2636,7 +2641,7 @@ ExecInitExpr(Expr *node, PlanState *parent) break; case T_TargetEntry: { - TargetEntry *tle = (TargetEntry *) node; + TargetEntry *tle = (TargetEntry *) node; GenericExprState *gstate = makeNode(GenericExprState); gstate->arg = ExecInitExpr(tle->expr, parent); @@ -2673,12 +2678,12 @@ ExecInitExpr(Expr *node, PlanState *parent) /* * ExecInitExprInitPlan --- initialize a subplan expr that's being handled - * as an InitPlan. This is identical to ExecInitExpr's handling of a regular + * as an InitPlan. This is identical to ExecInitExpr's handling of a regular * subplan expr, except we do NOT want to add the node to the parent's * subplan list. */ SubPlanState * -ExecInitExprInitPlan(SubPlan *node, PlanState *parent) +ExecInitExprInitPlan(SubPlan *node, PlanState * parent) { SubPlanState *sstate = makeNode(SubPlanState); @@ -2704,7 +2709,7 @@ ExecInitExprInitPlan(SubPlan *node, PlanState *parent) * This differs from ExecInitExpr in that we don't assume the caller is * already running in the EState's per-query context. Also, we apply * fix_opfuncids() to the passed expression tree to be sure it is ready - * to run. (In ordinary Plan trees the planner will have fixed opfuncids, + * to run. (In ordinary Plan trees the planner will have fixed opfuncids, * but callers outside the executor will not have done this.) */ ExprState * @@ -2988,8 +2993,8 @@ ExecTargetList(List *targetlist, if (itemIsDone[resind] == ExprEndResult) { /* - * Oh dear, this item is returning an empty - * set. Guess we can't make a tuple after all. + * Oh dear, this item is returning an empty set. + * Guess we can't make a tuple after all. */ *isDone = ExprEndResult; break; diff --git a/src/backend/executor/execScan.c b/src/backend/executor/execScan.c index 9352c79d81..35007cf0cc 100644 --- a/src/backend/executor/execScan.c +++ b/src/backend/executor/execScan.c @@ -12,7 +12,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execScan.c,v 1.23 2003/02/03 15:07:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execScan.c,v 1.24 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,7 +45,7 @@ static bool tlist_matches_tupdesc(List *tlist, Index varno, TupleDesc tupdesc); * ---------------------------------------------------------------- */ TupleTableSlot * -ExecScan(ScanState *node, +ExecScan(ScanState * node, ExecScanAccessMtd accessMtd) /* function returning a tuple */ { EState *estate; @@ -134,9 +134,10 @@ ExecScan(ScanState *node, if (projInfo) { /* - * Form a projection tuple, store it in the result tuple slot - * and return it --- unless we find we can project no tuples - * from this scan tuple, in which case continue scan. + * Form a projection tuple, store it in the result tuple + * slot and return it --- unless we find we can project no + * tuples from this scan tuple, in which case continue + * scan. */ resultSlot = ExecProject(projInfo, &isDone); if (isDone != ExprEndResult) @@ -175,13 +176,13 @@ ExecScan(ScanState *node, * ExecAssignScanType must have been called already. */ void -ExecAssignScanProjectionInfo(ScanState *node) +ExecAssignScanProjectionInfo(ScanState * node) { - Scan *scan = (Scan *) node->ps.plan; + Scan *scan = (Scan *) node->ps.plan; if (tlist_matches_tupdesc(scan->plan.targetlist, scan->scanrelid, - node->ss_ScanTupleSlot->ttc_tupleDescriptor)) + node->ss_ScanTupleSlot->ttc_tupleDescriptor)) node->ps.ps_ProjInfo = NULL; else ExecAssignProjectionInfo(&node->ps); @@ -190,13 +191,13 @@ ExecAssignScanProjectionInfo(ScanState *node) static bool tlist_matches_tupdesc(List *tlist, Index varno, TupleDesc tupdesc) { - int numattrs = tupdesc->natts; - int attrno; + int numattrs = tupdesc->natts; + int attrno; for (attrno = 1; attrno <= numattrs; attrno++) { Form_pg_attribute att_tup = tupdesc->attrs[attrno - 1]; - Var *var; + Var *var; if (tlist == NIL) return false; /* tlist too short */ diff --git a/src/backend/executor/execTuples.c b/src/backend/executor/execTuples.c index 976c152236..c2145b7eca 100644 --- a/src/backend/executor/execTuples.c +++ b/src/backend/executor/execTuples.c @@ -15,7 +15,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execTuples.c,v 1.67 2003/07/21 17:05:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execTuples.c,v 1.68 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -482,7 +482,7 @@ ExecSetSlotDescriptorIsNew(TupleTableSlot *slot, /* slot to change */ * ---------------- */ void -ExecInitResultTupleSlot(EState *estate, PlanState *planstate) +ExecInitResultTupleSlot(EState *estate, PlanState * planstate) { INIT_SLOT_DEFS; INIT_SLOT_ALLOC; @@ -494,7 +494,7 @@ ExecInitResultTupleSlot(EState *estate, PlanState *planstate) * ---------------- */ void -ExecInitScanTupleSlot(EState *estate, ScanState *scanstate) +ExecInitScanTupleSlot(EState *estate, ScanState * scanstate) { INIT_SLOT_DEFS; INIT_SLOT_ALLOC; @@ -807,7 +807,7 @@ do_text_output_multiline(TupOutputState *tstate, char *text) if (eol) *eol++ = '\0'; else - eol = text + strlen(text); + eol = text +strlen(text); do_tup_output(tstate, &text); text = eol; diff --git a/src/backend/executor/execUtils.c b/src/backend/executor/execUtils.c index ca4ff192f4..f87708d392 100644 --- a/src/backend/executor/execUtils.c +++ b/src/backend/executor/execUtils.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execUtils.c,v 1.100 2003/05/28 16:03:56 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execUtils.c,v 1.101 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -166,8 +166,8 @@ CreateExecutorState(void) ALLOCSET_DEFAULT_MAXSIZE); /* - * Make the EState node within the per-query context. This way, - * we don't need a separate pfree() operation for it at shutdown. + * Make the EState node within the per-query context. This way, we + * don't need a separate pfree() operation for it at shutdown. */ oldcontext = MemoryContextSwitchTo(qcontext); @@ -248,6 +248,7 @@ FreeExecutorState(EState *estate) FreeExprContext((ExprContext *) lfirst(estate->es_exprcontexts)); /* FreeExprContext removed the list link for us */ } + /* * Free the per-query memory context, thereby releasing all working * memory, including the EState node itself. @@ -310,10 +311,10 @@ CreateExprContext(EState *estate) econtext->ecxt_callbacks = NULL; /* - * Link the ExprContext into the EState to ensure it is shut down - * when the EState is freed. Because we use lcons(), shutdowns will - * occur in reverse order of creation, which may not be essential - * but can't hurt. + * Link the ExprContext into the EState to ensure it is shut down when + * the EState is freed. Because we use lcons(), shutdowns will occur + * in reverse order of creation, which may not be essential but can't + * hurt. */ estate->es_exprcontexts = lcons(econtext, estate->es_exprcontexts); @@ -377,14 +378,14 @@ MakePerTupleExprContext(EState *estate) /* ---------------- * ExecAssignExprContext * - * This initializes the ps_ExprContext field. It is only necessary + * This initializes the ps_ExprContext field. It is only necessary * to do this for nodes which use ExecQual or ExecProject - * because those routines require an econtext. Other nodes that + * because those routines require an econtext. Other nodes that * don't have to evaluate expressions don't need to do this. * ---------------- */ void -ExecAssignExprContext(EState *estate, PlanState *planstate) +ExecAssignExprContext(EState *estate, PlanState * planstate) { planstate->ps_ExprContext = CreateExprContext(estate); } @@ -394,7 +395,7 @@ ExecAssignExprContext(EState *estate, PlanState *planstate) * ---------------- */ void -ExecAssignResultType(PlanState *planstate, +ExecAssignResultType(PlanState * planstate, TupleDesc tupDesc, bool shouldFree) { TupleTableSlot *slot = planstate->ps_ResultTupleSlot; @@ -407,7 +408,7 @@ ExecAssignResultType(PlanState *planstate, * ---------------- */ void -ExecAssignResultTypeFromOuterPlan(PlanState *planstate) +ExecAssignResultTypeFromOuterPlan(PlanState * planstate) { PlanState *outerPlan; TupleDesc tupDesc; @@ -423,7 +424,7 @@ ExecAssignResultTypeFromOuterPlan(PlanState *planstate) * ---------------- */ void -ExecAssignResultTypeFromTL(PlanState *planstate) +ExecAssignResultTypeFromTL(PlanState * planstate) { bool hasoid = false; TupleDesc tupDesc; @@ -445,9 +446,9 @@ ExecAssignResultTypeFromTL(PlanState *planstate) * each of the child plans of the topmost Append plan. So, this is * ugly but it works, for now ... * - * SELECT INTO is also pretty grotty, because we don't yet have the - * INTO relation's descriptor at this point; we have to look aside - * at a flag set by InitPlan(). + * SELECT INTO is also pretty grotty, because we don't yet have the INTO + * relation's descriptor at this point; we have to look aside at a + * flag set by InitPlan(). */ if (planstate->state->es_force_oids) hasoid = true; @@ -465,9 +466,9 @@ ExecAssignResultTypeFromTL(PlanState *planstate) } /* - * ExecTypeFromTL needs the parse-time representation of the tlist, not - * a list of ExprStates. This is good because some plan nodes don't - * bother to set up planstate->targetlist ... + * ExecTypeFromTL needs the parse-time representation of the tlist, + * not a list of ExprStates. This is good because some plan nodes + * don't bother to set up planstate->targetlist ... */ tupDesc = ExecTypeFromTL(planstate->plan->targetlist, hasoid); ExecAssignResultType(planstate, tupDesc, true); @@ -478,7 +479,7 @@ ExecAssignResultTypeFromTL(PlanState *planstate) * ---------------- */ TupleDesc -ExecGetResultType(PlanState *planstate) +ExecGetResultType(PlanState * planstate) { TupleTableSlot *slot = planstate->ps_ResultTupleSlot; @@ -524,7 +525,7 @@ ExecBuildProjectionInfo(List *targetList, * ---------------- */ void -ExecAssignProjectionInfo(PlanState *planstate) +ExecAssignProjectionInfo(PlanState * planstate) { planstate->ps_ProjInfo = ExecBuildProjectionInfo(planstate->targetlist, @@ -543,7 +544,7 @@ ExecAssignProjectionInfo(PlanState *planstate) * ---------------- */ void -ExecFreeExprContext(PlanState *planstate) +ExecFreeExprContext(PlanState * planstate) { ExprContext *econtext; @@ -575,7 +576,7 @@ ExecFreeExprContext(PlanState *planstate) * ---------------- */ TupleDesc -ExecGetScanType(ScanState *scanstate) +ExecGetScanType(ScanState * scanstate) { TupleTableSlot *slot = scanstate->ss_ScanTupleSlot; @@ -587,7 +588,7 @@ ExecGetScanType(ScanState *scanstate) * ---------------- */ void -ExecAssignScanType(ScanState *scanstate, +ExecAssignScanType(ScanState * scanstate, TupleDesc tupDesc, bool shouldFree) { TupleTableSlot *slot = scanstate->ss_ScanTupleSlot; @@ -600,7 +601,7 @@ ExecAssignScanType(ScanState *scanstate, * ---------------- */ void -ExecAssignScanTypeFromOuterPlan(ScanState *scanstate) +ExecAssignScanTypeFromOuterPlan(ScanState * scanstate) { PlanState *outerPlan; TupleDesc tupDesc; @@ -795,8 +796,8 @@ ExecInsertIndexTuples(TupleTableSlot *slot, /* * We will use the EState's per-tuple context for evaluating - * predicates and index expressions (creating it if it's not - * already there). + * predicates and index expressions (creating it if it's not already + * there). */ econtext = GetPerTupleExprContext(estate); @@ -841,8 +842,8 @@ ExecInsertIndexTuples(TupleTableSlot *slot, /* * FormIndexDatum fills in its datum and null parameters with - * attribute information taken from the given heap tuple. - * It also computes any expressions needed. + * attribute information taken from the given heap tuple. It also + * computes any expressions needed. */ FormIndexDatum(indexInfo, heapTuple, @@ -878,7 +879,7 @@ ExecInsertIndexTuples(TupleTableSlot *slot, * Add changed parameters to a plan node's chgParam set */ void -UpdateChangedParamSet(PlanState *node, Bitmapset *newchg) +UpdateChangedParamSet(PlanState * node, Bitmapset * newchg) { Bitmapset *parmset; @@ -887,6 +888,7 @@ UpdateChangedParamSet(PlanState *node, Bitmapset *newchg) * Don't include anything else into its chgParam set. */ parmset = bms_intersect(node->plan->allParam, newchg); + /* * Keep node->chgParam == NULL if there's not actually any members; * this allows the simplest possible tests in executor node files. diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c index c8df7ccb83..ebc3cbcac3 100644 --- a/src/backend/executor/functions.c +++ b/src/backend/executor/functions.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/functions.c,v 1.69 2003/07/28 18:33:18 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/functions.c,v 1.70 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -29,8 +29,8 @@ /* - * We have an execution_state record for each query in a function. Each - * record contains a querytree and plantree for its query. If the query + * We have an execution_state record for each query in a function. Each + * record contains a querytree and plantree for its query. If the query * is currently in F_EXEC_RUN state then there's a QueryDesc too. */ typedef enum @@ -83,7 +83,7 @@ static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache); static TupleTableSlot *postquel_getnext(execution_state *es); static void postquel_end(execution_state *es); static void postquel_sub_params(SQLFunctionCachePtr fcache, - FunctionCallInfo fcinfo); + FunctionCallInfo fcinfo); static Datum postquel_execute(execution_state *es, FunctionCallInfo fcinfo, SQLFunctionCachePtr fcache); @@ -177,11 +177,11 @@ init_sql_fcache(FmgrInfo *finfo) if (rettype == ANYARRAYOID || rettype == ANYELEMENTOID) { rettype = get_fn_expr_rettype(finfo); - if (rettype == InvalidOid) /* this probably should not happen */ + if (rettype == InvalidOid) /* this probably should not happen */ ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("could not determine actual result type for function declared %s", - format_type_be(procedureStruct->prorettype)))); + format_type_be(procedureStruct->prorettype)))); } /* Now look up the actual result type */ @@ -226,7 +226,7 @@ init_sql_fcache(FmgrInfo *finfo) fcache->funcSlot = NULL; /* - * Parse and plan the queries. We need the argument type info to pass + * Parse and plan the queries. We need the argument type info to pass * to the parser. */ nargs = procedureStruct->pronargs; @@ -234,7 +234,7 @@ init_sql_fcache(FmgrInfo *finfo) if (nargs > 0) { - int argnum; + int argnum; argOidVect = (Oid *) palloc(nargs * sizeof(Oid)); memcpy(argOidVect, @@ -243,7 +243,7 @@ init_sql_fcache(FmgrInfo *finfo) /* Resolve any polymorphic argument types */ for (argnum = 0; argnum < nargs; argnum++) { - Oid argtype = argOidVect[argnum]; + Oid argtype = argOidVect[argnum]; if (argtype == ANYARRAYOID || argtype == ANYELEMENTOID) { @@ -309,7 +309,7 @@ postquel_getnext(execution_state *es) /* * If it's the function's last command, and it's a SELECT, fetch one - * row at a time so we can return the results. Otherwise just run it + * row at a time so we can return the results. Otherwise just run it * to completion. */ if (LAST_POSTQUEL_COMMAND(es) && es->qd->operation == CMD_SELECT) @@ -655,14 +655,14 @@ sql_exec_error_callback(void *arg) /* * Try to determine where in the function we failed. If there is a * query with non-null QueryDesc, finger it. (We check this rather - * than looking for F_EXEC_RUN state, so that errors during ExecutorStart - * or ExecutorEnd are blamed on the appropriate query; see postquel_start - * and postquel_end.) + * than looking for F_EXEC_RUN state, so that errors during + * ExecutorStart or ExecutorEnd are blamed on the appropriate query; + * see postquel_start and postquel_end.) */ if (fcache) { execution_state *es; - int query_num; + int query_num; es = fcache->func_state; query_num = 1; diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c index f0537cf5d9..5cf448e772 100644 --- a/src/backend/executor/nodeAgg.c +++ b/src/backend/executor/nodeAgg.c @@ -45,7 +45,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeAgg.c,v 1.112 2003/08/01 00:15:21 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeAgg.c,v 1.113 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -173,12 +173,12 @@ typedef struct AggStatePerGroupData * later input value. Only the first non-NULL input will be * auto-substituted. */ -} AggStatePerGroupData; +} AggStatePerGroupData; /* * To implement hashed aggregation, we need a hashtable that stores a * representative tuple and an array of AggStatePerGroup structs for each - * distinct set of GROUP BY column values. We compute the hash key from + * distinct set of GROUP BY column values. We compute the hash key from * the GROUP BY columns. */ typedef struct AggHashEntryData *AggHashEntry; @@ -188,27 +188,27 @@ typedef struct AggHashEntryData TupleHashEntryData shared; /* common header for hash table entries */ /* per-aggregate transition status array - must be last! */ AggStatePerGroupData pergroup[1]; /* VARIABLE LENGTH ARRAY */ -} AggHashEntryData; /* VARIABLE LENGTH STRUCT */ +} AggHashEntryData; /* VARIABLE LENGTH STRUCT */ static void initialize_aggregates(AggState *aggstate, - AggStatePerAgg peragg, - AggStatePerGroup pergroup); + AggStatePerAgg peragg, + AggStatePerGroup pergroup); static void advance_transition_function(AggState *aggstate, - AggStatePerAgg peraggstate, - AggStatePerGroup pergroupstate, - Datum newVal, bool isNull); + AggStatePerAgg peraggstate, + AggStatePerGroup pergroupstate, + Datum newVal, bool isNull); static void advance_aggregates(AggState *aggstate, AggStatePerGroup pergroup); static void process_sorted_aggregate(AggState *aggstate, - AggStatePerAgg peraggstate, - AggStatePerGroup pergroupstate); + AggStatePerAgg peraggstate, + AggStatePerGroup pergroupstate); static void finalize_aggregate(AggState *aggstate, - AggStatePerAgg peraggstate, - AggStatePerGroup pergroupstate, - Datum *resultVal, bool *resultIsNull); + AggStatePerAgg peraggstate, + AggStatePerGroup pergroupstate, + Datum *resultVal, bool *resultIsNull); static void build_hash_table(AggState *aggstate); static AggHashEntry lookup_hash_entry(AggState *aggstate, - TupleTableSlot *slot); + TupleTableSlot *slot); static TupleTableSlot *agg_retrieve_direct(AggState *aggstate); static void agg_fill_hash_table(AggState *aggstate); static TupleTableSlot *agg_retrieve_hash_table(AggState *aggstate); @@ -231,7 +231,7 @@ initialize_aggregates(AggState *aggstate, { AggStatePerAgg peraggstate = &peragg[aggno]; AggStatePerGroup pergroupstate = &pergroup[aggno]; - Aggref *aggref = peraggstate->aggref; + Aggref *aggref = peraggstate->aggref; /* * Start a fresh sort operation for each DISTINCT aggregate. @@ -265,18 +265,18 @@ initialize_aggregates(AggState *aggstate, oldContext = MemoryContextSwitchTo(aggstate->aggcontext); pergroupstate->transValue = datumCopy(peraggstate->initValue, - peraggstate->transtypeByVal, - peraggstate->transtypeLen); + peraggstate->transtypeByVal, + peraggstate->transtypeLen); MemoryContextSwitchTo(oldContext); } pergroupstate->transValueIsNull = peraggstate->initValueIsNull; /* - * If the initial value for the transition state doesn't exist in the - * pg_aggregate table then we will let the first non-NULL value - * returned from the outer procNode become the initial value. (This is - * useful for aggregates like max() and min().) The noTransValue flag - * signals that we still need to do this. + * If the initial value for the transition state doesn't exist in + * the pg_aggregate table then we will let the first non-NULL + * value returned from the outer procNode become the initial + * value. (This is useful for aggregates like max() and min().) + * The noTransValue flag signals that we still need to do this. */ pergroupstate->noTransValue = peraggstate->initValueIsNull; } @@ -299,8 +299,8 @@ advance_transition_function(AggState *aggstate, if (peraggstate->transfn.fn_strict) { /* - * For a strict transfn, nothing happens at a NULL input - * tuple; we just keep the prior transValue. + * For a strict transfn, nothing happens at a NULL input tuple; we + * just keep the prior transValue. */ if (isNull) return; @@ -314,12 +314,13 @@ advance_transition_function(AggState *aggstate, * here is OK.) * * We must copy the datum into aggcontext if it is pass-by-ref. - * We do not need to pfree the old transValue, since it's NULL. + * We do not need to pfree the old transValue, since it's + * NULL. */ oldContext = MemoryContextSwitchTo(aggstate->aggcontext); pergroupstate->transValue = datumCopy(newVal, - peraggstate->transtypeByVal, - peraggstate->transtypeLen); + peraggstate->transtypeByVal, + peraggstate->transtypeLen); pergroupstate->transValueIsNull = false; pergroupstate->noTransValue = false; MemoryContextSwitchTo(oldContext); @@ -363,12 +364,12 @@ advance_transition_function(AggState *aggstate, newVal = FunctionCallInvoke(&fcinfo); /* - * If pass-by-ref datatype, must copy the new value into aggcontext and - * pfree the prior transValue. But if transfn returned a pointer to its - * first input, we don't need to do anything. + * If pass-by-ref datatype, must copy the new value into aggcontext + * and pfree the prior transValue. But if transfn returned a pointer + * to its first input, we don't need to do anything. */ if (!peraggstate->transtypeByVal && - DatumGetPointer(newVal) != DatumGetPointer(pergroupstate->transValue)) + DatumGetPointer(newVal) != DatumGetPointer(pergroupstate->transValue)) { if (!fcinfo.isnull) { @@ -388,7 +389,7 @@ advance_transition_function(AggState *aggstate, } /* - * Advance all the aggregates for one input tuple. The input tuple + * Advance all the aggregates for one input tuple. The input tuple * has been stored in tmpcontext->ecxt_scantuple, so that it is accessible * to ExecEvalExpr. pergroup is the array of per-group structs to use * (this might be in a hashtable entry). @@ -467,8 +468,8 @@ process_sorted_aggregate(AggState *aggstate, continue; /* - * Clear and select the working context for evaluation of - * the equality function and transition function. + * Clear and select the working context for evaluation of the + * equality function and transition function. */ MemoryContextReset(workcontext); oldContext = MemoryContextSwitchTo(workcontext); @@ -570,9 +571,9 @@ finalize_aggregate(AggState *aggstate, static void build_hash_table(AggState *aggstate) { - Agg *node = (Agg *) aggstate->ss.ps.plan; - MemoryContext tmpmem = aggstate->tmpcontext->ecxt_per_tuple_memory; - Size entrysize; + Agg *node = (Agg *) aggstate->ss.ps.plan; + MemoryContext tmpmem = aggstate->tmpcontext->ecxt_per_tuple_memory; + Size entrysize; Assert(node->aggstrategy == AGG_HASHED); Assert(node->numGroups > 0); @@ -622,9 +623,9 @@ lookup_hash_entry(AggState *aggstate, TupleTableSlot *slot) * 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 grouped or plain - * aggregation is selected. In grouped aggregation, we produce a result + * aggregation is selected. In grouped aggregation, we produce a result * row for each group; in plain aggregation there's a single result row - * for the whole query. In either case, the value of each aggregate is + * for the whole query. In either case, the value of each aggregate is * stored in the expression context to be used when ExecProject evaluates * the result tuple. */ @@ -641,9 +642,7 @@ ExecAgg(AggState *node) return agg_retrieve_hash_table(node); } else - { return agg_retrieve_direct(node); - } } /* @@ -736,7 +735,7 @@ agg_retrieve_direct(AggState *aggstate) firstSlot, InvalidBuffer, true); - aggstate->grp_firstTuple = NULL; /* don't keep two pointers */ + aggstate->grp_firstTuple = NULL; /* don't keep two pointers */ /* set up for first advance_aggregates call */ tmpcontext->ecxt_scantuple = firstSlot; @@ -773,7 +772,7 @@ agg_retrieve_direct(AggState *aggstate) firstSlot->ttc_tupleDescriptor, node->numCols, node->grpColIdx, aggstate->eqfunctions, - tmpcontext->ecxt_per_tuple_memory)) + tmpcontext->ecxt_per_tuple_memory)) { /* * Save the first input tuple of the next group. @@ -806,15 +805,15 @@ agg_retrieve_direct(AggState *aggstate) * 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. + * 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. + * The values returned for the aggregates will be the initial values + * of the transition functions. */ if (TupIsNull(firstSlot)) { @@ -872,7 +871,7 @@ agg_fill_hash_table(AggState *aggstate) { PlanState *outerPlan; ExprContext *tmpcontext; - AggHashEntry entry; + AggHashEntry entry; TupleTableSlot *outerslot; /* @@ -883,8 +882,8 @@ agg_fill_hash_table(AggState *aggstate) tmpcontext = aggstate->tmpcontext; /* - * Process each outer-plan tuple, and then fetch the next one, - * until we exhaust the outer plan. + * Process each outer-plan tuple, and then fetch the next one, until + * we exhaust the outer plan. */ for (;;) { @@ -921,8 +920,8 @@ agg_retrieve_hash_table(AggState *aggstate) bool *aggnulls; AggStatePerAgg peragg; AggStatePerGroup pergroup; - TupleHashTable hashtable; - AggHashEntry entry; + TupleHashTable hashtable; + AggHashEntry entry; TupleTableSlot *firstSlot; TupleTableSlot *resultSlot; int aggno; @@ -1045,20 +1044,20 @@ ExecInitAgg(Agg *node, EState *estate) aggstate->hashtable = NULL; /* - * Create expression contexts. We need two, one for per-input-tuple - * processing and one for per-output-tuple processing. We cheat a little - * by using ExecAssignExprContext() to build both. + * Create expression contexts. We need two, one for per-input-tuple + * processing and one for per-output-tuple processing. We cheat a + * little by using ExecAssignExprContext() to build both. */ ExecAssignExprContext(estate, &aggstate->ss.ps); aggstate->tmpcontext = aggstate->ss.ps.ps_ExprContext; ExecAssignExprContext(estate, &aggstate->ss.ps); /* - * We also need a long-lived memory context for holding hashtable - * data structures and transition values. NOTE: the details of what - * is stored in aggcontext and what is stored in the regular per-query - * memory context are driven by a simple decision: we want to reset the - * aggcontext in ExecReScanAgg to recover no-longer-wanted space. + * We also need a long-lived memory context for holding hashtable data + * structures and transition values. NOTE: the details of what is + * stored in aggcontext and what is stored in the regular per-query + * memory context are driven by a simple decision: we want to reset + * the aggcontext in ExecReScanAgg to recover no-longer-wanted space. */ aggstate->aggcontext = AllocSetContextCreate(CurrentMemoryContext, @@ -1079,10 +1078,10 @@ ExecInitAgg(Agg *node, EState *estate) * initialize child expressions * * Note: ExecInitExpr finds Aggrefs for us, and 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. + * 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. */ aggstate->ss.ps.targetlist = (List *) ExecInitExpr((Expr *) node->plan.targetlist, @@ -1116,19 +1115,20 @@ ExecInitAgg(Agg *node, EState *estate) if (numaggs <= 0) { /* - * This is not an error condition: we might be using the Agg node just - * to do hash-based grouping. Even in the regular case, - * constant-expression simplification could optimize away all of the - * Aggrefs in the targetlist and qual. So keep going, but force local - * copy of numaggs positive so that palloc()s below don't choke. + * This is not an error condition: we might be using the Agg node + * just to do hash-based grouping. Even in the regular case, + * constant-expression simplification could optimize away all of + * the Aggrefs in the targetlist and qual. So keep going, but + * force local copy of numaggs positive so that palloc()s below + * don't choke. */ numaggs = 1; } /* - * If we are grouping, precompute fmgr lookup data for inner loop. - * We need both equality and hashing functions to do it by hashing, - * but only equality if not hashing. + * If we are grouping, precompute fmgr lookup data for inner loop. We + * need both equality and hashing functions to do it by hashing, but + * only equality if not hashing. */ if (node->numCols > 0) { @@ -1146,8 +1146,8 @@ ExecInitAgg(Agg *node, EState *estate) } /* - * Set up aggregate-result storage in the output expr context, and also - * allocate my private per-agg working storage + * Set up aggregate-result storage in the output expr context, and + * also allocate my private per-agg working storage */ econtext = aggstate->ss.ps.ps_ExprContext; econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numaggs); @@ -1174,8 +1174,8 @@ ExecInitAgg(Agg *node, EState *estate) * unchanging fields of the per-agg data. We also detect duplicate * aggregates (for example, "SELECT sum(x) ... HAVING sum(x) > 0"). * When duplicates are detected, we only make an AggStatePerAgg struct - * for the first one. The clones are simply pointed at the same result - * entry by giving them duplicate aggno values. + * for the first one. The clones are simply pointed at the same + * result entry by giving them duplicate aggno values. */ aggno = -1; foreach(alist, aggstate->aggs) @@ -1425,9 +1425,9 @@ ExecReScanAgg(AggState *node, ExprContext *exprCtxt) if (((Agg *) node->ss.ps.plan)->aggstrategy == AGG_HASHED) { /* - * In the hashed case, if we haven't yet built the hash table - * then we can just return; nothing done yet, so nothing to undo. - * If subnode's chgParam is not NULL then it will be re-scanned by + * In the hashed case, if we haven't yet built the hash table then + * we can just return; nothing done yet, so nothing to undo. If + * subnode's chgParam is not NULL then it will be re-scanned by * ExecProcNode, else no reason to re-scan it at all. */ if (!node->table_filled) diff --git a/src/backend/executor/nodeAppend.c b/src/backend/executor/nodeAppend.c index e79d37fd85..7fc8caac2a 100644 --- a/src/backend/executor/nodeAppend.c +++ b/src/backend/executor/nodeAppend.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeAppend.c,v 1.52 2003/02/09 00:30:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeAppend.c,v 1.53 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -355,7 +355,7 @@ ExecReScanAppend(AppendState *node, ExprContext *exprCtxt) for (i = node->as_firstplan; i <= node->as_lastplan; i++) { - PlanState *subnode = node->appendplans[i]; + PlanState *subnode = node->appendplans[i]; /* * ExecReScan doesn't know about my subplans, so I have to do diff --git a/src/backend/executor/nodeHash.c b/src/backend/executor/nodeHash.c index 69053708cd..a4eb9065c0 100644 --- a/src/backend/executor/nodeHash.c +++ b/src/backend/executor/nodeHash.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeHash.c,v 1.77 2003/07/21 17:05:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeHash.c,v 1.78 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -244,7 +244,7 @@ ExecHashTableCreate(Hash *node, List *hashOperators) i = 0; foreach(ho, hashOperators) { - Oid hashfn; + Oid hashfn; hashfn = get_op_hash_function(lfirsto(ho)); if (!OidIsValid(hashfn)) diff --git a/src/backend/executor/nodeHashjoin.c b/src/backend/executor/nodeHashjoin.c index bc3ecdfeed..a45e007aff 100644 --- a/src/backend/executor/nodeHashjoin.c +++ b/src/backend/executor/nodeHashjoin.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeHashjoin.c,v 1.53 2003/07/21 17:05:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeHashjoin.c,v 1.54 2003/08/04 00:43:17 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -22,8 +22,8 @@ #include "utils/memutils.h" -static TupleTableSlot *ExecHashJoinOuterGetTuple(PlanState *node, - HashJoinState *hjstate); +static TupleTableSlot *ExecHashJoinOuterGetTuple(PlanState * node, + HashJoinState *hjstate); static TupleTableSlot *ExecHashJoinGetSavedTuple(HashJoinState *hjstate, BufFile *file, TupleTableSlot *tupleSlot); @@ -94,10 +94,10 @@ ExecHashJoin(HashJoinState *node) /* * If we're doing an IN join, we want to return at most one row per - * outer tuple; so we can stop scanning the inner scan if we matched on - * the previous try. + * outer tuple; so we can stop scanning the inner scan if we matched + * on the previous try. */ - if (node->js.jointype == JOIN_IN && + if (node->js.jointype == JOIN_IN && node->hj_MatchedOuter) node->hj_NeedNewOuter = true; @@ -244,7 +244,10 @@ ExecHashJoin(HashJoinState *node) } } - /* If we didn't return a tuple, may need to set NeedNewOuter */ + /* + * If we didn't return a tuple, may need to set + * NeedNewOuter + */ if (node->js.jointype == JOIN_IN) { node->hj_NeedNewOuter = true; @@ -365,7 +368,7 @@ ExecInitHashJoin(HashJoin *node, EState *estate) case JOIN_LEFT: hjstate->hj_NullInnerTupleSlot = ExecInitNullTupleSlot(estate, - ExecGetResultType(innerPlanState(hjstate))); + ExecGetResultType(innerPlanState(hjstate))); break; default: elog(ERROR, "unrecognized join type: %d", @@ -407,10 +410,10 @@ ExecInitHashJoin(HashJoin *node, EState *estate) hjstate->hj_CurTuple = (HashJoinTuple) NULL; /* - * The planner already made a list of the inner hashkeys for us, - * but we also need a list of the outer hashkeys, as well as a list - * of the hash operator OIDs. Both lists of exprs must then be prepared - * for execution. + * The planner already made a list of the inner hashkeys for us, but + * we also need a list of the outer hashkeys, as well as a list of the + * hash operator OIDs. Both lists of exprs must then be prepared for + * execution. */ hjstate->hj_InnerHashKeys = (List *) ExecInitExpr((Expr *) hashNode->hashkeys, @@ -496,7 +499,7 @@ ExecEndHashJoin(HashJoinState *node) */ static TupleTableSlot * -ExecHashJoinOuterGetTuple(PlanState *node, HashJoinState *hjstate) +ExecHashJoinOuterGetTuple(PlanState * node, HashJoinState *hjstate) { HashJoinTable hashtable = hjstate->hj_HashTable; int curbatch = hashtable->curbatch; @@ -701,11 +704,11 @@ ExecReScanHashJoin(HashJoinState *node, ExprContext *exprCtxt) Assert(node->hj_HashTable != NULL); /* - * In a multi-batch join, we currently have to do rescans the hard way, - * primarily because batch temp files may have already been released. - * But if it's a single-batch join, and there is no parameter change - * for the inner subnode, then we can just re-use the existing hash - * table without rebuilding it. + * In a multi-batch join, we currently have to do rescans the hard + * way, primarily because batch temp files may have already been + * released. But if it's a single-batch join, and there is no + * parameter change for the inner subnode, then we can just re-use the + * existing hash table without rebuilding it. */ if (node->hj_HashTable->nbatch == 0 && ((PlanState *) node)->righttree->chgParam == NULL) @@ -718,6 +721,7 @@ ExecReScanHashJoin(HashJoinState *node, ExprContext *exprCtxt) node->hj_hashdone = false; ExecHashTableDestroy(node->hj_HashTable); node->hj_HashTable = NULL; + /* * if chgParam of subnode is not null then plan will be re-scanned * by first ExecProcNode. @@ -736,8 +740,8 @@ ExecReScanHashJoin(HashJoinState *node, ExprContext *exprCtxt) node->hj_MatchedOuter = false; /* - * if chgParam of subnode is not null then plan will be re-scanned - * by first ExecProcNode. + * if chgParam of subnode is not null then plan will be re-scanned by + * first ExecProcNode. */ if (((PlanState *) node)->lefttree->chgParam == NULL) ExecReScan(((PlanState *) node)->lefttree, exprCtxt); diff --git a/src/backend/executor/nodeIndexscan.c b/src/backend/executor/nodeIndexscan.c index 017a378f9d..d01d4cfa7c 100644 --- a/src/backend/executor/nodeIndexscan.c +++ b/src/backend/executor/nodeIndexscan.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeIndexscan.c,v 1.80 2003/07/21 17:05:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeIndexscan.c,v 1.81 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -290,7 +290,8 @@ ExecIndexReScan(IndexScanState *node, ExprContext *exprCtxt) int j; estate = node->ss.ps.state; - econtext = node->iss_RuntimeContext; /* context for runtime keys */ + econtext = node->iss_RuntimeContext; /* context for runtime + * keys */ numIndices = node->iss_NumIndices; scanDescs = node->iss_ScanDescs; scanKeys = node->iss_ScanKeys; @@ -882,7 +883,7 @@ ExecInitIndexScan(IndexScan *node, EState *estate) reloid))); indexstate->ss.ss_currentRelation = currentRelation; - indexstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */ + indexstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */ /* * get the scan type from the relation descriptor. diff --git a/src/backend/executor/nodeLimit.c b/src/backend/executor/nodeLimit.c index 4b1145e258..7477bd4304 100644 --- a/src/backend/executor/nodeLimit.c +++ b/src/backend/executor/nodeLimit.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeLimit.c,v 1.15 2003/07/21 17:05:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeLimit.c,v 1.16 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -55,17 +55,21 @@ ExecLimit(LimitState *node) switch (node->lstate) { case LIMIT_INITIAL: + /* * If backwards scan, just return NULL without changing state. */ if (!ScanDirectionIsForward(direction)) return NULL; + /* - * First call for this scan, so compute limit/offset. (We can't do - * this any earlier, because parameters from upper nodes may not - * be set until now.) This also sets position = 0. + * First call for this scan, so compute limit/offset. (We + * can't do this any earlier, because parameters from upper + * nodes may not be set until now.) This also sets position = + * 0. */ recompute_limits(node); + /* * Check for empty window; if so, treat like empty subplan. */ @@ -74,6 +78,7 @@ ExecLimit(LimitState *node) node->lstate = LIMIT_EMPTY; return NULL; } + /* * Fetch rows from subplan until we reach position > offset. */ @@ -83,8 +88,8 @@ ExecLimit(LimitState *node) if (TupIsNull(slot)) { /* - * The subplan returns too few tuples for us to produce - * any output at all. + * The subplan returns too few tuples for us to + * produce any output at all. */ node->lstate = LIMIT_EMPTY; return NULL; @@ -93,6 +98,7 @@ ExecLimit(LimitState *node) if (++node->position > node->offset) break; } + /* * Okay, we have the first tuple of the window. */ @@ -100,9 +106,10 @@ ExecLimit(LimitState *node) break; case LIMIT_EMPTY: + /* * The subplan is known to return no tuples (or not more than - * OFFSET tuples, in general). So we return no tuples. + * OFFSET tuples, in general). So we return no tuples. */ return NULL; @@ -113,7 +120,8 @@ ExecLimit(LimitState *node) * Forwards scan, so check for stepping off end of window. * If we are at the end of the window, return NULL without * advancing the subplan or the position variable; but - * change the state machine state to record having done so. + * change the state machine state to record having done + * so. */ if (!node->noCount && node->position >= node->offset + node->count) @@ -121,6 +129,7 @@ ExecLimit(LimitState *node) node->lstate = LIMIT_WINDOWEND; return NULL; } + /* * Get next tuple from subplan, if any. */ @@ -136,14 +145,16 @@ ExecLimit(LimitState *node) else { /* - * Backwards scan, so check for stepping off start of window. - * As above, change only state-machine status if so. + * Backwards scan, so check for stepping off start of + * window. As above, change only state-machine status if + * so. */ if (node->position <= node->offset + 1) { node->lstate = LIMIT_WINDOWSTART; return NULL; } + /* * Get previous tuple from subplan; there should be one! */ @@ -158,9 +169,11 @@ ExecLimit(LimitState *node) case LIMIT_SUBPLANEOF: if (ScanDirectionIsForward(direction)) return NULL; + /* * Backing up from subplan EOF, so re-fetch previous tuple; - * there should be one! Note previous tuple must be in window. + * there should be one! Note previous tuple must be in + * window. */ slot = ExecProcNode(outerPlan); if (TupIsNull(slot)) @@ -173,9 +186,10 @@ ExecLimit(LimitState *node) case LIMIT_WINDOWEND: if (ScanDirectionIsForward(direction)) return NULL; + /* - * Backing up from window end: simply re-return the last - * tuple fetched from the subplan. + * Backing up from window end: simply re-return the last tuple + * fetched from the subplan. */ slot = node->subSlot; node->lstate = LIMIT_INWINDOW; @@ -185,6 +199,7 @@ ExecLimit(LimitState *node) case LIMIT_WINDOWSTART: if (!ScanDirectionIsForward(direction)) return NULL; + /* * Advancing after having backed off window start: simply * re-return the last tuple fetched from the subplan. diff --git a/src/backend/executor/nodeMaterial.c b/src/backend/executor/nodeMaterial.c index 39968c65e0..afd08e8094 100644 --- a/src/backend/executor/nodeMaterial.c +++ b/src/backend/executor/nodeMaterial.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeMaterial.c,v 1.42 2003/03/27 16:51:27 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeMaterial.c,v 1.43 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -79,15 +79,15 @@ ExecMaterial(MaterialState *node) { /* * When reversing direction at tuplestore EOF, the first - * getheaptuple call will fetch the last-added tuple; but - * we want to return the one before that, if possible. - * So do an extra fetch. + * getheaptuple call will fetch the last-added tuple; but we + * want to return the one before that, if possible. So do an + * extra fetch. */ heapTuple = tuplestore_getheaptuple(tuplestorestate, forward, &should_free); if (heapTuple == NULL) - return NULL; /* the tuplestore must be empty */ + return NULL; /* the tuplestore must be empty */ if (should_free) heap_freetuple(heapTuple); } @@ -129,10 +129,11 @@ ExecMaterial(MaterialState *node) } heapTuple = outerslot->val; should_free = false; + /* * Append returned tuple to tuplestore, too. NOTE: because the - * tuplestore is certainly in EOF state, its read position will move - * forward over the added tuple. This is what we want. + * tuplestore is certainly in EOF state, its read position will + * move forward over the added tuple. This is what we want. */ tuplestore_puttuple(tuplestorestate, (void *) heapTuple); } @@ -293,8 +294,8 @@ ExecMaterialReScan(MaterialState *node, ExprContext *exprCtxt) * If subnode is to be rescanned then we forget previous stored * results; we have to re-read the subplan and re-store. * - * Otherwise we can just rewind and rescan the stored output. - * The state of the subnode does not change. + * Otherwise we can just rewind and rescan the stored output. The state + * of the subnode does not change. */ if (((PlanState *) node)->lefttree->chgParam != NULL) { @@ -303,7 +304,5 @@ ExecMaterialReScan(MaterialState *node, ExprContext *exprCtxt) node->eof_underlying = false; } else - { tuplestore_rescan((Tuplestorestate *) node->tuplestorestate); - } } diff --git a/src/backend/executor/nodeMergejoin.c b/src/backend/executor/nodeMergejoin.c index 57249d7d97..081ce24cb1 100644 --- a/src/backend/executor/nodeMergejoin.c +++ b/src/backend/executor/nodeMergejoin.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeMergejoin.c,v 1.58 2003/07/21 17:05:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeMergejoin.c,v 1.59 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -102,7 +102,7 @@ static bool MergeCompare(List *eqQual, List *compareQual, ExprContext *econtext) */ static void MJFormSkipQuals(List *qualList, List **ltQuals, List **gtQuals, - PlanState *parent) + PlanState * parent) { List *ltexprs, *gtexprs, @@ -358,9 +358,9 @@ ExecMergeJoin(MergeJoinState *node) List *otherqual; bool qualResult; bool compareResult; - PlanState *innerPlan; + PlanState *innerPlan; TupleTableSlot *innerTupleSlot; - PlanState *outerPlan; + PlanState *outerPlan; TupleTableSlot *outerTupleSlot; ExprContext *econtext; bool doFillOuter; @@ -644,7 +644,7 @@ ExecMergeJoin(MergeJoinState *node) * tuple, and return it if it passes the non-join * quals. */ - node->mj_MatchedInner = true; /* do it only once */ + node->mj_MatchedInner = true; /* do it only once */ ResetExprContext(econtext); @@ -720,7 +720,7 @@ ExecMergeJoin(MergeJoinState *node) * tuple, and return it if it passes the non-join * quals. */ - node->mj_MatchedOuter = true; /* do it only once */ + node->mj_MatchedOuter = true; /* do it only once */ ResetExprContext(econtext); @@ -1004,7 +1004,7 @@ ExecMergeJoin(MergeJoinState *node) * tuple, and return it if it passes the non-join * quals. */ - node->mj_MatchedOuter = true; /* do it only once */ + node->mj_MatchedOuter = true; /* do it only once */ ResetExprContext(econtext); @@ -1181,7 +1181,7 @@ ExecMergeJoin(MergeJoinState *node) * tuple, and return it if it passes the non-join * quals. */ - node->mj_MatchedInner = true; /* do it only once */ + node->mj_MatchedInner = true; /* do it only once */ ResetExprContext(econtext); @@ -1266,7 +1266,7 @@ ExecMergeJoin(MergeJoinState *node) * tuple, and return it if it passes the non-join * quals. */ - node->mj_MatchedInner = true; /* do it only once */ + node->mj_MatchedInner = true; /* do it only once */ ResetExprContext(econtext); @@ -1333,7 +1333,7 @@ ExecMergeJoin(MergeJoinState *node) * tuple, and return it if it passes the non-join * quals. */ - node->mj_MatchedOuter = true; /* do it only once */ + node->mj_MatchedOuter = true; /* do it only once */ ResetExprContext(econtext); @@ -1462,12 +1462,12 @@ ExecInitMergeJoin(MergeJoin *node, EState *estate) case JOIN_LEFT: mergestate->mj_NullInnerTupleSlot = ExecInitNullTupleSlot(estate, - ExecGetResultType(innerPlanState(mergestate))); + ExecGetResultType(innerPlanState(mergestate))); break; case JOIN_RIGHT: mergestate->mj_NullOuterTupleSlot = ExecInitNullTupleSlot(estate, - ExecGetResultType(outerPlanState(mergestate))); + ExecGetResultType(outerPlanState(mergestate))); /* * Can't handle right or full join with non-nil extra @@ -1481,10 +1481,10 @@ ExecInitMergeJoin(MergeJoin *node, EState *estate) case JOIN_FULL: mergestate->mj_NullOuterTupleSlot = ExecInitNullTupleSlot(estate, - ExecGetResultType(outerPlanState(mergestate))); + ExecGetResultType(outerPlanState(mergestate))); mergestate->mj_NullInnerTupleSlot = ExecInitNullTupleSlot(estate, - ExecGetResultType(innerPlanState(mergestate))); + ExecGetResultType(innerPlanState(mergestate))); /* * Can't handle right or full join with non-nil extra diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index 2b69da95e8..66dbd8c063 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeNestloop.c,v 1.33 2003/07/21 17:05:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeNestloop.c,v 1.34 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -103,8 +103,8 @@ ExecNestLoop(NestLoopState *node) /* * If we're doing an IN join, we want to return at most one row per - * outer tuple; so we can stop scanning the inner scan if we matched on - * the previous try. + * outer tuple; so we can stop scanning the inner scan if we matched + * on the previous try. */ if (node->js.jointype == JOIN_IN && node->nl_MatchedOuter) @@ -330,7 +330,7 @@ ExecInitNestLoop(NestLoop *node, EState *estate) case JOIN_LEFT: nlstate->nl_NullInnerTupleSlot = ExecInitNullTupleSlot(estate, - ExecGetResultType(innerPlanState(nlstate))); + ExecGetResultType(innerPlanState(nlstate))); break; default: elog(ERROR, "unrecognized join type: %d", @@ -404,7 +404,7 @@ ExecEndNestLoop(NestLoopState *node) void ExecReScanNestLoop(NestLoopState *node, ExprContext *exprCtxt) { - PlanState *outerPlan = outerPlanState(node); + PlanState *outerPlan = outerPlanState(node); /* * If outerPlan->chgParam is not null then plan will be automatically diff --git a/src/backend/executor/nodeResult.c b/src/backend/executor/nodeResult.c index 9ea75eb3ce..194ed19216 100644 --- a/src/backend/executor/nodeResult.c +++ b/src/backend/executor/nodeResult.c @@ -34,7 +34,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeResult.c,v 1.24 2002/12/15 16:17:46 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeResult.c,v 1.25 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -64,7 +64,7 @@ ExecResult(ResultState *node) { TupleTableSlot *outerTupleSlot; TupleTableSlot *resultSlot; - PlanState *outerPlan; + PlanState *outerPlan; ExprContext *econtext; ExprDoneCond isDone; diff --git a/src/backend/executor/nodeSeqscan.c b/src/backend/executor/nodeSeqscan.c index 47d2e4eb49..4721fc5bf6 100644 --- a/src/backend/executor/nodeSeqscan.c +++ b/src/backend/executor/nodeSeqscan.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeSeqscan.c,v 1.43 2003/02/03 15:07:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSeqscan.c,v 1.44 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -29,8 +29,8 @@ #include "executor/nodeSeqscan.h" #include "parser/parsetree.h" -static void InitScanRelation(SeqScanState *node, EState *estate); -static TupleTableSlot *SeqNext(SeqScanState *node); +static void InitScanRelation(SeqScanState * node, EState *estate); +static TupleTableSlot *SeqNext(SeqScanState * node); /* ---------------------------------------------------------------- * Scan Support @@ -43,7 +43,7 @@ static TupleTableSlot *SeqNext(SeqScanState *node); * ---------------------------------------------------------------- */ static TupleTableSlot * -SeqNext(SeqScanState *node) +SeqNext(SeqScanState * node) { HeapTuple tuple; HeapScanDesc scandesc; @@ -123,7 +123,7 @@ SeqNext(SeqScanState *node) */ TupleTableSlot * -ExecSeqScan(SeqScanState *node) +ExecSeqScan(SeqScanState * node) { /* * use SeqNext as access method @@ -139,7 +139,7 @@ ExecSeqScan(SeqScanState *node) * ---------------------------------------------------------------- */ static void -InitScanRelation(SeqScanState *node, EState *estate) +InitScanRelation(SeqScanState * node, EState *estate) { Index relid; List *rangeTable; @@ -252,7 +252,7 @@ ExecCountSlotsSeqScan(SeqScan *node) * ---------------------------------------------------------------- */ void -ExecEndSeqScan(SeqScanState *node) +ExecEndSeqScan(SeqScanState * node) { Relation relation; HeapScanDesc scanDesc; @@ -302,7 +302,7 @@ ExecEndSeqScan(SeqScanState *node) * ---------------------------------------------------------------- */ void -ExecSeqReScan(SeqScanState *node, ExprContext *exprCtxt) +ExecSeqReScan(SeqScanState * node, ExprContext *exprCtxt) { EState *estate; Index scanrelid; @@ -332,7 +332,7 @@ ExecSeqReScan(SeqScanState *node, ExprContext *exprCtxt) * ---------------------------------------------------------------- */ void -ExecSeqMarkPos(SeqScanState *node) +ExecSeqMarkPos(SeqScanState * node) { HeapScanDesc scan; @@ -347,7 +347,7 @@ ExecSeqMarkPos(SeqScanState *node) * ---------------------------------------------------------------- */ void -ExecSeqRestrPos(SeqScanState *node) +ExecSeqRestrPos(SeqScanState * node) { HeapScanDesc scan; diff --git a/src/backend/executor/nodeSubplan.c b/src/backend/executor/nodeSubplan.c index a42e8f18e2..0fe888c803 100644 --- a/src/backend/executor/nodeSubplan.c +++ b/src/backend/executor/nodeSubplan.c @@ -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.51 2003/07/21 17:05:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSubplan.c,v 1.52 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -29,13 +29,13 @@ #include "utils/lsyscache.h" -static Datum ExecHashSubPlan(SubPlanState *node, - ExprContext *econtext, - bool *isNull); -static Datum ExecScanSubPlan(SubPlanState *node, - ExprContext *econtext, - bool *isNull); -static void buildSubPlanHash(SubPlanState *node); +static Datum ExecHashSubPlan(SubPlanState * node, + ExprContext *econtext, + bool *isNull); +static Datum ExecScanSubPlan(SubPlanState * node, + ExprContext *econtext, + bool *isNull); +static void buildSubPlanHash(SubPlanState * node); static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot); static bool tupleAllNulls(HeapTuple tuple); @@ -45,11 +45,11 @@ static bool tupleAllNulls(HeapTuple tuple); * ---------------------------------------------------------------- */ Datum -ExecSubPlan(SubPlanState *node, +ExecSubPlan(SubPlanState * node, ExprContext *econtext, bool *isNull) { - SubPlan *subplan = (SubPlan *) node->xprstate.expr; + SubPlan *subplan = (SubPlan *) node->xprstate.expr; if (subplan->setParam != NIL) elog(ERROR, "cannot set parent params from subquery"); @@ -64,11 +64,11 @@ ExecSubPlan(SubPlanState *node, * ExecHashSubPlan: store subselect result in an in-memory hash table */ static Datum -ExecHashSubPlan(SubPlanState *node, +ExecHashSubPlan(SubPlanState * node, ExprContext *econtext, bool *isNull) { - SubPlan *subplan = (SubPlan *) node->xprstate.expr; + SubPlan *subplan = (SubPlan *) node->xprstate.expr; PlanState *planstate = node->planstate; ExprContext *innerecontext = node->innerecontext; TupleTableSlot *slot; @@ -79,8 +79,8 @@ ExecHashSubPlan(SubPlanState *node, elog(ERROR, "hashed subplan with direct correlation not supported"); /* - * If first time through or we need to rescan the subplan, build - * the hash table. + * If first time through or we need to rescan the subplan, build the + * hash table. */ if (node->hashtable == NULL || planstate->chgParam != NULL) buildSubPlanHash(node); @@ -94,19 +94,19 @@ ExecHashSubPlan(SubPlanState *node, return BoolGetDatum(false); /* - * Evaluate lefthand expressions and form a projection tuple. - * First we have to set the econtext to use (hack alert!). + * Evaluate lefthand expressions and form a projection tuple. First we + * have to set the econtext to use (hack alert!). */ node->projLeft->pi_exprContext = econtext; slot = ExecProject(node->projLeft, NULL); tup = slot->val; /* - * Note: because we are typically called in a per-tuple context, - * we have to explicitly clear the projected tuple before returning. - * Otherwise, we'll have a double-free situation: the per-tuple context - * will probably be reset before we're called again, and then the tuple - * slot will think it still needs to free the tuple. + * Note: because we are typically called in a per-tuple context, we + * have to explicitly clear the projected tuple before returning. + * Otherwise, we'll have a double-free situation: the per-tuple + * context will probably be reset before we're called again, and then + * the tuple slot will think it still needs to free the tuple. */ /* @@ -116,20 +116,20 @@ ExecHashSubPlan(SubPlanState *node, ResetExprContext(innerecontext); /* - * If the LHS is all non-null, probe for an exact match in the - * main hash table. If we find one, the result is TRUE. - * Otherwise, scan the partly-null table to see if there are any - * rows that aren't provably unequal to the LHS; if so, the result - * is UNKNOWN. (We skip that part if we don't care about UNKNOWN.) - * Otherwise, the result is FALSE. + * If the LHS is all non-null, probe for an exact match in the main + * hash table. If we find one, the result is TRUE. Otherwise, scan + * the partly-null table to see if there are any rows that aren't + * provably unequal to the LHS; if so, the result is UNKNOWN. (We + * skip that part if we don't care about UNKNOWN.) Otherwise, the + * result is FALSE. * - * Note: the reason we can avoid a full scan of the main hash table - * is that the combining operators are assumed never to yield NULL - * when both inputs are non-null. If they were to do so, we might - * need to produce UNKNOWN instead of FALSE because of an UNKNOWN - * result in comparing the LHS to some main-table entry --- which - * is a comparison we will not even make, unless there's a chance - * match of hash keys. + * Note: the reason we can avoid a full scan of the main hash table is + * that the combining operators are assumed never to yield NULL when + * both inputs are non-null. If they were to do so, we might need to + * produce UNKNOWN instead of FALSE because of an UNKNOWN result in + * comparing the LHS to some main-table entry --- which is a + * comparison we will not even make, unless there's a chance match of + * hash keys. */ if (HeapTupleNoNulls(tup)) { @@ -151,14 +151,14 @@ ExecHashSubPlan(SubPlanState *node, } /* - * When the LHS is partly or wholly NULL, we can never return TRUE. - * If we don't care about UNKNOWN, just return FALSE. Otherwise, - * if the LHS is wholly NULL, immediately return UNKNOWN. (Since the - * combining operators are strict, the result could only be FALSE if the - * sub-select were empty, but we already handled that case.) Otherwise, - * we must scan both the main and partly-null tables to see if there are - * any rows that aren't provably unequal to the LHS; if so, the result is - * UNKNOWN. Otherwise, the result is FALSE. + * When the LHS is partly or wholly NULL, we can never return TRUE. If + * we don't care about UNKNOWN, just return FALSE. Otherwise, if the + * LHS is wholly NULL, immediately return UNKNOWN. (Since the + * combining operators are strict, the result could only be FALSE if + * the sub-select were empty, but we already handled that case.) + * Otherwise, we must scan both the main and partly-null tables to see + * if there are any rows that aren't provably unequal to the LHS; if + * so, the result is UNKNOWN. Otherwise, the result is FALSE. */ if (node->hashnulls == NULL) { @@ -194,11 +194,11 @@ ExecHashSubPlan(SubPlanState *node, * ExecScanSubPlan: default case where we have to rescan subplan each time */ static Datum -ExecScanSubPlan(SubPlanState *node, +ExecScanSubPlan(SubPlanState * node, ExprContext *econtext, bool *isNull) { - SubPlan *subplan = (SubPlan *) node->xprstate.expr; + SubPlan *subplan = (SubPlan *) node->xprstate.expr; PlanState *planstate = node->planstate; SubLinkType subLinkType = subplan->subLinkType; bool useOr = subplan->useOr; @@ -218,14 +218,14 @@ ExecScanSubPlan(SubPlanState *node, oldcontext = MemoryContextSwitchTo(node->sub_estate->es_query_cxt); /* - * Set Params of this plan from parent plan correlation values. - * (Any calculation we have to do is done in the parent econtext, - * since the Param values don't need to have per-query lifetime.) + * Set Params of this plan from parent plan correlation values. (Any + * calculation we have to do is done in the parent econtext, since the + * Param values don't need to have per-query lifetime.) */ pvar = node->args; foreach(lst, subplan->parParam) { - int paramid = lfirsti(lst); + int paramid = lfirsti(lst); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); Assert(pvar != NIL); @@ -241,23 +241,24 @@ ExecScanSubPlan(SubPlanState *node, ExecReScan(planstate, NULL); /* - * For all sublink types except EXPR_SUBLINK and ARRAY_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 - * tuples is FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for - * MULTIEXPR_SUBLINK. + * For all sublink types except EXPR_SUBLINK and ARRAY_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 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. For ARRAY_SUBLINK we allow the subplan - * to produce more than one tuple. In either case, if zero tuples are - * produced, we return NULL. Assuming we get a tuple, we just use its - * first column (there can be only one non-junk column in this case). + * tuple, else an error is raised. For ARRAY_SUBLINK we allow the + * subplan to produce more than one tuple. In either case, if zero + * tuples are produced, we return NULL. Assuming we get a tuple, we + * just use its first column (there can be only one non-junk column in + * this case). */ result = BoolGetDatum(subLinkType == ALL_SUBLINK); *isNull = false; @@ -311,8 +312,8 @@ ExecScanSubPlan(SubPlanState *node, if (subLinkType == ARRAY_SUBLINK) { - Datum dvalue; - bool disnull; + Datum dvalue; + bool disnull; found = true; /* stash away current value */ @@ -346,7 +347,8 @@ ExecScanSubPlan(SubPlanState *node, bool expnull; /* - * Load up the Param representing this column of the sub-select. + * Load up the Param representing this column of the + * sub-select. */ prmdata = &(econtext->ecxt_param_exec_vals[paramid]); Assert(prmdata->execPlan == NULL); @@ -432,8 +434,8 @@ ExecScanSubPlan(SubPlanState *node, { /* * deal with empty subplan result. result/isNull were previously - * initialized correctly for all sublink types except EXPR, ARRAY, and - * MULTIEXPR; for those, return NULL. + * initialized correctly for all sublink types except EXPR, ARRAY, + * and MULTIEXPR; for those, return NULL. */ if (subLinkType == EXPR_SUBLINK || subLinkType == ARRAY_SUBLINK || @@ -459,9 +461,9 @@ ExecScanSubPlan(SubPlanState *node, * buildSubPlanHash: load hash table by scanning subplan output. */ static void -buildSubPlanHash(SubPlanState *node) +buildSubPlanHash(SubPlanState * node) { - SubPlan *subplan = (SubPlan *) node->xprstate.expr; + SubPlan *subplan = (SubPlan *) node->xprstate.expr; PlanState *planstate = node->planstate; int ncols = length(node->exprs); ExprContext *innerecontext = node->innerecontext; @@ -474,19 +476,19 @@ buildSubPlanHash(SubPlanState *node) Assert(!subplan->useOr); /* - * If we already had any hash tables, destroy 'em; then create - * empty hash table(s). + * If we already had any hash tables, destroy 'em; then create empty + * hash table(s). * - * If we need to distinguish accurately between FALSE and UNKNOWN - * (i.e., NULL) results of the IN operation, then we have to store - * subplan output rows that are partly or wholly NULL. We store such - * rows in a separate hash table that we expect will be much smaller - * than the main table. (We can use hashing to eliminate partly-null - * rows that are not distinct. We keep them separate to minimize the - * cost of the inevitable full-table searches; see findPartialMatch.) + * If we need to distinguish accurately between FALSE and UNKNOWN (i.e., + * NULL) results of the IN operation, then we have to store subplan + * output rows that are partly or wholly NULL. We store such rows in + * a separate hash table that we expect will be much smaller than the + * main table. (We can use hashing to eliminate partly-null rows that + * are not distinct. We keep them separate to minimize the cost of + * the inevitable full-table searches; see findPartialMatch.) * - * If it's not necessary to distinguish FALSE and UNKNOWN, then we - * don't need to store subplan output rows that contain NULL. + * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't + * need to store subplan output rows that contain NULL. */ MemoryContextReset(node->tablecxt); node->hashtable = NULL; @@ -529,7 +531,8 @@ buildSubPlanHash(SubPlanState *node) /* * We are probably in a short-lived expression-evaluation context. - * Switch to the child plan's per-query context for calling ExecProcNode. + * Switch to the child plan's per-query context for calling + * ExecProcNode. */ oldcontext = MemoryContextSwitchTo(node->sub_estate->es_query_cxt); @@ -539,8 +542,9 @@ buildSubPlanHash(SubPlanState *node) ExecReScan(planstate, NULL); /* - * Scan the subplan and load the hash table(s). Note that when there are - * duplicate rows coming out of the sub-select, only one copy is stored. + * Scan the subplan and load the hash table(s). Note that when there + * are duplicate rows coming out of the sub-select, only one copy is + * stored. */ for (slot = ExecProcNode(planstate); !TupIsNull(slot); @@ -572,9 +576,9 @@ buildSubPlanHash(SubPlanState *node) /* * If result contains any nulls, store separately or not at all. - * (Since we know the projection tuple has no junk columns, we - * can just look at the overall hasnull info bit, instead of - * groveling through the columns.) + * (Since we know the projection tuple has no junk columns, we can + * just look at the overall hasnull info bit, instead of groveling + * through the columns.) */ if (HeapTupleNoNulls(tup)) { @@ -621,7 +625,7 @@ findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot) HeapTuple tuple = slot->val; TupleDesc tupdesc = slot->ttc_tupleDescriptor; TupleHashIterator hashiter; - TupleHashEntry entry; + TupleHashEntry entry; ResetTupleHashIterator(&hashiter); while ((entry = ScanTupleHashTable(hashtable, &hashiter)) != NULL) @@ -643,8 +647,8 @@ findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot) static bool tupleAllNulls(HeapTuple tuple) { - int ncols = tuple->t_data->t_natts; - int i; + int ncols = tuple->t_data->t_natts; + int i; for (i = 1; i <= ncols; i++) { @@ -659,15 +663,15 @@ tupleAllNulls(HeapTuple tuple) * ---------------------------------------------------------------- */ void -ExecInitSubPlan(SubPlanState *node, EState *estate) +ExecInitSubPlan(SubPlanState * node, EState *estate) { - SubPlan *subplan = (SubPlan *) node->xprstate.expr; + SubPlan *subplan = (SubPlan *) node->xprstate.expr; EState *sp_estate; MemoryContext oldcontext; /* - * Do access checking on the rangetable entries in the subquery. - * Here, we assume the subquery is a SELECT. + * Do access checking on the rangetable entries in the subquery. Here, + * we assume the subquery is a SELECT. */ ExecCheckRTPerms(subplan->rtable, CMD_SELECT); @@ -690,9 +694,9 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) * create an EState for the subplan * * The subquery needs its own EState because it has its own rangetable. - * It shares our Param ID space, however. XXX if rangetable access were - * done differently, the subquery could share our EState, which would - * eliminate some thrashing about in this module... + * It shares our Param ID space, however. XXX if rangetable access + * were done differently, the subquery could share our EState, which + * would eliminate some thrashing about in this module... */ sp_estate = CreateExecutorState(); node->sub_estate = sp_estate; @@ -721,9 +725,9 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) * to set params for parent plan then mark parameters as needing * evaluation. * - * Note that in the case of un-correlated subqueries we don't care - * about setting parent->chgParam here: indices take care about - * it, for others - it doesn't matter... + * Note that in the case of un-correlated subqueries we don't care about + * setting parent->chgParam here: indices take care about it, for + * others - it doesn't matter... */ if (subplan->setParam != NIL) { @@ -731,7 +735,7 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) foreach(lst, subplan->setParam) { - int paramid = lfirsti(lst); + int paramid = lfirsti(lst); ParamExecData *prm = &(estate->es_param_exec_vals[paramid]); prm->execPlan = node; @@ -744,8 +748,8 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) */ if (subplan->useHashTable) { - int ncols, - i; + int ncols, + i; TupleDesc tupDesc; TupleTable tupTable; TupleTableSlot *slot; @@ -768,15 +772,16 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) ncols = length(node->exprs); node->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber)); for (i = 0; i < ncols; i++) - node->keyColIdx[i] = i+1; + node->keyColIdx[i] = i + 1; + /* * We use ExecProject to evaluate the lefthand and righthand * expression lists and form tuples. (You might think that we * could use the sub-select's output tuples directly, but that is * not the case if we had to insert any run-time coercions of the * sub-select's output datatypes; anyway this avoids storing any - * resjunk columns that might be in the sub-select's output.) - * Run through the combining expressions to build tlists for the + * resjunk columns that might be in the sub-select's output.) Run + * through the combining expressions to build tlists for the * lefthand and righthand sides. We need both the ExprState list * (for ExecProject) and the underlying parse Exprs (for * ExecTypeFromTL). @@ -791,7 +796,7 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) i = 1; foreach(lexpr, node->exprs) { - FuncExprState *fstate = (FuncExprState *) lfirst(lexpr); + FuncExprState *fstate = (FuncExprState *) lfirst(lexpr); OpExpr *opexpr = (OpExpr *) fstate->xprstate.expr; ExprState *exstate; Expr *expr; @@ -834,34 +839,34 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) rightptlist = lappend(rightptlist, tle); /* Lookup the combining function */ - fmgr_info(opexpr->opfuncid, &node->eqfunctions[i-1]); - node->eqfunctions[i-1].fn_expr = (Node *) opexpr; + fmgr_info(opexpr->opfuncid, &node->eqfunctions[i - 1]); + node->eqfunctions[i - 1].fn_expr = (Node *) opexpr; /* Lookup the associated hash function */ hashfn = get_op_hash_function(opexpr->opno); if (!OidIsValid(hashfn)) elog(ERROR, "could not find hash function for hash operator %u", opexpr->opno); - fmgr_info(hashfn, &node->hashfunctions[i-1]); + fmgr_info(hashfn, &node->hashfunctions[i - 1]); i++; } /* - * Create a tupletable to hold these tuples. (Note: we never bother - * to free the tupletable explicitly; that's okay because it will - * never store raw disk tuples that might have associated buffer - * pins. The only resource involved is memory, which will be - * cleaned up by freeing the query context.) + * Create a tupletable to hold these tuples. (Note: we never + * bother to free the tupletable explicitly; that's okay because + * it will never store raw disk tuples that might have associated + * buffer pins. The only resource involved is memory, which will + * be cleaned up by freeing the query context.) */ tupTable = ExecCreateTupleTable(2); /* * Construct tupdescs, slots and projection nodes for left and - * right sides. The lefthand expressions will be evaluated in - * the parent plan node's exprcontext, which we don't have access - * to here. Fortunately we can just pass NULL for now and fill it - * in later (hack alert!). The righthand expressions will be + * right sides. The lefthand expressions will be evaluated in the + * parent plan node's exprcontext, which we don't have access to + * here. Fortunately we can just pass NULL for now and fill it in + * later (hack alert!). The righthand expressions will be * evaluated in our own innerecontext. */ tupDesc = ExecTypeFromTL(leftptlist, false); @@ -894,11 +899,11 @@ ExecInitSubPlan(SubPlanState *node, EState *estate) * ---------------------------------------------------------------- */ void -ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) +ExecSetParamPlan(SubPlanState * node, ExprContext *econtext) { - SubPlan *subplan = (SubPlan *) node->xprstate.expr; + SubPlan *subplan = (SubPlan *) node->xprstate.expr; PlanState *planstate = node->planstate; - SubLinkType subLinkType = subplan->subLinkType; + SubLinkType subLinkType = subplan->subLinkType; MemoryContext oldcontext; TupleTableSlot *slot; List *lst; @@ -928,7 +933,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) if (subLinkType == EXISTS_SUBLINK) { /* There can be only one param... */ - int paramid = lfirsti(subplan->setParam); + int paramid = lfirsti(subplan->setParam); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); prm->execPlan = NULL; @@ -940,8 +945,8 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) if (subLinkType == ARRAY_SUBLINK) { - Datum dvalue; - bool disnull; + Datum dvalue; + bool disnull; found = true; /* stash away current value */ @@ -963,8 +968,8 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) found = true; /* - * We need to copy the subplan's tuple into our own context, - * in case any of the params are pass-by-ref type --- the pointers + * We need to copy the subplan's tuple into our own context, 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. @@ -981,7 +986,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) */ foreach(lst, subplan->setParam) { - int paramid = lfirsti(lst); + int paramid = lfirsti(lst); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); prm->execPlan = NULL; @@ -995,7 +1000,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) if (subLinkType == EXISTS_SUBLINK) { /* There can be only one param... */ - int paramid = lfirsti(subplan->setParam); + int paramid = lfirsti(subplan->setParam); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); prm->execPlan = NULL; @@ -1006,7 +1011,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) { foreach(lst, subplan->setParam) { - int paramid = lfirsti(lst); + int paramid = lfirsti(lst); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); prm->execPlan = NULL; @@ -1018,7 +1023,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) else if (subLinkType == ARRAY_SUBLINK) { /* There can be only one param... */ - int paramid = lfirsti(subplan->setParam); + int paramid = lfirsti(subplan->setParam); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); Assert(astate != NULL); @@ -1036,7 +1041,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) * ---------------------------------------------------------------- */ void -ExecEndSubPlan(SubPlanState *node) +ExecEndSubPlan(SubPlanState * node) { if (node->needShutdown) { @@ -1056,10 +1061,10 @@ ExecEndSubPlan(SubPlanState *node) * Mark an initplan as needing recalculation */ void -ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent) +ExecReScanSetParamPlan(SubPlanState * node, PlanState * parent) { PlanState *planstate = node->planstate; - SubPlan *subplan = (SubPlan *) node->xprstate.expr; + SubPlan *subplan = (SubPlan *) node->xprstate.expr; EState *estate = parent->state; List *lst; @@ -1080,7 +1085,7 @@ ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent) */ foreach(lst, subplan->setParam) { - int paramid = lfirsti(lst); + int paramid = lfirsti(lst); ParamExecData *prm = &(estate->es_param_exec_vals[paramid]); prm->execPlan = node; diff --git a/src/backend/executor/nodeSubqueryscan.c b/src/backend/executor/nodeSubqueryscan.c index ba4804fceb..deec07ae6b 100644 --- a/src/backend/executor/nodeSubqueryscan.c +++ b/src/backend/executor/nodeSubqueryscan.c @@ -12,7 +12,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeSubqueryscan.c,v 1.18 2003/02/09 00:30:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSubqueryscan.c,v 1.19 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -160,10 +160,11 @@ ExecInitSubqueryScan(SubqueryScan *node, EState *estate) Assert(rte->rtekind == RTE_SUBQUERY); /* - * The subquery needs its own EState because it has its own rangetable. - * It shares our Param ID space, however. XXX if rangetable access were - * done differently, the subquery could share our EState, which would - * eliminate some thrashing about in this module... + * The subquery needs its own EState because it has its own + * rangetable. It shares our Param ID space, however. XXX if + * rangetable access were done differently, the subquery could share + * our EState, which would eliminate some thrashing about in this + * module... */ sp_estate = CreateExecutorState(); subquerystate->sss_SubEState = sp_estate; @@ -259,9 +260,9 @@ ExecSubqueryReScan(SubqueryScanState *node, ExprContext *exprCtxt) /* * ExecReScan doesn't know about my subplan, so I have to do - * changed-parameter signaling myself. This is just as well, - * because the subplan has its own memory context in which its - * chgParam state lives. + * changed-parameter signaling myself. This is just as well, because + * the subplan has its own memory context in which its chgParam state + * lives. */ if (node->ss.ps.chgParam != NULL) UpdateChangedParamSet(node->subplan, node->ss.ps.chgParam); diff --git a/src/backend/executor/nodeUnique.c b/src/backend/executor/nodeUnique.c index fb012a5cc4..18e172209d 100644 --- a/src/backend/executor/nodeUnique.c +++ b/src/backend/executor/nodeUnique.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeUnique.c,v 1.38 2003/02/02 19:08:57 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeUnique.c,v 1.39 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -57,9 +57,9 @@ ExecUnique(UniqueState *node) * now loop, returning only non-duplicate tuples. We assume that the * tuples arrive in sorted order so we can detect duplicates easily. * - * We return the first tuple from each group of duplicates (or the - * last tuple of each group, when moving backwards). At either end - * of the subplan, clear priorTuple so that we correctly return the + * We return the first tuple from each group of duplicates (or the last + * tuple of each group, when moving backwards). At either end of the + * subplan, clear priorTuple so that we correctly return the * first/last tuple when reversing direction. */ for (;;) diff --git a/src/backend/executor/spi.c b/src/backend/executor/spi.c index 4d554aef1e..b25f0a79ff 100644 --- a/src/backend/executor/spi.c +++ b/src/backend/executor/spi.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/spi.c,v 1.99 2003/07/21 17:05:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/spi.c,v 1.100 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -95,8 +95,8 @@ SPI_connect(void) /* * Create memory contexts for this procedure * - * XXX it would be better to use PortalContext as the parent context, - * but we may not be inside a portal (consider deferred-trigger + * XXX it would be better to use PortalContext as the parent context, but + * we may not be inside a portal (consider deferred-trigger * execution). */ _SPI_current->procCxt = AllocSetContextCreate(TopTransactionContext, @@ -799,7 +799,7 @@ SPI_cursor_open(const char *name, void *plan, Datum *Values, const char *Nulls) */ PortalDefineQuery(portal, NULL, /* unfortunately don't have sourceText */ - "SELECT", /* cursor's query is always a SELECT */ + "SELECT", /* cursor's query is always a SELECT */ makeList1(queryTree), makeList1(planTree), PortalGetHeapMemory(portal)); @@ -1007,9 +1007,9 @@ _SPI_execute(const char *src, int tcount, _SPI_plan *plan) /* * Do parse analysis and rule rewrite for each raw parsetree. * - * We save the querytrees from each raw parsetree as a separate - * sublist. This allows _SPI_execute_plan() to know where the - * boundaries between original queries fall. + * We save the querytrees from each raw parsetree as a separate sublist. + * This allows _SPI_execute_plan() to know where the boundaries + * between original queries fall. */ query_list_list = NIL; plan_list = NIL; @@ -1136,8 +1136,8 @@ _SPI_execute_plan(_SPI_plan *plan, Datum *Values, const char *Nulls, foreach(query_list_list_item, query_list_list) { - List *query_list = lfirst(query_list_list_item); - List *query_list_item; + List *query_list = lfirst(query_list_list_item); + List *query_list_item; /* Reset state for each original parsetree */ /* (at most one of its querytrees will be marked canSetTag) */ @@ -1148,7 +1148,7 @@ _SPI_execute_plan(_SPI_plan *plan, Datum *Values, const char *Nulls, foreach(query_list_item, query_list) { - Query *queryTree = (Query *) lfirst(query_list_item); + Query *queryTree = (Query *) lfirst(query_list_item); Plan *planTree; QueryDesc *qdesc; DestReceiver *dest; @@ -1190,10 +1190,10 @@ _SPI_pquery(QueryDesc *queryDesc, bool runit, int tcount) { case CMD_SELECT: res = SPI_OK_SELECT; - if (queryDesc->parsetree->into != NULL) /* select into table */ + if (queryDesc->parsetree->into != NULL) /* select into table */ { res = SPI_OK_SELINTO; - queryDesc->dest = None_Receiver; /* don't output results */ + queryDesc->dest = None_Receiver; /* don't output results */ } break; case CMD_INSERT: @@ -1351,7 +1351,7 @@ _SPI_checktuples(void) SPITupleTable *tuptable = _SPI_current->tuptable; bool failed = false; - if (tuptable == NULL) /* spi_dest_startup was not called */ + if (tuptable == NULL) /* spi_dest_startup was not called */ failed = true; else if (processed != (tuptable->alloced - tuptable->free)) failed = true; @@ -1372,7 +1372,8 @@ _SPI_copy_plan(_SPI_plan *plan, int location) parentcxt = _SPI_current->procCxt; else if (location == _SPI_CPLAN_TOPCXT) parentcxt = TopMemoryContext; - else /* (this case not currently used) */ + else +/* (this case not currently used) */ parentcxt = CurrentMemoryContext; /* diff --git a/src/backend/executor/tstoreReceiver.c b/src/backend/executor/tstoreReceiver.c index 3d8479faee..0989eb3e27 100644 --- a/src/backend/executor/tstoreReceiver.c +++ b/src/backend/executor/tstoreReceiver.c @@ -9,7 +9,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/tstoreReceiver.c,v 1.6 2003/05/08 18:16:36 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/tstoreReceiver.c,v 1.7 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,10 +21,10 @@ typedef struct { - DestReceiver pub; - Tuplestorestate *tstore; - MemoryContext cxt; -} TStoreState; + DestReceiver pub; + Tuplestorestate *tstore; + MemoryContext cxt; +} TStoreState; /* diff --git a/src/backend/lib/stringinfo.c b/src/backend/lib/stringinfo.c index 03251beed9..9424070e50 100644 --- a/src/backend/lib/stringinfo.c +++ b/src/backend/lib/stringinfo.c @@ -9,7 +9,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: stringinfo.c,v 1.34 2003/04/24 21:16:43 tgl Exp $ + * $Id: stringinfo.c,v 1.35 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -62,7 +62,7 @@ initStringInfo(StringInfo str) * strcat. */ void -appendStringInfo(StringInfo str, const char *fmt, ...) +appendStringInfo(StringInfo str, const char *fmt,...) { for (;;) { @@ -86,7 +86,7 @@ appendStringInfo(StringInfo str, const char *fmt, ...) * appendStringInfoVA * * Attempt to format text data under the control of fmt (an sprintf-style - * format string) and append it to whatever is already in str. If successful + * format string) and append it to whatever is already in str. If successful * return true; if not (because there's not enough space), return false * without modifying str. Typically the caller would enlarge str and retry * on false return --- see appendStringInfo for standard usage pattern. @@ -113,9 +113,9 @@ appendStringInfoVA(StringInfo str, const char *fmt, va_list args) return false; /* - * Assert check here is to catch buggy vsnprintf that overruns - * the specified buffer length. Solaris 7 in 64-bit mode is - * an example of a platform with such a bug. + * Assert check here is to catch buggy vsnprintf that overruns the + * specified buffer length. Solaris 7 in 64-bit mode is an example of + * a platform with such a bug. */ #ifdef USE_ASSERT_CHECKING str->data[str->maxlen - 1] = '\0'; diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c index 9c80651d5f..9b9ffecbca 100644 --- a/src/backend/libpq/auth.c +++ b/src/backend/libpq/auth.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/libpq/auth.c,v 1.108 2003/07/28 06:27:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/auth.c,v 1.109 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -221,8 +221,8 @@ pg_krb5_init(void) if (retval) { ereport(LOG, - (errmsg("kerberos sname_to_principal(\"%s\") returned error %d", - PG_KRB_SRVNAM, retval))); + (errmsg("kerberos sname_to_principal(\"%s\") returned error %d", + PG_KRB_SRVNAM, retval))); com_err("postgres", retval, "while getting server principal for service \"%s\"", PG_KRB_SRVNAM); @@ -432,7 +432,7 @@ ClientAuthentication(Port *port) * out the less clueful good guys. */ { - char hostinfo[NI_MAXHOST]; + char hostinfo[NI_MAXHOST]; getnameinfo_all(&port->raddr.addr, port->raddr.salen, hostinfo, sizeof(hostinfo), @@ -441,15 +441,15 @@ ClientAuthentication(Port *port) #ifdef USE_SSL ereport(FATAL, - (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), - errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s", - hostinfo, port->user_name, port->database_name, - port->ssl ? gettext("SSL on") : gettext("SSL off")))); + (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), + errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s", + hostinfo, port->user_name, port->database_name, + port->ssl ? gettext("SSL on") : gettext("SSL off")))); #else ereport(FATAL, - (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), - errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"", - hostinfo, port->user_name, port->database_name))); + (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), + errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"", + hostinfo, port->user_name, port->database_name))); #endif break; } @@ -460,7 +460,7 @@ ClientAuthentication(Port *port) || port->laddr.addr.ss_family != AF_INET) ereport(FATAL, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("kerberos 4 only supports IPv4 connections"))); + errmsg("kerberos 4 only supports IPv4 connections"))); sendAuthRequest(port, AUTH_REQ_KRB4); status = pg_krb4_recvauth(port); break; @@ -492,7 +492,7 @@ ClientAuthentication(Port *port) if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0) ereport(FATAL, (errcode_for_socket_access(), - errmsg("failed to enable credential receipt: %m"))); + errmsg("failed to enable credential receipt: %m"))); } #endif if (port->raddr.addr.ss_family == AF_UNIX) @@ -755,22 +755,22 @@ recv_password_packet(Port *port) if (PG_PROTOCOL_MAJOR(port->proto) >= 3) { /* Expect 'p' message type */ - int mtype; + int mtype; mtype = pq_getbyte(); if (mtype != 'p') { /* * If the client just disconnects without offering a password, - * don't make a log entry. This is legal per protocol spec and - * in fact commonly done by psql, so complaining just clutters - * the log. + * don't make a log entry. This is legal per protocol spec + * and in fact commonly done by psql, so complaining just + * clutters the log. */ if (mtype != EOF) ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("expected password response, got msg type %d", - mtype))); + errmsg("expected password response, got msg type %d", + mtype))); return NULL; /* EOF or bad message type */ } } @@ -782,7 +782,7 @@ recv_password_packet(Port *port) } initStringInfo(&buf); - if (pq_getmessage(&buf, 1000)) /* receive password */ + if (pq_getmessage(&buf, 1000)) /* receive password */ { /* EOF - pq_getmessage already logged a suitable message */ pfree(buf.data); @@ -804,7 +804,7 @@ recv_password_packet(Port *port) (errmsg("received password packet"))); /* - * Return the received string. Note we do not attempt to do any + * Return the received string. Note we do not attempt to do any * character-set conversion on it; since we don't yet know the * client's encoding, there wouldn't be much point. */ diff --git a/src/backend/libpq/be-fsstubs.c b/src/backend/libpq/be-fsstubs.c index 00bd01b6ae..5a33712243 100644 --- a/src/backend/libpq/be-fsstubs.c +++ b/src/backend/libpq/be-fsstubs.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/libpq/be-fsstubs.c,v 1.66 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/be-fsstubs.c,v 1.67 2003/08/04 00:43:18 momjian Exp $ * * NOTES * This should be moved to a more appropriate place. It is here @@ -372,7 +372,7 @@ lo_import(PG_FUNCTION_ARGS) if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to use server-side lo_import()"), + errmsg("must be superuser to use server-side lo_import()"), errhint("Anyone can use the client-side lo_import() provided by libpq."))); #endif @@ -439,7 +439,7 @@ lo_export(PG_FUNCTION_ARGS) if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to use server-side lo_export()"), + errmsg("must be superuser to use server-side lo_export()"), errhint("Anyone can use the client-side lo_export() provided by libpq."))); #endif diff --git a/src/backend/libpq/be-secure.c b/src/backend/libpq/be-secure.c index 0bd4f78741..7089b5077a 100644 --- a/src/backend/libpq/be-secure.c +++ b/src/backend/libpq/be-secure.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/libpq/be-secure.c,v 1.37 2003/07/27 21:49:53 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/be-secure.c,v 1.38 2003/08/04 00:43:18 momjian Exp $ * * Since the server static private key ($DataDir/server.key) * will normally be stored unencrypted so that the database @@ -187,7 +187,6 @@ OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\ AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\ KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\ -----END DH PARAMETERS-----\n"; - #endif /* ------------------------------------------------------------ */ @@ -258,7 +257,7 @@ secure_read(Port *port, void *ptr, size_t len) #ifdef USE_SSL if (port->ssl) { - rloop: +rloop: n = SSL_read(port->ssl, ptr, len); switch (SSL_get_error(port->ssl, n)) { @@ -328,7 +327,7 @@ secure_write(Port *port, void *ptr, size_t len) if (port->ssl->state != SSL_ST_OK) ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("SSL failed to send renegotiation request"))); + errmsg("SSL failed to send renegotiation request"))); port->ssl->state |= SSL_ST_ACCEPT; SSL_do_handshake(port->ssl); if (port->ssl->state != SSL_ST_OK) @@ -338,7 +337,7 @@ secure_write(Port *port, void *ptr, size_t len) port->count = 0; } - wloop: +wloop: n = SSL_write(port->ssl, ptr, len); switch (SSL_get_error(port->ssl, n)) { @@ -436,7 +435,7 @@ load_dh_file(int keylength) (codes & DH_CHECK_P_NOT_SAFE_PRIME)) { elog(LOG, - "DH error (%s): neither suitable generator or safe prime", + "DH error (%s): neither suitable generator or safe prime", fnbuf); return NULL; } @@ -620,21 +619,21 @@ initialize_SSL(void) if (!SSL_CTX_use_certificate_file(SSL_context, fnbuf, SSL_FILETYPE_PEM)) ereport(FATAL, (errcode(ERRCODE_CONFIG_FILE_ERROR), - errmsg("could not load server certificate file \"%s\": %s", - fnbuf, SSLerrmessage()))); + errmsg("could not load server certificate file \"%s\": %s", + fnbuf, SSLerrmessage()))); snprintf(fnbuf, sizeof(fnbuf), "%s/server.key", DataDir); if (stat(fnbuf, &buf) == -1) ereport(FATAL, (errcode_for_file_access(), - errmsg("could not access private key file \"%s\": %m", - fnbuf))); + errmsg("could not access private key file \"%s\": %m", + fnbuf))); if (!S_ISREG(buf.st_mode) || (buf.st_mode & (S_IRWXG | S_IRWXO)) || buf.st_uid != getuid()) ereport(FATAL, (errcode(ERRCODE_CONFIG_FILE_ERROR), - errmsg("unsafe permissions on private key file \"%s\"", - fnbuf), + errmsg("unsafe permissions on private key file \"%s\"", + fnbuf), errdetail("File must be owned by the database user and must have no permissions for \"group\" or \"other\"."))); if (!SSL_CTX_use_PrivateKey_file(SSL_context, fnbuf, SSL_FILETYPE_PEM)) diff --git a/src/backend/libpq/crypt.c b/src/backend/libpq/crypt.c index c1443e5674..9629a47aa9 100644 --- a/src/backend/libpq/crypt.c +++ b/src/backend/libpq/crypt.c @@ -9,7 +9,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/libpq/crypt.c,v 1.54 2003/07/22 19:00:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/crypt.c,v 1.55 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -119,7 +119,10 @@ md5_crypt_verify(const Port *port, const char *user, char *client_pass) default: if (isMD5(shadow_pass)) { - /* Encrypt user-supplied password to match MD5 in pg_shadow */ + /* + * Encrypt user-supplied password to match MD5 in + * pg_shadow + */ crypt_client_pass = palloc(MD5_PASSWD_LEN + 1); if (!EncryptMD5(client_pass, port->user_name, diff --git a/src/backend/libpq/hba.c b/src/backend/libpq/hba.c index f9f77cda57..1c42d1a7d4 100644 --- a/src/backend/libpq/hba.c +++ b/src/backend/libpq/hba.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/libpq/hba.c,v 1.109 2003/08/01 23:24:28 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/hba.c,v 1.110 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -392,7 +392,7 @@ get_group_line(const char *group) /* * Lookup a user name in the pg_shadow file */ -List ** +List ** get_user_line(const char *user) { return (List **) bsearch((void *) user, @@ -416,7 +416,7 @@ check_group(char *group, char *user) { foreach(l, lnext(lnext(*line))) if (strcmp(lfirst(l), user) == 0) - return true; + return true; } return false; @@ -547,13 +547,14 @@ static void parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) { int line_number; - char *token; - char *db; - char *user; - struct addrinfo *file_ip_addr = NULL, *file_ip_mask = NULL; - struct addrinfo hints; - struct sockaddr_storage *mask; - char *cidr_slash; + char *token; + char *db; + char *user; + struct addrinfo *file_ip_addr = NULL, + *file_ip_mask = NULL; + struct addrinfo hints; + struct sockaddr_storage *mask; + char *cidr_slash; int ret; Assert(line != NIL); @@ -595,11 +596,11 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) return; } else if (strcmp(token, "host") == 0 - || strcmp(token, "hostssl") == 0 - || strcmp(token, "hostnossl") == 0) + || strcmp(token, "hostssl") == 0 + || strcmp(token, "hostnossl") == 0) { - if (token[4] == 's') /* "hostssl" */ + if (token[4] == 's') /* "hostssl" */ { #ifdef USE_SSL /* Record does not match if we are not on an SSL connection */ @@ -616,7 +617,7 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) #endif } #ifdef USE_SSL - else if (token[4] == 'n') /* "hostnossl" */ + else if (token[4] == 'n') /* "hostnossl" */ { /* Record does not match if we are on an SSL connection */ if (port->ssl) @@ -643,7 +644,7 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) token = lfirst(line); /* Check if it has a CIDR suffix and if so isolate it */ - cidr_slash = strchr(token,'/'); + cidr_slash = strchr(token, '/'); if (cidr_slash) *cidr_slash = '\0'; @@ -698,7 +699,7 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) if (ret || !file_ip_mask) goto hba_syntax; - mask = (struct sockaddr_storage *)file_ip_mask->ai_addr; + mask = (struct sockaddr_storage *) file_ip_mask->ai_addr; if (file_ip_addr->ai_family != mask->ss_family) goto hba_syntax; @@ -714,7 +715,7 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) /* Must meet network restrictions */ if (!rangeSockAddr(&port->raddr.addr, - (struct sockaddr_storage *)file_ip_addr->ai_addr, + (struct sockaddr_storage *) file_ip_addr->ai_addr, mask)) goto hba_freeaddr; @@ -743,8 +744,8 @@ hba_syntax: else ereport(LOG, (errcode(ERRCODE_CONFIG_FILE_ERROR), - errmsg("missing field in pg_hba.conf file at end of line %d", - line_number))); + errmsg("missing field in pg_hba.conf file at end of line %d", + line_number))); *error_p = true; @@ -1012,8 +1013,8 @@ ident_syntax: else ereport(LOG, (errcode(ERRCODE_CONFIG_FILE_ERROR), - errmsg("missing entry in pg_ident.conf file at end of line %d", - line_number))); + errmsg("missing entry in pg_ident.conf file at end of line %d", + line_number))); *error_p = true; } @@ -1044,7 +1045,7 @@ check_ident_usermap(const char *usermap_name, { ereport(LOG, (errcode(ERRCODE_CONFIG_FILE_ERROR), - errmsg("cannot use IDENT authentication without usermap field"))); + errmsg("cannot use IDENT authentication without usermap field"))); found_entry = false; } else if (strcmp(usermap_name, "sameuser") == 0) @@ -1215,11 +1216,13 @@ ident_inet(const SockAddr remote_addr, char ident_port[NI_MAXSERV]; char ident_query[80]; char ident_response[80 + IDENT_USERNAME_MAX]; - struct addrinfo *ident_serv = NULL, *la = NULL, hints; + struct addrinfo *ident_serv = NULL, + *la = NULL, + hints; /* - * Might look a little weird to first convert it to text and - * then back to sockaddr, but it's protocol independent. + * Might look a little weird to first convert it to text and then back + * to sockaddr, but it's protocol independent. */ getnameinfo_all(&remote_addr.addr, remote_addr.salen, remote_addr_s, sizeof(remote_addr_s), @@ -1254,22 +1257,23 @@ ident_inet(const SockAddr remote_addr, rc = getaddrinfo_all(local_addr_s, NULL, &hints, &la); if (rc || !la) return false; /* we don't expect this to happen */ - + sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype, ident_serv->ai_protocol); if (sock_fd < 0) { ereport(LOG, (errcode_for_socket_access(), - errmsg("could not create socket for IDENT connection: %m"))); + errmsg("could not create socket for IDENT connection: %m"))); ident_return = false; goto ident_inet_done; } + /* * Bind to the address which the client originally contacted, * otherwise the ident server won't be able to match up the right - * connection. This is necessary if the PostgreSQL server is - * running on an IP alias. + * connection. This is necessary if the PostgreSQL server is running + * on an IP alias. */ rc = bind(sock_fd, la->ai_addr, la->ai_addrlen); if (rc != 0) @@ -1282,7 +1286,7 @@ ident_inet(const SockAddr remote_addr, goto ident_inet_done; } - rc = connect(sock_fd, ident_serv->ai_addr, + rc = connect(sock_fd, ident_serv->ai_addr, ident_serv->ai_addrlen); if (rc != 0) { @@ -1354,12 +1358,12 @@ ident_unix(int sock, char *ident_user) { #if defined(HAVE_GETPEEREID) /* OpenBSD style: */ - uid_t uid; - gid_t gid; + uid_t uid; + gid_t gid; struct passwd *pass; errno = 0; - if (getpeereid(sock,&uid,&gid) != 0) + if (getpeereid(sock, &uid, &gid) != 0) { /* We didn't get a valid credentials struct. */ ereport(LOG, @@ -1491,8 +1495,7 @@ ident_unix(int sock, char *ident_user) return false; #endif } - -#endif /* HAVE_UNIX_SOCKETS */ +#endif /* HAVE_UNIX_SOCKETS */ /* diff --git a/src/backend/libpq/ip.c b/src/backend/libpq/ip.c index 8fd3941266..a17c817c65 100644 --- a/src/backend/libpq/ip.c +++ b/src/backend/libpq/ip.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/libpq/ip.c,v 1.17 2003/08/01 17:53:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/ip.c,v 1.18 2003/08/04 00:43:18 momjian Exp $ * * This file and the IPV6 implementation were initially provided by * Nigel Kukard , Linux Based Systems Design @@ -34,30 +34,30 @@ #endif #include #include - #endif #include "libpq/ip.h" -static int rangeSockAddrAF_INET(const struct sockaddr_in *addr, - const struct sockaddr_in *netaddr, - const struct sockaddr_in *netmask); +static int rangeSockAddrAF_INET(const struct sockaddr_in * addr, + const struct sockaddr_in * netaddr, + const struct sockaddr_in * netmask); + #ifdef HAVE_IPV6 -static int rangeSockAddrAF_INET6(const struct sockaddr_in6 *addr, - const struct sockaddr_in6 *netaddr, - const struct sockaddr_in6 *netmask); +static int rangeSockAddrAF_INET6(const struct sockaddr_in6 * addr, + const struct sockaddr_in6 * netaddr, + const struct sockaddr_in6 * netmask); #endif #ifdef HAVE_UNIX_SOCKETS -static int getaddrinfo_unix(const char *path, - const struct addrinfo *hintsp, - struct addrinfo **result); +static int getaddrinfo_unix(const char *path, + const struct addrinfo * hintsp, + struct addrinfo ** result); -static int getnameinfo_unix(const struct sockaddr_un *sa, int salen, - char *node, int nodelen, - char *service, int servicelen, - int flags); +static int getnameinfo_unix(const struct sockaddr_un * sa, int salen, + char *node, int nodelen, + char *service, int servicelen, + int flags); #endif @@ -66,7 +66,7 @@ static int getnameinfo_unix(const struct sockaddr_un *sa, int salen, */ int getaddrinfo_all(const char *hostname, const char *servname, - const struct addrinfo *hintp, struct addrinfo **result) + const struct addrinfo * hintp, struct addrinfo ** result) { #ifdef HAVE_UNIX_SOCKETS if (hintp != NULL && hintp->ai_family == AF_UNIX) @@ -89,7 +89,7 @@ getaddrinfo_all(const char *hostname, const char *servname, * not safe to look at ai_family in the addrinfo itself. */ void -freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai) +freeaddrinfo_all(int hint_ai_family, struct addrinfo * ai) { #ifdef HAVE_UNIX_SOCKETS if (hint_ai_family == AF_UNIX) @@ -123,12 +123,12 @@ freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai) * guaranteed to be filled with something even on failure return. */ int -getnameinfo_all(const struct sockaddr_storage *addr, int salen, +getnameinfo_all(const struct sockaddr_storage * addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags) { - int rc; + int rc; #ifdef HAVE_UNIX_SOCKETS if (addr && addr->ss_family == AF_UNIX) @@ -166,8 +166,8 @@ getnameinfo_all(const struct sockaddr_storage *addr, int salen, * ------- */ static int -getaddrinfo_unix(const char *path, const struct addrinfo *hintsp, - struct addrinfo **result) +getaddrinfo_unix(const char *path, const struct addrinfo * hintsp, + struct addrinfo ** result) { struct addrinfo hints; struct addrinfo *aip; @@ -178,9 +178,7 @@ getaddrinfo_unix(const char *path, const struct addrinfo *hintsp, MemSet(&hints, 0, sizeof(hints)); if (strlen(path) >= sizeof(unp->sun_path)) - { return EAI_FAIL; - } if (hintsp == NULL) { @@ -234,139 +232,123 @@ getaddrinfo_unix(const char *path, const struct addrinfo *hintsp, * Convert an address to a hostname. */ static int -getnameinfo_unix(const struct sockaddr_un *sa, int salen, +getnameinfo_unix(const struct sockaddr_un * sa, int salen, char *node, int nodelen, char *service, int servicelen, int flags) { - int ret = -1; + int ret = -1; /* Invalid arguments. */ if (sa == NULL || sa->sun_family != AF_UNIX || (node == NULL && service == NULL)) - { return EAI_FAIL; - } /* We don't support those. */ if ((node && !(flags & NI_NUMERICHOST)) || (service && !(flags & NI_NUMERICSERV))) - { return EAI_FAIL; - } if (node) { ret = snprintf(node, nodelen, "%s", "localhost"); if (ret == -1 || ret > nodelen) - { return EAI_MEMORY; - } } if (service) { ret = snprintf(service, servicelen, "%s", sa->sun_path); if (ret == -1 || ret > servicelen) - { return EAI_MEMORY; - } } return 0; } - #endif /* HAVE_UNIX_SOCKETS */ int -rangeSockAddr(const struct sockaddr_storage *addr, - const struct sockaddr_storage *netaddr, - const struct sockaddr_storage *netmask) +rangeSockAddr(const struct sockaddr_storage * addr, + const struct sockaddr_storage * netaddr, + const struct sockaddr_storage * netmask) { if (addr->ss_family == AF_INET) - return rangeSockAddrAF_INET((struct sockaddr_in *)addr, - (struct sockaddr_in *)netaddr, - (struct sockaddr_in *)netmask); + return rangeSockAddrAF_INET((struct sockaddr_in *) addr, + (struct sockaddr_in *) netaddr, + (struct sockaddr_in *) netmask); #ifdef HAVE_IPV6 else if (addr->ss_family == AF_INET6) - return rangeSockAddrAF_INET6((struct sockaddr_in6 *)addr, - (struct sockaddr_in6 *)netaddr, - (struct sockaddr_in6 *)netmask); + return rangeSockAddrAF_INET6((struct sockaddr_in6 *) addr, + (struct sockaddr_in6 *) netaddr, + (struct sockaddr_in6 *) netmask); #endif else return 0; } /* - * SockAddr_cidr_mask - make a network mask of the appropriate family - * and required number of significant bits + * SockAddr_cidr_mask - make a network mask of the appropriate family + * and required number of significant bits * * Note: Returns a static pointer for the mask, so it's not thread safe, - * and a second call will overwrite the data. + * and a second call will overwrite the data. */ int -SockAddr_cidr_mask(struct sockaddr_storage **mask, char *numbits, int family) +SockAddr_cidr_mask(struct sockaddr_storage ** mask, char *numbits, int family) { - long bits; - char *endptr; -static struct sockaddr_storage sock; - struct sockaddr_in mask4; + long bits; + char *endptr; + static struct sockaddr_storage sock; + struct sockaddr_in mask4; + #ifdef HAVE_IPV6 - struct sockaddr_in6 mask6; + struct sockaddr_in6 mask6; #endif bits = strtol(numbits, &endptr, 10); if (*numbits == '\0' || *endptr != '\0') - { return -1; - } if ((bits < 0) || (family == AF_INET && bits > 32) #ifdef HAVE_IPV6 || (family == AF_INET6 && bits > 128) #endif ) - { return -1; - } *mask = &sock; switch (family) { case AF_INET: - mask4.sin_addr.s_addr = + mask4.sin_addr.s_addr = htonl((0xffffffffUL << (32 - bits)) - & 0xffffffffUL); - memcpy(&sock, &mask4, sizeof(mask4)); + & 0xffffffffUL); + memcpy(&sock, &mask4, sizeof(mask4)); break; #ifdef HAVE_IPV6 case AF_INET6: - { - int i; - - for (i = 0; i < 16; i++) { - if (bits <= 0) + int i; + + for (i = 0; i < 16; i++) { - mask6.sin6_addr.s6_addr[i] = 0; + if (bits <= 0) + mask6.sin6_addr.s6_addr[i] = 0; + else if (bits >= 8) + mask6.sin6_addr.s6_addr[i] = 0xff; + else + { + mask6.sin6_addr.s6_addr[i] = + (0xff << (8 - bits)) & 0xff; + } + bits -= 8; } - else if (bits >= 8) - { - mask6.sin6_addr.s6_addr[i] = 0xff; - } - else - { - mask6.sin6_addr.s6_addr[i] = - (0xff << (8 - bits)) & 0xff; - } - bits -= 8; + memcpy(&sock, &mask6, sizeof(mask6)); + break; } - memcpy(&sock, &mask6, sizeof(mask6)); - break; - } #endif default: return -1; @@ -377,8 +359,8 @@ static struct sockaddr_storage sock; } static int -rangeSockAddrAF_INET(const struct sockaddr_in *addr, const struct sockaddr_in *netaddr, - const struct sockaddr_in *netmask) +rangeSockAddrAF_INET(const struct sockaddr_in * addr, const struct sockaddr_in * netaddr, + const struct sockaddr_in * netmask) { if (((addr->sin_addr.s_addr ^ netaddr->sin_addr.s_addr) & netmask->sin_addr.s_addr) == 0) @@ -390,9 +372,9 @@ rangeSockAddrAF_INET(const struct sockaddr_in *addr, const struct sockaddr_in *n #ifdef HAVE_IPV6 static int -rangeSockAddrAF_INET6(const struct sockaddr_in6 *addr, - const struct sockaddr_in6 *netaddr, - const struct sockaddr_in6 *netmask) +rangeSockAddrAF_INET6(const struct sockaddr_in6 * addr, + const struct sockaddr_in6 * netaddr, + const struct sockaddr_in6 * netmask) { int i; @@ -405,6 +387,5 @@ rangeSockAddrAF_INET6(const struct sockaddr_in6 *addr, return 1; } + #endif - - diff --git a/src/backend/libpq/md5.c b/src/backend/libpq/md5.c index dbf639fc74..05adff56a6 100644 --- a/src/backend/libpq/md5.c +++ b/src/backend/libpq/md5.c @@ -14,7 +14,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/libpq/md5.c,v 1.19 2002/10/03 17:09:41 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/md5.c,v 1.20 2003/08/04 00:43:18 momjian Exp $ */ @@ -35,8 +35,8 @@ #include "postgres_fe.h" #ifndef WIN32 #include "libpq/crypt.h" -#endif /* WIN32 */ -#endif /* FRONTEND */ +#endif /* WIN32 */ +#endif /* FRONTEND */ #ifdef MD5_ODBC #include "md5.h" diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c index 2f6d0245bf..5ae7e1ae2c 100644 --- a/src/backend/libpq/pqcomm.c +++ b/src/backend/libpq/pqcomm.c @@ -30,7 +30,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/libpq/pqcomm.c,v 1.161 2003/07/27 21:49:53 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/pqcomm.c,v 1.162 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -151,6 +151,7 @@ pq_close(void) { /* Cleanly shut down SSL layer */ secure_close(MyProcPort); + /* * Formerly we did an explicit close() here, but it seems better * to leave the socket open until the process dies. This allows @@ -208,10 +209,11 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, int maxconn; int one = 1; int ret; - char portNumberStr[64]; - char *service; - struct addrinfo *addrs = NULL, *addr; - struct addrinfo hint; + char portNumberStr[64]; + char *service; + struct addrinfo *addrs = NULL, + *addr; + struct addrinfo hint; int listen_index = 0; int added = 0; @@ -245,8 +247,8 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, hostName, service, gai_strerror(ret)))); else ereport(LOG, - (errmsg("could not translate service \"%s\" to address: %s", - service, gai_strerror(ret)))); + (errmsg("could not translate service \"%s\" to address: %s", + service, gai_strerror(ret)))); freeaddrinfo_all(hint.ai_family, addrs); return STATUS_ERROR; } @@ -255,9 +257,9 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, { if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family)) { - /* Only set up a unix domain socket when - * they really asked for it. The service/port - * is different in that case. + /* + * Only set up a unix domain socket when they really asked for + * it. The service/port is different in that case. */ continue; } @@ -285,7 +287,7 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, if (!IS_AF_UNIX(addr->ai_family)) { if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, - (char *) &one, sizeof(one))) == -1) + (char *) &one, sizeof(one))) == -1) { ereport(LOG, (errcode_for_socket_access(), @@ -299,7 +301,7 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, if (addr->ai_family == AF_INET6) { if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, - (char *)&one, sizeof(one)) == -1) + (char *) &one, sizeof(one)) == -1) { ereport(LOG, (errcode_for_socket_access(), @@ -311,10 +313,10 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, #endif /* - * Note: This might fail on some OS's, like Linux - * older than 2.4.21-pre3, that don't have the IPV6_V6ONLY - * socket option, and map ipv4 addresses to ipv6. It will - * show ::ffff:ipv4 for all ipv4 connections. + * Note: This might fail on some OS's, like Linux older than + * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and + * map ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all + * ipv4 connections. */ err = bind(fd, addr->ai_addr, addr->ai_addrlen); if (err < 0) @@ -323,12 +325,12 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, (errcode_for_socket_access(), errmsg("failed to bind server socket: %m"), (IS_AF_UNIX(addr->ai_family)) ? - errhint("Is another postmaster already running on port %d?" - " If not, remove socket node \"%s\" and retry.", - (int) portNumber, sock_path) : - errhint("Is another postmaster already running on port %d?" - " If not, wait a few seconds and retry.", - (int) portNumber))); + errhint("Is another postmaster already running on port %d?" + " If not, remove socket node \"%s\" and retry.", + (int) portNumber, sock_path) : + errhint("Is another postmaster already running on port %d?" + " If not, wait a few seconds and retry.", + (int) portNumber))); closesocket(fd); continue; } @@ -345,10 +347,10 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, #endif /* - * Select appropriate accept-queue length limit. PG_SOMAXCONN - * is only intended to provide a clamp on the request on - * platforms where an overly large request provokes a kernel - * error (are there any?). + * Select appropriate accept-queue length limit. PG_SOMAXCONN is + * only intended to provide a clamp on the request on platforms + * where an overly large request provokes a kernel error (are + * there any?). */ maxconn = MaxBackends * 2; if (maxconn > PG_SOMAXCONN) @@ -465,7 +467,6 @@ Setup_AF_UNIX(void) } return STATUS_OK; } - #endif /* HAVE_UNIX_SOCKETS */ @@ -485,8 +486,8 @@ StreamConnection(int server_fd, Port *port) /* accept connection and fill in the client (remote) address */ port->raddr.salen = sizeof(port->raddr.addr); if ((port->sock = accept(server_fd, - (struct sockaddr *) &port->raddr.addr, - &port->raddr.salen)) < 0) + (struct sockaddr *) & port->raddr.addr, + &port->raddr.salen)) < 0) { ereport(LOG, (errcode_for_socket_access(), @@ -495,6 +496,7 @@ StreamConnection(int server_fd, Port *port) } #ifdef SCO_ACCEPT_BUG + /* * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it * shouldn't hurt to catch it for all versions of those platforms. @@ -571,19 +573,19 @@ TouchSocketFile(void) if (sock_path[0] != '\0') { /* - * utime() is POSIX standard, utimes() is a common alternative. - * If we have neither, there's no way to affect the mod or access + * utime() is POSIX standard, utimes() is a common alternative. If + * we have neither, there's no way to affect the mod or access * time of the socket :-( * * In either path, we ignore errors; there's no point in complaining. */ #ifdef HAVE_UTIME utime(sock_path, NULL); -#else /* !HAVE_UTIME */ +#else /* !HAVE_UTIME */ #ifdef HAVE_UTIMES utimes(sock_path, NULL); -#endif /* HAVE_UTIMES */ -#endif /* HAVE_UTIME */ +#endif /* HAVE_UTIMES */ +#endif /* HAVE_UTIME */ } } @@ -634,9 +636,10 @@ pq_recvbuf(void) continue; /* Ok if interrupted */ /* - * Careful: an ereport() that tries to write to the client would - * cause recursion to here, leading to stack overflow and core - * dump! This message must go *only* to the postmaster log. + * Careful: an ereport() that tries to write to the client + * would cause recursion to here, leading to stack overflow + * and core dump! This message must go *only* to the + * postmaster log. */ ereport(COMMERROR, (errcode_for_socket_access(), @@ -646,8 +649,8 @@ pq_recvbuf(void) if (r == 0) { /* - * EOF detected. We used to write a log message here, but it's - * better to expect the ultimate caller to do that. + * EOF detected. We used to write a log message here, but + * it's better to expect the ultimate caller to do that. */ return EOF; } @@ -894,9 +897,10 @@ pq_flush(void) continue; /* Ok if we were interrupted */ /* - * Careful: an ereport() that tries to write to the client would - * cause recursion to here, leading to stack overflow and core - * dump! This message must go *only* to the postmaster log. + * Careful: an ereport() that tries to write to the client + * would cause recursion to here, leading to stack overflow + * and core dump! This message must go *only* to the + * postmaster log. * * If a client disconnects while we're in the midst of output, we * might write quite a bit of data before we get to a safe diff --git a/src/backend/libpq/pqformat.c b/src/backend/libpq/pqformat.c index 8b04dbe705..d5b1baded2 100644 --- a/src/backend/libpq/pqformat.c +++ b/src/backend/libpq/pqformat.c @@ -24,7 +24,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/libpq/pqformat.c,v 1.32 2003/07/22 19:00:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/pqformat.c,v 1.33 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -58,12 +58,12 @@ * pq_getmsgbyte - get a raw byte from a message buffer * pq_getmsgint - get a binary integer from a message buffer * pq_getmsgint64 - get a binary 8-byte int from a message buffer - * pq_getmsgfloat4 - get a float4 from a message buffer - * pq_getmsgfloat8 - get a float8 from a message buffer + * pq_getmsgfloat4 - get a float4 from a message buffer + * pq_getmsgfloat8 - get a float8 from a message buffer * pq_getmsgbytes - get raw data from a message buffer - * pq_copymsgbytes - copy raw data from a message buffer + * pq_copymsgbytes - copy raw data from a message buffer * pq_getmsgtext - get a counted text string (with conversion) - * pq_getmsgstring - get a null-terminated text string (with conversion) + * pq_getmsgstring - get a null-terminated text string (with conversion) * pq_getmsgend - verify message fully consumed */ @@ -90,10 +90,12 @@ void pq_beginmessage(StringInfo buf, char msgtype) { initStringInfo(buf); + /* * We stash the message type into the buffer's cursor field, expecting - * that the pq_sendXXX routines won't touch it. We could alternatively - * make it the first byte of the buffer contents, but this seems easier. + * that the pq_sendXXX routines won't touch it. We could + * alternatively make it the first byte of the buffer contents, but + * this seems easier. */ buf->cursor = msgtype; } @@ -122,7 +124,7 @@ pq_sendbytes(StringInfo buf, const char *data, int datalen) * pq_sendcountedtext - append a counted text string (with character set conversion) * * The data sent to the frontend by this routine is a 4-byte count field - * followed by the string. The count includes itself or not, as per the + * followed by the string. The count includes itself or not, as per the * countincludesself flag (pre-3.0 protocol requires it to include itself). * The passed text string need not be null-terminated, and the data sent * to the frontend isn't either. @@ -173,9 +175,7 @@ pq_sendtext(StringInfo buf, const char *str, int slen) pfree(p); } else - { appendBinaryStringInfo(buf, str, slen); - } } /* -------------------------------- @@ -200,9 +200,7 @@ pq_sendstring(StringInfo buf, const char *str) pfree(p); } else - { appendBinaryStringInfo(buf, str, slen + 1); - } } /* -------------------------------- @@ -281,9 +279,9 @@ pq_sendfloat4(StringInfo buf, float4 f) { union { - float4 f; - uint32 i; - } swap; + float4 f; + uint32 i; + } swap; swap.f = f; swap.i = htonl(swap.i); @@ -308,9 +306,9 @@ pq_sendfloat8(StringInfo buf, float8 f) #ifdef INT64_IS_BUSTED union { - float8 f; - uint32 h[2]; - } swap; + float8 f; + uint32 h[2]; + } swap; swap.f = f; swap.h[0] = htonl(swap.h[0]); @@ -332,9 +330,9 @@ pq_sendfloat8(StringInfo buf, float8 f) #else union { - float8 f; - int64 i; - } swap; + float8 f; + int64 i; + } swap; swap.f = f; pq_sendint64(buf, swap.i); @@ -515,7 +513,7 @@ pq_getmsgint64(StringInfo msg) } /* -------------------------------- - * pq_getmsgfloat4 - get a float4 from a message buffer + * pq_getmsgfloat4 - get a float4 from a message buffer * * See notes for pq_sendfloat4. * -------------------------------- @@ -525,16 +523,16 @@ pq_getmsgfloat4(StringInfo msg) { union { - float4 f; - uint32 i; - } swap; + float4 f; + uint32 i; + } swap; swap.i = pq_getmsgint(msg, 4); return swap.f; } /* -------------------------------- - * pq_getmsgfloat8 - get a float8 from a message buffer + * pq_getmsgfloat8 - get a float8 from a message buffer * * See notes for pq_sendfloat8. * -------------------------------- @@ -545,9 +543,9 @@ pq_getmsgfloat8(StringInfo msg) #ifdef INT64_IS_BUSTED union { - float8 f; - uint32 h[2]; - } swap; + float8 f; + uint32 h[2]; + } swap; /* Have to figure out endianness by testing... */ if (((uint32) 1) == htonl((uint32) 1)) @@ -566,9 +564,9 @@ pq_getmsgfloat8(StringInfo msg) #else union { - float8 f; - int64 i; - } swap; + float8 f; + int64 i; + } swap; swap.i = pq_getmsgint64(msg); return swap.f; @@ -597,7 +595,7 @@ pq_getmsgbytes(StringInfo msg, int datalen) } /* -------------------------------- - * pq_copymsgbytes - copy raw data from a message buffer + * pq_copymsgbytes - copy raw data from a message buffer * * Same as above, except data is copied to caller's buffer. * -------------------------------- @@ -623,8 +621,8 @@ pq_copymsgbytes(StringInfo msg, char *buf, int datalen) char * pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes) { - char *str; - char *p; + char *str; + char *p; if (rawbytes < 0 || rawbytes > (msg->len - msg->cursor)) ereport(ERROR, @@ -635,9 +633,7 @@ pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes) p = (char *) pg_client_to_server((unsigned char *) str, rawbytes); if (p != str) /* actual conversion has been done? */ - { *nbytes = strlen(p); - } else { p = (char *) palloc(rawbytes + 1); @@ -649,7 +645,7 @@ pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes) } /* -------------------------------- - * pq_getmsgstring - get a null-terminated text string (with conversion) + * pq_getmsgstring - get a null-terminated text string (with conversion) * * May return a pointer directly into the message buffer, or a pointer * to a palloc'd conversion result. @@ -658,14 +654,15 @@ pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes) const char * pq_getmsgstring(StringInfo msg) { - char *str; - int slen; + char *str; + int slen; str = &msg->data[msg->cursor]; + /* * It's safe to use strlen() here because a StringInfo is guaranteed - * to have a trailing null byte. But check we found a null inside - * the message. + * to have a trailing null byte. But check we found a null inside the + * message. */ slen = strlen(str); if (msg->cursor + slen >= msg->len) diff --git a/src/backend/main/main.c b/src/backend/main/main.c index 862194b17d..fcc6ea5a7e 100644 --- a/src/backend/main/main.c +++ b/src/backend/main/main.c @@ -13,7 +13,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/main/main.c,v 1.59 2003/07/27 21:49:53 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/main/main.c,v 1.60 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -163,6 +163,7 @@ main(int argc, char *argv[]) { #ifndef WIN32 #ifndef __BEOS__ + /* * Make sure we are not running as root. * @@ -175,8 +176,8 @@ main(int argc, char *argv[]) gettext("\"root\" execution of the PostgreSQL server is not permitted.\n" "The server must be started under an unprivileged user id to prevent\n" "possible system security compromise. See the documentation for\n" - "more information on how to properly start the server.\n" - )); + "more information on how to properly start the server.\n" + )); exit(1); } #endif /* !__BEOS__ */ @@ -193,16 +194,16 @@ main(int argc, char *argv[]) if (getuid() != geteuid()) { fprintf(stderr, - gettext("%s: real and effective user ids must match\n"), + gettext("%s: real and effective user ids must match\n"), argv[0]); exit(1); } -#endif /* !WIN32 */ +#endif /* !WIN32 */ } /* - * Now dispatch to one of PostmasterMain, PostgresMain, GucInfoMain, or - * BootstrapMain depending on the program name (and possibly first + * Now dispatch to one of PostmasterMain, PostgresMain, GucInfoMain, + * or BootstrapMain depending on the program name (and possibly first * argument) we were called with. The lack of consistency here is * historical. */ @@ -223,8 +224,8 @@ main(int argc, char *argv[]) /* * If the first argument is "--help-config", then invoke runtime - * configuration option display mode. - * We remove "--help-config" from the arguments passed on to GucInfoMain. + * configuration option display mode. We remove "--help-config" from + * the arguments passed on to GucInfoMain. */ if (argc > 1 && strcmp(new_argv[1], "--help-config") == 0) exit(GucInfoMain(argc - 1, new_argv + 1)); @@ -246,7 +247,7 @@ main(int argc, char *argv[]) pw_name_persist = strdup(pw->pw_name); #else { - long namesize = 256 /* UNLEN */ + 1; + long namesize = 256 /* UNLEN */ + 1; pw_name_persist = malloc(namesize); if (!GetUserName(pw_name_persist, &namesize)) diff --git a/src/backend/nodes/bitmapset.c b/src/backend/nodes/bitmapset.c index c4576cf3b3..e444f449e1 100644 --- a/src/backend/nodes/bitmapset.c +++ b/src/backend/nodes/bitmapset.c @@ -14,7 +14,7 @@ * Copyright (c) 2003, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/bitmapset.c,v 1.3 2003/07/22 23:30:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/bitmapset.c,v 1.4 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -38,7 +38,7 @@ * where x's are unspecified bits. The two's complement negative is formed * by inverting all the bits and adding one. Inversion gives * yyyyyy01111 - * where each y is the inverse of the corresponding x. Incrementing gives + * where each y is the inverse of the corresponding x. Incrementing gives * yyyyyy10000 * and then ANDing with the original value gives * 00000010000 @@ -65,41 +65,41 @@ */ static const uint8 rightmost_one_pos[256] = { - 0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, - 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 + 0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 }; static const uint8 number_of_ones[256] = { - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 }; @@ -107,7 +107,7 @@ static const uint8 number_of_ones[256] = { * bms_copy - make a palloc'd copy of a bitmapset */ Bitmapset * -bms_copy(const Bitmapset *a) +bms_copy(const Bitmapset * a) { Bitmapset *result; size_t size; @@ -127,7 +127,7 @@ bms_copy(const Bitmapset *a) * be reported as equal to a palloc'd value containing no members. */ bool -bms_equal(const Bitmapset *a, const Bitmapset *b) +bms_equal(const Bitmapset * a, const Bitmapset * b) { const Bitmapset *shorter; const Bitmapset *longer; @@ -143,9 +143,7 @@ bms_equal(const Bitmapset *a, const Bitmapset *b) return bms_is_empty(b); } else if (b == NULL) - { return bms_is_empty(a); - } /* Identify shorter and longer input */ if (a->nwords <= b->nwords) { @@ -199,7 +197,7 @@ bms_make_singleton(int x) * Same as pfree except for allowing NULL input */ void -bms_free(Bitmapset *a) +bms_free(Bitmapset * a) { if (a) pfree(a); @@ -216,7 +214,7 @@ bms_free(Bitmapset *a) * bms_union - set union */ Bitmapset * -bms_union(const Bitmapset *a, const Bitmapset *b) +bms_union(const Bitmapset * a, const Bitmapset * b) { Bitmapset *result; const Bitmapset *other; @@ -242,9 +240,7 @@ bms_union(const Bitmapset *a, const Bitmapset *b) /* And union the shorter input into the result */ otherlen = other->nwords; for (i = 0; i < otherlen; i++) - { result->words[i] |= other->words[i]; - } return result; } @@ -252,7 +248,7 @@ bms_union(const Bitmapset *a, const Bitmapset *b) * bms_intersect - set intersection */ Bitmapset * -bms_intersect(const Bitmapset *a, const Bitmapset *b) +bms_intersect(const Bitmapset * a, const Bitmapset * b) { Bitmapset *result; const Bitmapset *other; @@ -276,9 +272,7 @@ bms_intersect(const Bitmapset *a, const Bitmapset *b) /* And intersect the longer input with the result */ resultlen = result->nwords; for (i = 0; i < resultlen; i++) - { result->words[i] &= other->words[i]; - } return result; } @@ -286,7 +280,7 @@ bms_intersect(const Bitmapset *a, const Bitmapset *b) * bms_difference - set difference (ie, A without members of B) */ Bitmapset * -bms_difference(const Bitmapset *a, const Bitmapset *b) +bms_difference(const Bitmapset * a, const Bitmapset * b) { Bitmapset *result; int shortlen; @@ -302,9 +296,7 @@ bms_difference(const Bitmapset *a, const Bitmapset *b) /* And remove b's bits from result */ shortlen = Min(a->nwords, b->nwords); for (i = 0; i < shortlen; i++) - { - result->words[i] &= ~ b->words[i]; - } + result->words[i] &= ~b->words[i]; return result; } @@ -312,7 +304,7 @@ bms_difference(const Bitmapset *a, const Bitmapset *b) * bms_is_subset - is A a subset of B? */ bool -bms_is_subset(const Bitmapset *a, const Bitmapset *b) +bms_is_subset(const Bitmapset * a, const Bitmapset * b) { int shortlen; int longlen; @@ -327,7 +319,7 @@ bms_is_subset(const Bitmapset *a, const Bitmapset *b) shortlen = Min(a->nwords, b->nwords); for (i = 0; i < shortlen; i++) { - if ((a->words[i] & ~ b->words[i]) != 0) + if ((a->words[i] & ~b->words[i]) != 0) return false; } /* Check extra words */ @@ -347,7 +339,7 @@ bms_is_subset(const Bitmapset *a, const Bitmapset *b) * bms_is_member - is X a member of A? */ bool -bms_is_member(int x, const Bitmapset *a) +bms_is_member(int x, const Bitmapset * a) { int wordnum, bitnum; @@ -370,7 +362,7 @@ bms_is_member(int x, const Bitmapset *a) * bms_overlap - do sets overlap (ie, have a nonempty intersection)? */ bool -bms_overlap(const Bitmapset *a, const Bitmapset *b) +bms_overlap(const Bitmapset * a, const Bitmapset * b) { int shortlen; int i; @@ -392,7 +384,7 @@ bms_overlap(const Bitmapset *a, const Bitmapset *b) * bms_nonempty_difference - do sets have a nonempty difference? */ bool -bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b) +bms_nonempty_difference(const Bitmapset * a, const Bitmapset * b) { int shortlen; int i; @@ -406,7 +398,7 @@ bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b) shortlen = Min(a->nwords, b->nwords); for (i = 0; i < shortlen; i++) { - if ((a->words[i] & ~ b->words[i]) != 0) + if ((a->words[i] & ~b->words[i]) != 0) return true; } /* Check extra words in a */ @@ -424,11 +416,11 @@ bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b) * Raises error if |a| is not 1. */ int -bms_singleton_member(const Bitmapset *a) +bms_singleton_member(const Bitmapset * a) { - int result = -1; - int nwords; - int wordnum; + int result = -1; + int nwords; + int wordnum; if (a == NULL) elog(ERROR, "bitmapset is empty"); @@ -459,11 +451,11 @@ bms_singleton_member(const Bitmapset *a) * bms_num_members - count members of set */ int -bms_num_members(const Bitmapset *a) +bms_num_members(const Bitmapset * a) { - int result = 0; - int nwords; - int wordnum; + int result = 0; + int nwords; + int wordnum; if (a == NULL) return 0; @@ -488,11 +480,11 @@ bms_num_members(const Bitmapset *a) * This is faster than making an exact count with bms_num_members(). */ BMS_Membership -bms_membership(const Bitmapset *a) +bms_membership(const Bitmapset * a) { BMS_Membership result = BMS_EMPTY_SET; - int nwords; - int wordnum; + int nwords; + int wordnum; if (a == NULL) return BMS_EMPTY_SET; @@ -517,10 +509,10 @@ bms_membership(const Bitmapset *a) * This is even faster than bms_membership(). */ bool -bms_is_empty(const Bitmapset *a) +bms_is_empty(const Bitmapset * a) { - int nwords; - int wordnum; + int nwords; + int wordnum; if (a == NULL) return true; @@ -552,7 +544,7 @@ bms_is_empty(const Bitmapset *a) * Input set is modified or recycled! */ Bitmapset * -bms_add_member(Bitmapset *a, int x) +bms_add_member(Bitmapset * a, int x) { int wordnum, bitnum; @@ -573,9 +565,7 @@ bms_add_member(Bitmapset *a, int x) result = bms_make_singleton(x); nwords = a->nwords; for (i = 0; i < nwords; i++) - { result->words[i] |= a->words[i]; - } pfree(a); return result; } @@ -592,7 +582,7 @@ bms_add_member(Bitmapset *a, int x) * Input set is modified in-place! */ Bitmapset * -bms_del_member(Bitmapset *a, int x) +bms_del_member(Bitmapset * a, int x) { int wordnum, bitnum; @@ -604,9 +594,7 @@ bms_del_member(Bitmapset *a, int x) wordnum = WORDNUM(x); bitnum = BITNUM(x); if (wordnum < a->nwords) - { - a->words[wordnum] &= ~ ((bitmapword) 1 << bitnum); - } + a->words[wordnum] &= ~((bitmapword) 1 << bitnum); return a; } @@ -614,7 +602,7 @@ bms_del_member(Bitmapset *a, int x) * bms_add_members - like bms_union, but left input is recycled */ Bitmapset * -bms_add_members(Bitmapset *a, const Bitmapset *b) +bms_add_members(Bitmapset * a, const Bitmapset * b) { Bitmapset *result; const Bitmapset *other; @@ -640,9 +628,7 @@ bms_add_members(Bitmapset *a, const Bitmapset *b) /* And union the shorter input into the result */ otherlen = other->nwords; for (i = 0; i < otherlen; i++) - { result->words[i] |= other->words[i]; - } if (result != a) pfree(a); return result; @@ -652,7 +638,7 @@ bms_add_members(Bitmapset *a, const Bitmapset *b) * bms_int_members - like bms_intersect, but left input is recycled */ Bitmapset * -bms_int_members(Bitmapset *a, const Bitmapset *b) +bms_int_members(Bitmapset * a, const Bitmapset * b) { int shortlen; int i; @@ -668,13 +654,9 @@ bms_int_members(Bitmapset *a, const Bitmapset *b) /* Intersect b into a; we need never copy */ shortlen = Min(a->nwords, b->nwords); for (i = 0; i < shortlen; i++) - { a->words[i] &= b->words[i]; - } for (; i < a->nwords; i++) - { a->words[i] = 0; - } return a; } @@ -682,7 +664,7 @@ bms_int_members(Bitmapset *a, const Bitmapset *b) * bms_del_members - like bms_difference, but left input is recycled */ Bitmapset * -bms_del_members(Bitmapset *a, const Bitmapset *b) +bms_del_members(Bitmapset * a, const Bitmapset * b) { int shortlen; int i; @@ -695,9 +677,7 @@ bms_del_members(Bitmapset *a, const Bitmapset *b) /* Remove b's bits from a; we need never copy */ shortlen = Min(a->nwords, b->nwords); for (i = 0; i < shortlen; i++) - { - a->words[i] &= ~ b->words[i]; - } + a->words[i] &= ~b->words[i]; return a; } @@ -705,7 +685,7 @@ bms_del_members(Bitmapset *a, const Bitmapset *b) * bms_join - like bms_union, but *both* inputs are recycled */ Bitmapset * -bms_join(Bitmapset *a, Bitmapset *b) +bms_join(Bitmapset * a, Bitmapset * b) { Bitmapset *result; Bitmapset *other; @@ -731,9 +711,7 @@ bms_join(Bitmapset *a, Bitmapset *b) /* And union the shorter input into the result */ otherlen = other->nwords; for (i = 0; i < otherlen; i++) - { result->words[i] |= other->words[i]; - } if (other != result) /* pure paranoia */ pfree(other); return result; @@ -742,24 +720,22 @@ bms_join(Bitmapset *a, Bitmapset *b) /*---------- * bms_first_member - find and remove first member of a set * - * Returns -1 if set is empty. NB: set is destructively modified! + * Returns -1 if set is empty. NB: set is destructively modified! * * This is intended as support for iterating through the members of a set. * The typical pattern is * * tmpset = bms_copy(inputset); * while ((x = bms_first_member(tmpset)) >= 0) - * { * process member x; - * } * bms_free(tmpset); *---------- */ int -bms_first_member(Bitmapset *a) +bms_first_member(Bitmapset * a) { - int nwords; - int wordnum; + int nwords; + int wordnum; if (a == NULL) return -1; @@ -770,10 +746,10 @@ bms_first_member(Bitmapset *a) if (w != 0) { - int result; + int result; w = RIGHTMOST_ONE(w); - a->words[wordnum] &= ~ w; + a->words[wordnum] &= ~w; result = wordnum * BITS_PER_BITMAPWORD; while ((w & 255) == 0) diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c index 6945e98d5d..03349efdc7 100644 --- a/src/backend/nodes/copyfuncs.c +++ b/src/backend/nodes/copyfuncs.c @@ -4,7 +4,7 @@ * Copy functions for Postgres tree nodes. * * NOTE: we currently support copying all node types found in parse and - * plan trees. We do not support copying executor state trees; there + * plan trees. We do not support copying executor state trees; there * is no need for that, and no point in maintaining all the code that * would be needed. We also do not support copying Path trees, mainly * because the circular linkages between RelOptInfo and Path nodes can't @@ -15,7 +15,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/copyfuncs.c,v 1.260 2003/07/22 23:30:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/copyfuncs.c,v 1.261 2003/08/04 00:43:18 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,7 +30,7 @@ /* * Macros to simplify copying of different kinds of fields. Use these - * wherever possible to reduce the chance for silly typos. Note that these + * wherever possible to reduce the chance for silly typos. Note that these * hard-wire the convention that the local variables in a Copy routine are * named 'newnode' and 'from'. */ @@ -639,7 +639,7 @@ _copyRangeVar(RangeVar *from) /* * We don't need a _copyExpr because Expr is an abstract supertype which - * should never actually get instantiated. Also, since it has no common + * should never actually get instantiated. Also, since it has no common * fields except NodeTag, there's no need for a helper routine to factor * out copying the common fields... */ @@ -755,9 +755,9 @@ _copyArrayRef(ArrayRef *from) * _copyFuncExpr */ static FuncExpr * -_copyFuncExpr(FuncExpr *from) +_copyFuncExpr(FuncExpr * from) { - FuncExpr *newnode = makeNode(FuncExpr); + FuncExpr *newnode = makeNode(FuncExpr); COPY_SCALAR_FIELD(funcid); COPY_SCALAR_FIELD(funcresulttype); @@ -772,7 +772,7 @@ _copyFuncExpr(FuncExpr *from) * _copyOpExpr */ static OpExpr * -_copyOpExpr(OpExpr *from) +_copyOpExpr(OpExpr * from) { OpExpr *newnode = makeNode(OpExpr); @@ -789,9 +789,9 @@ _copyOpExpr(OpExpr *from) * _copyDistinctExpr (same as OpExpr) */ static DistinctExpr * -_copyDistinctExpr(DistinctExpr *from) +_copyDistinctExpr(DistinctExpr * from) { - DistinctExpr *newnode = makeNode(DistinctExpr); + DistinctExpr *newnode = makeNode(DistinctExpr); COPY_SCALAR_FIELD(opno); COPY_SCALAR_FIELD(opfuncid); @@ -806,9 +806,9 @@ _copyDistinctExpr(DistinctExpr *from) * _copyScalarArrayOpExpr */ static ScalarArrayOpExpr * -_copyScalarArrayOpExpr(ScalarArrayOpExpr *from) +_copyScalarArrayOpExpr(ScalarArrayOpExpr * from) { - ScalarArrayOpExpr *newnode = makeNode(ScalarArrayOpExpr); + ScalarArrayOpExpr *newnode = makeNode(ScalarArrayOpExpr); COPY_SCALAR_FIELD(opno); COPY_SCALAR_FIELD(opfuncid); @@ -822,9 +822,9 @@ _copyScalarArrayOpExpr(ScalarArrayOpExpr *from) * _copyBoolExpr */ static BoolExpr * -_copyBoolExpr(BoolExpr *from) +_copyBoolExpr(BoolExpr * from) { - BoolExpr *newnode = makeNode(BoolExpr); + BoolExpr *newnode = makeNode(BoolExpr); COPY_SCALAR_FIELD(boolop); COPY_NODE_FIELD(args); @@ -940,9 +940,9 @@ _copyCaseWhen(CaseWhen *from) * _copyArrayExpr */ static ArrayExpr * -_copyArrayExpr(ArrayExpr *from) +_copyArrayExpr(ArrayExpr * from) { - ArrayExpr *newnode = makeNode(ArrayExpr); + ArrayExpr *newnode = makeNode(ArrayExpr); COPY_SCALAR_FIELD(array_typeid); COPY_SCALAR_FIELD(element_typeid); @@ -956,7 +956,7 @@ _copyArrayExpr(ArrayExpr *from) * _copyCoalesceExpr */ static CoalesceExpr * -_copyCoalesceExpr(CoalesceExpr *from) +_copyCoalesceExpr(CoalesceExpr * from) { CoalesceExpr *newnode = makeNode(CoalesceExpr); @@ -970,9 +970,9 @@ _copyCoalesceExpr(CoalesceExpr *from) * _copyNullIfExpr (same as OpExpr) */ static NullIfExpr * -_copyNullIfExpr(NullIfExpr *from) +_copyNullIfExpr(NullIfExpr * from) { - NullIfExpr *newnode = makeNode(NullIfExpr); + NullIfExpr *newnode = makeNode(NullIfExpr); COPY_SCALAR_FIELD(opno); COPY_SCALAR_FIELD(opfuncid); @@ -1015,7 +1015,7 @@ _copyBooleanTest(BooleanTest *from) * _copyCoerceToDomain */ static CoerceToDomain * -_copyCoerceToDomain(CoerceToDomain *from) +_copyCoerceToDomain(CoerceToDomain * from) { CoerceToDomain *newnode = makeNode(CoerceToDomain); @@ -1031,7 +1031,7 @@ _copyCoerceToDomain(CoerceToDomain *from) * _copyCoerceToDomainValue */ static CoerceToDomainValue * -_copyCoerceToDomainValue(CoerceToDomainValue *from) +_copyCoerceToDomainValue(CoerceToDomainValue * from) { CoerceToDomainValue *newnode = makeNode(CoerceToDomainValue); @@ -1045,7 +1045,7 @@ _copyCoerceToDomainValue(CoerceToDomainValue *from) * _copySetToDefault */ static SetToDefault * -_copySetToDefault(SetToDefault *from) +_copySetToDefault(SetToDefault * from) { SetToDefault *newnode = makeNode(SetToDefault); @@ -1148,7 +1148,7 @@ _copyRestrictInfo(RestrictInfo *from) COPY_NODE_FIELD(clause); COPY_SCALAR_FIELD(ispusheddown); - COPY_NODE_FIELD(subclauseindices); /* XXX probably bad */ + COPY_NODE_FIELD(subclauseindices); /* XXX probably bad */ COPY_SCALAR_FIELD(eval_cost); COPY_SCALAR_FIELD(this_selec); COPY_BITMAPSET_FIELD(left_relids); @@ -1191,7 +1191,7 @@ _copyJoinInfo(JoinInfo *from) * _copyInClauseInfo */ static InClauseInfo * -_copyInClauseInfo(InClauseInfo *from) +_copyInClauseInfo(InClauseInfo * from) { InClauseInfo *newnode = makeNode(InClauseInfo); @@ -1532,9 +1532,9 @@ _copyQuery(Query *from) /* * We do not copy the other planner internal fields: base_rel_list, - * other_rel_list, join_rel_list, equi_key_list, query_pathkeys. - * That would get us into copying RelOptInfo/Path trees, which we don't - * want to do. It is necessary to copy in_info_list and hasJoinRTEs + * other_rel_list, join_rel_list, equi_key_list, query_pathkeys. That + * would get us into copying RelOptInfo/Path trees, which we don't + * want to do. It is necessary to copy in_info_list and hasJoinRTEs * for the benefit of inheritance_planner(), which may try to copy a * Query in which these are already set. */ @@ -1633,7 +1633,7 @@ _copyAlterTableStmt(AlterTableStmt *from) } static AlterDomainStmt * -_copyAlterDomainStmt(AlterDomainStmt *from) +_copyAlterDomainStmt(AlterDomainStmt * from) { AlterDomainStmt *newnode = makeNode(AlterDomainStmt); @@ -1644,7 +1644,7 @@ _copyAlterDomainStmt(AlterDomainStmt *from) COPY_SCALAR_FIELD(behavior); return newnode; -} +} static GrantStmt * _copyGrantStmt(GrantStmt *from) @@ -1685,7 +1685,7 @@ _copyFuncWithArgs(FuncWithArgs *from) } static DeclareCursorStmt * -_copyDeclareCursorStmt(DeclareCursorStmt *from) +_copyDeclareCursorStmt(DeclareCursorStmt * from) { DeclareCursorStmt *newnode = makeNode(DeclareCursorStmt); @@ -1747,7 +1747,7 @@ _copyCreateStmt(CreateStmt *from) } static InhRelation * -_copyInhRelation(InhRelation *from) +_copyInhRelation(InhRelation * from) { InhRelation *newnode = makeNode(InhRelation); @@ -2118,7 +2118,7 @@ _copyCreateSeqStmt(CreateSeqStmt *from) } static AlterSeqStmt * -_copyAlterSeqStmt(AlterSeqStmt *from) +_copyAlterSeqStmt(AlterSeqStmt * from) { AlterSeqStmt *newnode = makeNode(AlterSeqStmt); @@ -2171,7 +2171,7 @@ _copyCreateTrigStmt(CreateTrigStmt *from) COPY_NODE_FIELD(args); COPY_SCALAR_FIELD(before); COPY_SCALAR_FIELD(row); - strcpy(newnode->actions, from->actions); /* in-line string field */ + strcpy(newnode->actions, from->actions); /* in-line string field */ COPY_SCALAR_FIELD(isconstraint); COPY_SCALAR_FIELD(deferrable); COPY_SCALAR_FIELD(initdeferred); diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c index 513c17b048..924793d07e 100644 --- a/src/backend/nodes/equalfuncs.c +++ b/src/backend/nodes/equalfuncs.c @@ -11,14 +11,14 @@ * be handled easily in a simple depth-first traversal. * * Currently, in fact, equal() doesn't know how to compare Plan trees - * either. This might need to be fixed someday. + * either. This might need to be fixed someday. * * * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/equalfuncs.c,v 1.204 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/equalfuncs.c,v 1.205 2003/08/04 00:43:19 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -32,8 +32,8 @@ /* - * Macros to simplify comparison of different kinds of fields. Use these - * wherever possible to reduce the chance for silly typos. Note that these + * Macros to simplify comparison of different kinds of fields. Use these + * wherever possible to reduce the chance for silly typos. Note that these * hard-wire the convention that the local variables in an Equal routine are * named 'a' and 'b'. */ @@ -135,7 +135,7 @@ _equalRangeVar(RangeVar *a, RangeVar *b) /* * We don't need an _equalExpr because Expr is an abstract supertype which - * should never actually get instantiated. Also, since it has no common + * should never actually get instantiated. Also, since it has no common * fields except NodeTag, there's no need for a helper routine to factor * out comparing the common fields... */ @@ -224,11 +224,12 @@ _equalArrayRef(ArrayRef *a, ArrayRef *b) } static bool -_equalFuncExpr(FuncExpr *a, FuncExpr *b) +_equalFuncExpr(FuncExpr * a, FuncExpr * b) { COMPARE_SCALAR_FIELD(funcid); COMPARE_SCALAR_FIELD(funcresulttype); COMPARE_SCALAR_FIELD(funcretset); + /* * Special-case COERCE_DONTCARE, so that pathkeys can build coercion * nodes that are equal() to both explicit and implicit coercions. @@ -244,14 +245,15 @@ _equalFuncExpr(FuncExpr *a, FuncExpr *b) } static bool -_equalOpExpr(OpExpr *a, OpExpr *b) +_equalOpExpr(OpExpr * a, OpExpr * b) { COMPARE_SCALAR_FIELD(opno); + /* - * Special-case opfuncid: it is allowable for it to differ if one - * node contains zero and the other doesn't. This just means that the - * one node isn't as far along in the parse/plan pipeline and hasn't - * had the opfuncid cache filled yet. + * Special-case opfuncid: it is allowable for it to differ if one node + * contains zero and the other doesn't. This just means that the one + * node isn't as far along in the parse/plan pipeline and hasn't had + * the opfuncid cache filled yet. */ if (a->opfuncid != b->opfuncid && a->opfuncid != 0 && @@ -266,14 +268,15 @@ _equalOpExpr(OpExpr *a, OpExpr *b) } static bool -_equalDistinctExpr(DistinctExpr *a, DistinctExpr *b) +_equalDistinctExpr(DistinctExpr * a, DistinctExpr * b) { COMPARE_SCALAR_FIELD(opno); + /* - * Special-case opfuncid: it is allowable for it to differ if one - * node contains zero and the other doesn't. This just means that the - * one node isn't as far along in the parse/plan pipeline and hasn't - * had the opfuncid cache filled yet. + * Special-case opfuncid: it is allowable for it to differ if one node + * contains zero and the other doesn't. This just means that the one + * node isn't as far along in the parse/plan pipeline and hasn't had + * the opfuncid cache filled yet. */ if (a->opfuncid != b->opfuncid && a->opfuncid != 0 && @@ -288,14 +291,15 @@ _equalDistinctExpr(DistinctExpr *a, DistinctExpr *b) } static bool -_equalScalarArrayOpExpr(ScalarArrayOpExpr *a, ScalarArrayOpExpr *b) +_equalScalarArrayOpExpr(ScalarArrayOpExpr * a, ScalarArrayOpExpr * b) { COMPARE_SCALAR_FIELD(opno); + /* - * Special-case opfuncid: it is allowable for it to differ if one - * node contains zero and the other doesn't. This just means that the - * one node isn't as far along in the parse/plan pipeline and hasn't - * had the opfuncid cache filled yet. + * Special-case opfuncid: it is allowable for it to differ if one node + * contains zero and the other doesn't. This just means that the one + * node isn't as far along in the parse/plan pipeline and hasn't had + * the opfuncid cache filled yet. */ if (a->opfuncid != b->opfuncid && a->opfuncid != 0 && @@ -309,7 +313,7 @@ _equalScalarArrayOpExpr(ScalarArrayOpExpr *a, ScalarArrayOpExpr *b) } static bool -_equalBoolExpr(BoolExpr *a, BoolExpr *b) +_equalBoolExpr(BoolExpr * a, BoolExpr * b) { COMPARE_SCALAR_FIELD(boolop); COMPARE_NODE_FIELD(args); @@ -366,6 +370,7 @@ _equalRelabelType(RelabelType *a, RelabelType *b) COMPARE_NODE_FIELD(arg); COMPARE_SCALAR_FIELD(resulttype); COMPARE_SCALAR_FIELD(resulttypmod); + /* * Special-case COERCE_DONTCARE, so that pathkeys can build coercion * nodes that are equal() to both explicit and implicit coercions. @@ -399,7 +404,7 @@ _equalCaseWhen(CaseWhen *a, CaseWhen *b) } static bool -_equalArrayExpr(ArrayExpr *a, ArrayExpr *b) +_equalArrayExpr(ArrayExpr * a, ArrayExpr * b) { COMPARE_SCALAR_FIELD(array_typeid); COMPARE_SCALAR_FIELD(element_typeid); @@ -410,7 +415,7 @@ _equalArrayExpr(ArrayExpr *a, ArrayExpr *b) } static bool -_equalCoalesceExpr(CoalesceExpr *a, CoalesceExpr *b) +_equalCoalesceExpr(CoalesceExpr * a, CoalesceExpr * b) { COMPARE_SCALAR_FIELD(coalescetype); COMPARE_NODE_FIELD(args); @@ -419,14 +424,15 @@ _equalCoalesceExpr(CoalesceExpr *a, CoalesceExpr *b) } static bool -_equalNullIfExpr(NullIfExpr *a, NullIfExpr *b) +_equalNullIfExpr(NullIfExpr * a, NullIfExpr * b) { COMPARE_SCALAR_FIELD(opno); + /* - * Special-case opfuncid: it is allowable for it to differ if one - * node contains zero and the other doesn't. This just means that the - * one node isn't as far along in the parse/plan pipeline and hasn't - * had the opfuncid cache filled yet. + * Special-case opfuncid: it is allowable for it to differ if one node + * contains zero and the other doesn't. This just means that the one + * node isn't as far along in the parse/plan pipeline and hasn't had + * the opfuncid cache filled yet. */ if (a->opfuncid != b->opfuncid && a->opfuncid != 0 && @@ -459,11 +465,12 @@ _equalBooleanTest(BooleanTest *a, BooleanTest *b) } static bool -_equalCoerceToDomain(CoerceToDomain *a, CoerceToDomain *b) +_equalCoerceToDomain(CoerceToDomain * a, CoerceToDomain * b) { COMPARE_NODE_FIELD(arg); COMPARE_SCALAR_FIELD(resulttype); COMPARE_SCALAR_FIELD(resulttypmod); + /* * Special-case COERCE_DONTCARE, so that pathkeys can build coercion * nodes that are equal() to both explicit and implicit coercions. @@ -477,7 +484,7 @@ _equalCoerceToDomain(CoerceToDomain *a, CoerceToDomain *b) } static bool -_equalCoerceToDomainValue(CoerceToDomainValue *a, CoerceToDomainValue *b) +_equalCoerceToDomainValue(CoerceToDomainValue * a, CoerceToDomainValue * b) { COMPARE_SCALAR_FIELD(typeId); COMPARE_SCALAR_FIELD(typeMod); @@ -486,7 +493,7 @@ _equalCoerceToDomainValue(CoerceToDomainValue *a, CoerceToDomainValue *b) } static bool -_equalSetToDefault(SetToDefault *a, SetToDefault *b) +_equalSetToDefault(SetToDefault * a, SetToDefault * b) { COMPARE_SCALAR_FIELD(typeId); COMPARE_SCALAR_FIELD(typeMod); @@ -554,11 +561,13 @@ _equalRestrictInfo(RestrictInfo *a, RestrictInfo *b) { COMPARE_NODE_FIELD(clause); COMPARE_SCALAR_FIELD(ispusheddown); + /* - * We ignore subclauseindices, eval_cost, this_selec, left/right_relids, - * left/right_pathkey, and left/right_bucketsize, since they may not be - * set yet, and should be derivable from the clause anyway. Probably it's - * not really necessary to compare any of these remaining fields ... + * We ignore subclauseindices, eval_cost, this_selec, + * left/right_relids, left/right_pathkey, and left/right_bucketsize, + * since they may not be set yet, and should be derivable from the + * clause anyway. Probably it's not really necessary to compare any + * of these remaining fields ... */ COMPARE_SCALAR_FIELD(mergejoinoperator); COMPARE_SCALAR_FIELD(left_sortop); @@ -578,7 +587,7 @@ _equalJoinInfo(JoinInfo *a, JoinInfo *b) } static bool -_equalInClauseInfo(InClauseInfo *a, InClauseInfo *b) +_equalInClauseInfo(InClauseInfo * a, InClauseInfo * b) { COMPARE_BITMAPSET_FIELD(lefthand); COMPARE_BITMAPSET_FIELD(righthand); @@ -620,9 +629,9 @@ _equalQuery(Query *a, Query *b) /* * We do not check the other planner internal fields: base_rel_list, - * other_rel_list, join_rel_list, equi_key_list, query_pathkeys. - * They might not be set yet, and in any case they should be derivable - * from the other fields. + * other_rel_list, join_rel_list, equi_key_list, query_pathkeys. They + * might not be set yet, and in any case they should be derivable from + * the other fields. */ return true; } @@ -706,7 +715,7 @@ _equalAlterTableStmt(AlterTableStmt *a, AlterTableStmt *b) } static bool -_equalAlterDomainStmt(AlterDomainStmt *a, AlterDomainStmt *b) +_equalAlterDomainStmt(AlterDomainStmt * a, AlterDomainStmt * b) { COMPARE_SCALAR_FIELD(subtype); COMPARE_NODE_FIELD(typename); @@ -750,7 +759,7 @@ _equalFuncWithArgs(FuncWithArgs *a, FuncWithArgs *b) } static bool -_equalDeclareCursorStmt(DeclareCursorStmt *a, DeclareCursorStmt *b) +_equalDeclareCursorStmt(DeclareCursorStmt * a, DeclareCursorStmt * b) { COMPARE_STRING_FIELD(portalname); COMPARE_SCALAR_FIELD(options); @@ -802,7 +811,7 @@ _equalCreateStmt(CreateStmt *a, CreateStmt *b) } static bool -_equalInhRelation(InhRelation *a, InhRelation *b) +_equalInhRelation(InhRelation * a, InhRelation * b) { COMPARE_NODE_FIELD(relation); COMPARE_SCALAR_FIELD(including_defaults); @@ -1113,7 +1122,7 @@ _equalCreateSeqStmt(CreateSeqStmt *a, CreateSeqStmt *b) } static bool -_equalAlterSeqStmt(AlterSeqStmt *a, AlterSeqStmt *b) +_equalAlterSeqStmt(AlterSeqStmt * a, AlterSeqStmt * b) { COMPARE_NODE_FIELD(sequence); COMPARE_NODE_FIELD(options); @@ -1156,7 +1165,7 @@ _equalCreateTrigStmt(CreateTrigStmt *a, CreateTrigStmt *b) COMPARE_NODE_FIELD(args); COMPARE_SCALAR_FIELD(before); COMPARE_SCALAR_FIELD(row); - if (strcmp(a->actions, b->actions) != 0) /* in-line string field */ + if (strcmp(a->actions, b->actions) != 0) /* in-line string field */ return false; COMPARE_SCALAR_FIELD(isconstraint); COMPARE_SCALAR_FIELD(deferrable); @@ -1400,7 +1409,7 @@ _equalParamRef(ParamRef *a, ParamRef *b) static bool _equalAConst(A_Const *a, A_Const *b) { - if (!equal(&a->val, &b->val)) /* hack for in-line Value field */ + if (!equal(&a->val, &b->val)) /* hack for in-line Value field */ return false; COMPARE_NODE_FIELD(typename); @@ -1649,9 +1658,9 @@ equal(void *a, void *b) switch (nodeTag(a)) { - /* - * PRIMITIVE NODES - */ + /* + * PRIMITIVE NODES + */ case T_Resdom: retval = _equalResdom(a, b); break; @@ -1841,7 +1850,7 @@ equal(void *a, void *b) retval = _equalCreateStmt(a, b); break; case T_InhRelation: - retval = _equalInhRelation(a,b); + retval = _equalInhRelation(a, b); break; case T_DefineStmt: retval = _equalDefineStmt(a, b); diff --git a/src/backend/nodes/list.c b/src/backend/nodes/list.c index b0f6821b8c..354134caea 100644 --- a/src/backend/nodes/list.c +++ b/src/backend/nodes/list.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/list.c,v 1.51 2003/07/22 23:30:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/list.c,v 1.52 2003/08/04 00:43:19 momjian Exp $ * * NOTES * XXX a few of the following functions are duplicated to handle @@ -202,7 +202,7 @@ nconc(List *l1, List *l2) * since we avoid having to chase down the list again each time. */ void -FastAppend(FastList *fl, void *datum) +FastAppend(FastList * fl, void *datum) { List *cell = makeList1(datum); @@ -223,7 +223,7 @@ FastAppend(FastList *fl, void *datum) * FastAppendi - same for integers */ void -FastAppendi(FastList *fl, int datum) +FastAppendi(FastList * fl, int datum) { List *cell = makeListi1(datum); @@ -244,7 +244,7 @@ FastAppendi(FastList *fl, int datum) * FastAppendo - same for Oids */ void -FastAppendo(FastList *fl, Oid datum) +FastAppendo(FastList * fl, Oid datum) { List *cell = makeListo1(datum); @@ -267,14 +267,12 @@ FastAppendo(FastList *fl, Oid datum) * Note that the cells of the second argument are absorbed into the FastList. */ void -FastConc(FastList *fl, List *cells) +FastConc(FastList * fl, List *cells) { if (cells == NIL) return; /* nothing to do */ if (fl->tail) - { lnext(fl->tail) = cells; - } else { /* First cell of list */ @@ -292,14 +290,12 @@ FastConc(FastList *fl, List *cells) * Note that the cells of the second argument are absorbed into the first. */ void -FastConcFast(FastList *fl, FastList *fl2) +FastConcFast(FastList * fl, FastList * fl2) { if (fl2->head == NIL) return; /* nothing to do */ if (fl->tail) - { lnext(fl->tail) = fl2->head; - } else { /* First cell of list */ @@ -319,9 +315,7 @@ nth(int n, List *l) { /* XXX assume list is long enough */ while (n-- > 0) - { l = lnext(l); - } return lfirst(l); } @@ -781,4 +775,5 @@ lreverse(List *l) result = lcons(lfirst(i), result); return result; } + #endif diff --git a/src/backend/nodes/nodes.c b/src/backend/nodes/nodes.c index f71bd020ce..4a4e0c98f5 100644 --- a/src/backend/nodes/nodes.c +++ b/src/backend/nodes/nodes.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/nodes.c,v 1.19 2002/12/16 16:22:46 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/nodes.c,v 1.20 2003/08/04 00:43:19 momjian Exp $ * * HISTORY * Andrew Yu Oct 20, 1994 file creation @@ -24,4 +24,4 @@ * Support for newNode() macro */ -Node *newNodeMacroHolder; +Node *newNodeMacroHolder; diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c index fba5955379..9247bb00d2 100644 --- a/src/backend/nodes/outfuncs.c +++ b/src/backend/nodes/outfuncs.c @@ -8,12 +8,12 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/outfuncs.c,v 1.214 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/outfuncs.c,v 1.215 2003/08/04 00:43:19 momjian Exp $ * * NOTES * Every node type that can appear in stored rules' parsetrees *must* * have an output function defined here (as well as an input function - * in readfuncs.c). For use in debugging, we also provide output + * in readfuncs.c). For use in debugging, we also provide output * functions for nodes that appear in raw parsetrees, path, and plan trees. * These nodes however need not have input functions. * @@ -31,8 +31,8 @@ /* - * Macros to simplify output of different kinds of fields. Use these - * wherever possible to reduce the chance for silly typos. Note that these + * Macros to simplify output of different kinds of fields. Use these + * wherever possible to reduce the chance for silly typos. Note that these * hard-wire conventions about the names of the local variables in an Out * routine. */ @@ -184,7 +184,7 @@ _outOidList(StringInfo str, List *list) * an integer List would be. */ static void -_outBitmapset(StringInfo str, Bitmapset *bms) +_outBitmapset(StringInfo str, Bitmapset * bms) { Bitmapset *tmpset; int x; @@ -192,9 +192,7 @@ _outBitmapset(StringInfo str, Bitmapset *bms) appendStringInfoChar(str, '('); tmpset = bms_copy(bms); while ((x = bms_first_member(tmpset)) >= 0) - { appendStringInfo(str, " %d", x); - } bms_free(tmpset); appendStringInfoChar(str, ')'); } @@ -633,7 +631,7 @@ _outArrayRef(StringInfo str, ArrayRef *node) } static void -_outFuncExpr(StringInfo str, FuncExpr *node) +_outFuncExpr(StringInfo str, FuncExpr * node) { WRITE_NODE_TYPE("FUNCEXPR"); @@ -645,7 +643,7 @@ _outFuncExpr(StringInfo str, FuncExpr *node) } static void -_outOpExpr(StringInfo str, OpExpr *node) +_outOpExpr(StringInfo str, OpExpr * node) { WRITE_NODE_TYPE("OPEXPR"); @@ -657,7 +655,7 @@ _outOpExpr(StringInfo str, OpExpr *node) } static void -_outDistinctExpr(StringInfo str, DistinctExpr *node) +_outDistinctExpr(StringInfo str, DistinctExpr * node) { WRITE_NODE_TYPE("DISTINCTEXPR"); @@ -669,7 +667,7 @@ _outDistinctExpr(StringInfo str, DistinctExpr *node) } static void -_outScalarArrayOpExpr(StringInfo str, ScalarArrayOpExpr *node) +_outScalarArrayOpExpr(StringInfo str, ScalarArrayOpExpr * node) { WRITE_NODE_TYPE("SCALARARRAYOPEXPR"); @@ -680,7 +678,7 @@ _outScalarArrayOpExpr(StringInfo str, ScalarArrayOpExpr *node) } static void -_outBoolExpr(StringInfo str, BoolExpr *node) +_outBoolExpr(StringInfo str, BoolExpr * node) { char *opstr = NULL; @@ -780,7 +778,7 @@ _outCaseWhen(StringInfo str, CaseWhen *node) } static void -_outArrayExpr(StringInfo str, ArrayExpr *node) +_outArrayExpr(StringInfo str, ArrayExpr * node) { WRITE_NODE_TYPE("ARRAY"); @@ -791,7 +789,7 @@ _outArrayExpr(StringInfo str, ArrayExpr *node) } static void -_outCoalesceExpr(StringInfo str, CoalesceExpr *node) +_outCoalesceExpr(StringInfo str, CoalesceExpr * node) { WRITE_NODE_TYPE("COALESCE"); @@ -800,7 +798,7 @@ _outCoalesceExpr(StringInfo str, CoalesceExpr *node) } static void -_outNullIfExpr(StringInfo str, NullIfExpr *node) +_outNullIfExpr(StringInfo str, NullIfExpr * node) { WRITE_NODE_TYPE("NULLIFEXPR"); @@ -830,7 +828,7 @@ _outBooleanTest(StringInfo str, BooleanTest *node) } static void -_outCoerceToDomain(StringInfo str, CoerceToDomain *node) +_outCoerceToDomain(StringInfo str, CoerceToDomain * node) { WRITE_NODE_TYPE("COERCETODOMAIN"); @@ -841,7 +839,7 @@ _outCoerceToDomain(StringInfo str, CoerceToDomain *node) } static void -_outCoerceToDomainValue(StringInfo str, CoerceToDomainValue *node) +_outCoerceToDomainValue(StringInfo str, CoerceToDomainValue * node) { WRITE_NODE_TYPE("COERCETODOMAINVALUE"); @@ -850,7 +848,7 @@ _outCoerceToDomainValue(StringInfo str, CoerceToDomainValue *node) } static void -_outSetToDefault(StringInfo str, SetToDefault *node) +_outSetToDefault(StringInfo str, SetToDefault * node) { WRITE_NODE_TYPE("SETTODEFAULT"); @@ -979,7 +977,7 @@ _outAppendPath(StringInfo str, AppendPath *node) } static void -_outResultPath(StringInfo str, ResultPath *node) +_outResultPath(StringInfo str, ResultPath * node) { WRITE_NODE_TYPE("RESULTPATH"); @@ -990,7 +988,7 @@ _outResultPath(StringInfo str, ResultPath *node) } static void -_outMaterialPath(StringInfo str, MaterialPath *node) +_outMaterialPath(StringInfo str, MaterialPath * node) { WRITE_NODE_TYPE("MATERIALPATH"); @@ -1000,7 +998,7 @@ _outMaterialPath(StringInfo str, MaterialPath *node) } static void -_outUniquePath(StringInfo str, UniquePath *node) +_outUniquePath(StringInfo str, UniquePath * node) { WRITE_NODE_TYPE("UNIQUEPATH"); @@ -1079,7 +1077,7 @@ _outJoinInfo(StringInfo str, JoinInfo *node) } static void -_outInClauseInfo(StringInfo str, InClauseInfo *node) +_outInClauseInfo(StringInfo str, InClauseInfo * node) { WRITE_NODE_TYPE("INCLAUSEINFO"); @@ -1132,7 +1130,7 @@ _outNotifyStmt(StringInfo str, NotifyStmt *node) } static void -_outDeclareCursorStmt(StringInfo str, DeclareCursorStmt *node) +_outDeclareCursorStmt(StringInfo str, DeclareCursorStmt * node) { WRITE_NODE_TYPE("DECLARECURSOR"); @@ -1820,9 +1818,11 @@ _outNode(StringInfo str, void *obj) break; default: + /* * This should be an ERROR, but it's too useful to be able - * to dump structures that _outNode only understands part of. + * to dump structures that _outNode only understands part + * of. */ elog(WARNING, "could not dump unrecognized node type: %d", (int) nodeTag(obj)); diff --git a/src/backend/nodes/readfuncs.c b/src/backend/nodes/readfuncs.c index abc3a1b010..32af1d9292 100644 --- a/src/backend/nodes/readfuncs.c +++ b/src/backend/nodes/readfuncs.c @@ -8,11 +8,11 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/readfuncs.c,v 1.159 2003/07/22 23:30:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/readfuncs.c,v 1.160 2003/08/04 00:43:19 momjian Exp $ * * NOTES * Path and Plan nodes do not have any readfuncs support, because we - * never have occasion to read them in. (There was once code here that + * never have occasion to read them in. (There was once code here that * claimed to read them, but it was broken as well as unused.) We * never read executor state trees, either. * @@ -28,7 +28,7 @@ /* * Macros to simplify reading of different kinds of fields. Use these - * wherever possible to reduce the chance for silly typos. Note that these + * wherever possible to reduce the chance for silly typos. Note that these * hard-wire conventions about the names of the local variables in a Read * routine. */ @@ -466,13 +466,14 @@ _readOpExpr(void) READ_OID_FIELD(opno); READ_OID_FIELD(opfuncid); + /* - * The opfuncid is stored in the textual format primarily for debugging - * and documentation reasons. We want to always read it as zero to force - * it to be re-looked-up in the pg_operator entry. This ensures that - * stored rules don't have hidden dependencies on operators' functions. - * (We don't currently support an ALTER OPERATOR command, but might - * someday.) + * The opfuncid is stored in the textual format primarily for + * debugging and documentation reasons. We want to always read it as + * zero to force it to be re-looked-up in the pg_operator entry. This + * ensures that stored rules don't have hidden dependencies on + * operators' functions. (We don't currently support an ALTER OPERATOR + * command, but might someday.) */ local_node->opfuncid = InvalidOid; @@ -493,13 +494,14 @@ _readDistinctExpr(void) READ_OID_FIELD(opno); READ_OID_FIELD(opfuncid); + /* - * The opfuncid is stored in the textual format primarily for debugging - * and documentation reasons. We want to always read it as zero to force - * it to be re-looked-up in the pg_operator entry. This ensures that - * stored rules don't have hidden dependencies on operators' functions. - * (We don't currently support an ALTER OPERATOR command, but might - * someday.) + * The opfuncid is stored in the textual format primarily for + * debugging and documentation reasons. We want to always read it as + * zero to force it to be re-looked-up in the pg_operator entry. This + * ensures that stored rules don't have hidden dependencies on + * operators' functions. (We don't currently support an ALTER OPERATOR + * command, but might someday.) */ local_node->opfuncid = InvalidOid; @@ -520,13 +522,14 @@ _readScalarArrayOpExpr(void) READ_OID_FIELD(opno); READ_OID_FIELD(opfuncid); + /* - * The opfuncid is stored in the textual format primarily for debugging - * and documentation reasons. We want to always read it as zero to force - * it to be re-looked-up in the pg_operator entry. This ensures that - * stored rules don't have hidden dependencies on operators' functions. - * (We don't currently support an ALTER OPERATOR command, but might - * someday.) + * The opfuncid is stored in the textual format primarily for + * debugging and documentation reasons. We want to always read it as + * zero to force it to be re-looked-up in the pg_operator entry. This + * ensures that stored rules don't have hidden dependencies on + * operators' functions. (We don't currently support an ALTER OPERATOR + * command, but might someday.) */ local_node->opfuncid = InvalidOid; @@ -685,13 +688,14 @@ _readNullIfExpr(void) READ_OID_FIELD(opno); READ_OID_FIELD(opfuncid); + /* - * The opfuncid is stored in the textual format primarily for debugging - * and documentation reasons. We want to always read it as zero to force - * it to be re-looked-up in the pg_operator entry. This ensures that - * stored rules don't have hidden dependencies on operators' functions. - * (We don't currently support an ALTER OPERATOR command, but might - * someday.) + * The opfuncid is stored in the textual format primarily for + * debugging and documentation reasons. We want to always read it as + * zero to force it to be re-looked-up in the pg_operator entry. This + * ensures that stored rules don't have hidden dependencies on + * operators' functions. (We don't currently support an ALTER OPERATOR + * command, but might someday.) */ local_node->opfuncid = InvalidOid; @@ -955,6 +959,7 @@ Node * parseNodeString(void) { void *return_value; + READ_TEMP_LOCALS(); token = pg_strtok(&length); diff --git a/src/backend/optimizer/geqo/geqo_eval.c b/src/backend/optimizer/geqo/geqo_eval.c index ee06560ca2..b1ff994f06 100644 --- a/src/backend/optimizer/geqo/geqo_eval.c +++ b/src/backend/optimizer/geqo/geqo_eval.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/optimizer/geqo/geqo_eval.c,v 1.63 2003/07/25 00:01:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/geqo/geqo_eval.c,v 1.64 2003/08/04 00:43:19 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -48,9 +48,9 @@ geqo_eval(Query *root, List *initial_rels, Gene *tour, int num_gene) /* * Because gimme_tree considers both left- and right-sided trees, * there is no difference between a tour (a,b,c,d,...) and a tour - * (b,a,c,d,...) --- the same join orders will be considered. - * To avoid redundant cost calculations, we simply reject tours where - * tour[0] > tour[1], assigning them an artificially bad fitness. + * (b,a,c,d,...) --- the same join orders will be considered. To avoid + * redundant cost calculations, we simply reject tours where tour[0] > + * tour[1], assigning them an artificially bad fitness. * * (It would be better to tweak the GEQO logic to not generate such tours * in the first place, but I'm not sure of all the implications in the @@ -65,8 +65,8 @@ geqo_eval(Query *root, List *initial_rels, Gene *tour, int num_gene) * * Since geqo_eval() will be called many times, we can't afford to let * all that memory go unreclaimed until end of statement. Note we - * make the temp context a child of the planner's normal context, so that - * it will be freed even if we abort via ereport(ERROR). + * make the temp context a child of the planner's normal context, so + * that it will be freed even if we abort via ereport(ERROR). */ mycontext = AllocSetContextCreate(CurrentMemoryContext, "GEQO", @@ -76,9 +76,9 @@ geqo_eval(Query *root, List *initial_rels, Gene *tour, int num_gene) oldcxt = MemoryContextSwitchTo(mycontext); /* - * preserve root->join_rel_list, which gimme_tree changes; without this, - * it'll be pointing at recycled storage after the MemoryContextDelete - * below. + * preserve root->join_rel_list, which gimme_tree changes; without + * this, it'll be pointing at recycled storage after the + * MemoryContextDelete below. */ savelist = root->join_rel_list; @@ -151,9 +151,10 @@ gimme_tree(Query *root, List *initial_rels, /* * Construct a RelOptInfo representing the previous joinrel joined - * to inner_rel. These are always inner joins. Note that we expect - * the joinrel not to exist in root->join_rel_list yet, and so the - * paths constructed for it will only include the ones we want. + * to inner_rel. These are always inner joins. Note that we + * expect the joinrel not to exist in root->join_rel_list yet, and + * so the paths constructed for it will only include the ones we + * want. */ new_rel = make_join_rel(root, joinrel, inner_rel, JOIN_INNER); diff --git a/src/backend/optimizer/geqo/geqo_main.c b/src/backend/optimizer/geqo/geqo_main.c index f60fd7d466..c91f16fd0e 100644 --- a/src/backend/optimizer/geqo/geqo_main.c +++ b/src/backend/optimizer/geqo/geqo_main.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/optimizer/geqo/geqo_main.c,v 1.36 2003/07/25 00:01:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/geqo/geqo_main.c,v 1.37 2003/08/04 00:43:19 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -229,8 +229,8 @@ geqo(Query *root, int number_of_rels, List *initial_rels) /* - * got the cheapest query tree processed by geqo; - * first element of the population indicates the best query tree + * got the cheapest query tree processed by geqo; first element of the + * population indicates the best query tree */ best_tour = (Gene *) pool->data[0].string; diff --git a/src/backend/optimizer/geqo/geqo_misc.c b/src/backend/optimizer/geqo/geqo_misc.c index acc9285d00..329e19c401 100644 --- a/src/backend/optimizer/geqo/geqo_misc.c +++ b/src/backend/optimizer/geqo/geqo_misc.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/optimizer/geqo/geqo_misc.c,v 1.37 2003/07/25 00:01:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/geqo/geqo_misc.c,v 1.38 2003/08/04 00:43:19 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -42,7 +42,7 @@ avg_pool(Pool *pool) /* * Since the pool may contain multiple occurrences of DBL_MAX, divide - * by pool->size before summing, not after, to avoid overflow. This + * by pool->size before summing, not after, to avoid overflow. This * loses a little in speed and accuracy, but this routine is only used * for debug printouts, so we don't care that much. */ diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 486dede0fb..494f624d4c 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/allpaths.c,v 1.104 2003/07/25 00:01:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/allpaths.c,v 1.105 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -50,13 +50,13 @@ static void set_function_pathlist(Query *root, RelOptInfo *rel, static RelOptInfo *make_one_rel_by_joins(Query *root, int levels_needed, List *initial_rels); static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, - bool *differentTypes); + bool *differentTypes); static bool recurse_pushdown_safe(Node *setOp, Query *topquery, - bool *differentTypes); + bool *differentTypes); static void compare_tlist_datatypes(List *tlist, List *colTypes, - bool *differentTypes); + bool *differentTypes); static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual, - bool *differentTypes); + bool *differentTypes); static void subquery_push_qual(Query *subquery, Index rti, Node *qual); static void recurse_push_qual(Node *setOp, Query *topquery, Index rti, Node *qual); @@ -290,14 +290,14 @@ set_inherited_rel_pathlist(Query *root, RelOptInfo *rel, rel->rows += childrel->rows; if (childrel->width > rel->width) rel->width = childrel->width; - + childvars = FastListValue(&childrel->reltargetlist); foreach(parentvars, FastListValue(&rel->reltargetlist)) { - Var *parentvar = (Var *) lfirst(parentvars); - Var *childvar = (Var *) lfirst(childvars); - int parentndx = parentvar->varattno - rel->min_attr; - int childndx = childvar->varattno - childrel->min_attr; + Var *parentvar = (Var *) lfirst(parentvars); + Var *childvar = (Var *) lfirst(childvars); + int parentndx = parentvar->varattno - rel->min_attr; + int childndx = childvar->varattno - childrel->min_attr; if (childrel->attr_widths[childndx] > rel->attr_widths[parentndx]) rel->attr_widths[parentndx] = childrel->attr_widths[childndx]; @@ -343,8 +343,8 @@ set_subquery_pathlist(Query *root, RelOptInfo *rel, * * There are several cases where we cannot push down clauses. * Restrictions involving the subquery are checked by - * subquery_is_pushdown_safe(). Restrictions on individual clauses are - * checked by qual_is_pushdown_safe(). + * subquery_is_pushdown_safe(). Restrictions on individual clauses + * are checked by qual_is_pushdown_safe(). * * Non-pushed-down clauses will get evaluated as qpquals of the * SubqueryScan node. @@ -725,15 +725,16 @@ qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual, vars = pull_var_clause(qual, false); foreach(vl, vars) { - Var *var = (Var *) lfirst(vl); + Var *var = (Var *) lfirst(vl); List *tl; TargetEntry *tle = NULL; Assert(var->varno == rti); + /* * We use a bitmapset to avoid testing the same attno more than - * once. (NB: this only works because subquery outputs can't - * have negative attnos.) + * once. (NB: this only works because subquery outputs can't have + * negative attnos.) */ if (bms_is_member(var->varattno, tested)) continue; diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c index e1754a7a69..1a0e2da82f 100644 --- a/src/backend/optimizer/path/costsize.c +++ b/src/backend/optimizer/path/costsize.c @@ -49,7 +49,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.111 2003/07/25 00:01:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.112 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -102,10 +102,10 @@ bool enable_hashjoin = true; static Selectivity estimate_hash_bucketsize(Query *root, Var *var, - int nbuckets); -static bool cost_qual_eval_walker(Node *node, QualCost *total); + int nbuckets); +static bool cost_qual_eval_walker(Node *node, QualCost * total); static Selectivity approx_selectivity(Query *root, List *quals, - JoinType jointype); + JoinType jointype); static void set_rel_width(Query *root, RelOptInfo *rel); static double relation_byte_size(double tuples, int width); static double page_size(double tuples, int width); @@ -358,13 +358,13 @@ cost_index(Path *path, Query *root, * Normally the indexquals will be removed from the list of restriction * clauses that we have to evaluate as qpquals, so we should subtract * their costs from baserestrictcost. But if we are doing a join then - * some of the indexquals are join clauses and shouldn't be subtracted. - * Rather than work out exactly how much to subtract, we don't subtract - * anything. + * some of the indexquals are join clauses and shouldn't be + * subtracted. Rather than work out exactly how much to subtract, we + * don't subtract anything. * * XXX For a lossy index, not all the quals will be removed and so we - * really shouldn't subtract their costs; but detecting that seems more - * expensive than it's worth. + * really shouldn't subtract their costs; but detecting that seems + * more expensive than it's worth. */ startup_cost += baserel->baserestrictcost.startup; cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple; @@ -433,8 +433,8 @@ cost_subqueryscan(Path *path, RelOptInfo *baserel) /* * Cost of path is cost of evaluating the subplan, plus cost of * evaluating any restriction clauses that will be attached to the - * SubqueryScan node, plus cpu_tuple_cost to account for selection - * and projection overhead. + * SubqueryScan node, plus cpu_tuple_cost to account for selection and + * projection overhead. */ path->startup_cost = baserel->subplan->startup_cost; path->total_cost = baserel->subplan->total_cost; @@ -597,8 +597,9 @@ cost_material(Path *path, } /* - * Also charge a small amount per extracted tuple. We use cpu_tuple_cost - * so that it doesn't appear worthwhile to materialize a bare seqscan. + * Also charge a small amount per extracted tuple. We use + * cpu_tuple_cost so that it doesn't appear worthwhile to materialize + * a bare seqscan. */ run_cost += cpu_tuple_cost * tuples; @@ -631,17 +632,17 @@ cost_agg(Path *path, Query *root, * additional cpu_operator_cost per grouping column per input tuple * for grouping comparisons. * - * We will produce a single output tuple if not grouping, - * and a tuple per group otherwise. + * We will produce a single output tuple if not grouping, and a tuple per + * group otherwise. * * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the - * same total CPU cost, but AGG_SORTED has lower startup cost. If the + * same total CPU cost, but AGG_SORTED has lower startup cost. If the * input path is already sorted appropriately, AGG_SORTED should be - * preferred (since it has no risk of memory overflow). This will happen - * as long as the computed total costs are indeed exactly equal --- but - * if there's roundoff error we might do the wrong thing. So be sure - * that the computations below form the same intermediate values in the - * same order. + * preferred (since it has no risk of memory overflow). This will + * happen as long as the computed total costs are indeed exactly equal + * --- but if there's roundoff error we might do the wrong thing. So + * be sure that the computations below form the same intermediate + * values in the same order. */ if (aggstrategy == AGG_PLAIN) { @@ -724,26 +725,26 @@ cost_nestloop(NestPath *path, Query *root) double outer_path_rows = PATH_ROWS(outer_path); double inner_path_rows = PATH_ROWS(inner_path); double ntuples; - Selectivity joininfactor; + Selectivity joininfactor; if (!enable_nestloop) startup_cost += disable_cost; /* - * If we're doing JOIN_IN then we will stop scanning inner tuples for an - * outer tuple as soon as we have one match. Account for the effects of - * this by scaling down the cost estimates in proportion to the expected - * output size. (This assumes that all the quals attached to the join are - * IN quals, which should be true.) + * If we're doing JOIN_IN then we will stop scanning inner tuples for + * an outer tuple as soon as we have one match. Account for the + * effects of this by scaling down the cost estimates in proportion to + * the expected output size. (This assumes that all the quals + * attached to the join are IN quals, which should be true.) * * Note: it's probably bogus to use the normal selectivity calculation * here when either the outer or inner path is a UniquePath. */ if (path->jointype == JOIN_IN) { - Selectivity qual_selec = approx_selectivity(root, restrictlist, + Selectivity qual_selec = approx_selectivity(root, restrictlist, path->jointype); - double qptuples; + double qptuples; qptuples = ceil(qual_selec * outer_path_rows * inner_path_rows); if (qptuples > path->path.parent->rows) @@ -761,8 +762,8 @@ cost_nestloop(NestPath *path, Query *root) * before we can start returning tuples, so the join's startup cost is * their sum. What's not so clear is whether the inner path's * startup_cost must be paid again on each rescan of the inner path. - * This is not true if the inner path is materialized or is a hashjoin, - * but probably is true otherwise. + * This is not true if the inner path is materialized or is a + * hashjoin, but probably is true otherwise. */ startup_cost += outer_path->startup_cost + inner_path->startup_cost; run_cost += outer_path->total_cost - outer_path->startup_cost; @@ -783,14 +784,15 @@ cost_nestloop(NestPath *path, Query *root) (inner_path->total_cost - inner_path->startup_cost) * joininfactor; /* - * Compute number of tuples processed (not number emitted!). - * If inner path is an indexscan, be sure to use its estimated output row - * count, which may be lower than the restriction-clause-only row count of - * its parent. (We don't include this case in the PATH_ROWS macro because - * it applies *only* to a nestloop's inner relation.) Note: it is correct - * to use the unadjusted inner_path_rows in the above calculation for - * joininfactor, since otherwise we'd be double-counting the selectivity - * of the join clause being used for the index. + * Compute number of tuples processed (not number emitted!). If inner + * path is an indexscan, be sure to use its estimated output row + * count, which may be lower than the restriction-clause-only row + * count of its parent. (We don't include this case in the PATH_ROWS + * macro because it applies *only* to a nestloop's inner relation.) + * Note: it is correct to use the unadjusted inner_path_rows in the + * above calculation for joininfactor, since otherwise we'd be + * double-counting the selectivity of the join clause being used for + * the index. */ if (IsA(inner_path, IndexPath)) inner_path_rows = ((IndexPath *) inner_path)->rows; @@ -831,8 +833,8 @@ cost_mergejoin(MergePath *path, Query *root) Cost startup_cost = 0; Cost run_cost = 0; Cost cpu_per_tuple; - Selectivity merge_selec; - Selectivity qp_selec; + Selectivity merge_selec; + Selectivity qp_selec; QualCost merge_qual_cost; QualCost qp_qual_cost; RestrictInfo *firstclause; @@ -847,7 +849,7 @@ cost_mergejoin(MergePath *path, Query *root) double rescanratio; Selectivity outerscansel, innerscansel; - Selectivity joininfactor; + Selectivity joininfactor; Path sort_path; /* dummy for result of cost_sort */ if (!enable_mergejoin) @@ -856,7 +858,8 @@ cost_mergejoin(MergePath *path, Query *root) /* * Compute cost and selectivity of the mergequals and qpquals (other * restriction clauses) separately. We use approx_selectivity here - * for speed --- in most cases, any errors won't affect the result much. + * for speed --- in most cases, any errors won't affect the result + * much. * * Note: it's probably bogus to use the normal selectivity calculation * here when either the outer or inner path is a UniquePath. @@ -876,29 +879,30 @@ cost_mergejoin(MergePath *path, Query *root) qptuples = ceil(mergejointuples * qp_selec); /* - * When there are equal merge keys in the outer relation, the mergejoin - * must rescan any matching tuples in the inner relation. This means - * re-fetching inner tuples. Our cost model for this is that a re-fetch - * costs the same as an original fetch, which is probably an overestimate; - * but on the other hand we ignore the bookkeeping costs of mark/restore. - * Not clear if it's worth developing a more refined model. + * When there are equal merge keys in the outer relation, the + * mergejoin must rescan any matching tuples in the inner relation. + * This means re-fetching inner tuples. Our cost model for this is + * that a re-fetch costs the same as an original fetch, which is + * probably an overestimate; but on the other hand we ignore the + * bookkeeping costs of mark/restore. Not clear if it's worth + * developing a more refined model. * * The number of re-fetches can be estimated approximately as size of - * merge join output minus size of inner relation. Assume that the - * distinct key values are 1, 2, ..., and denote the number of values of - * each key in the outer relation as m1, m2, ...; in the inner relation, - * n1, n2, ... Then we have + * merge join output minus size of inner relation. Assume that the + * distinct key values are 1, 2, ..., and denote the number of values + * of each key in the outer relation as m1, m2, ...; in the inner + * relation, n1, n2, ... Then we have * - * size of join = m1 * n1 + m2 * n2 + ... + * size of join = m1 * n1 + m2 * n2 + ... * - * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... - * = m1 * n1 + m2 * n2 + ... - (n1 + n2 + ...) - * = size of join - size of inner relation + * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 * + * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner + * relation * * This equation works correctly for outer tuples having no inner match * (nk = 0), but not for inner tuples having no outer match (mk = 0); * we are effectively subtracting those from the number of rescanned - * tuples, when we should not. Can we do better without expensive + * tuples, when we should not. Can we do better without expensive * selectivity computations? */ if (IsA(outer_path, UniquePath)) @@ -953,8 +957,9 @@ cost_mergejoin(MergePath *path, Query *root) /* * Readjust scan selectivities to account for above rounding. This is - * normally an insignificant effect, but when there are only a few rows - * in the inputs, failing to do this makes for a large percentage error. + * normally an insignificant effect, but when there are only a few + * rows in the inputs, failing to do this makes for a large percentage + * error. */ outerscansel = outer_rows / outer_path_rows; innerscansel = inner_rows / inner_path_rows; @@ -1002,11 +1007,11 @@ cost_mergejoin(MergePath *path, Query *root) /* CPU costs */ /* - * If we're doing JOIN_IN then we will stop outputting inner - * tuples for an outer tuple as soon as we have one match. Account for - * the effects of this by scaling down the cost estimates in proportion - * to the expected output size. (This assumes that all the quals attached - * to the join are IN quals, which should be true.) + * If we're doing JOIN_IN then we will stop outputting inner tuples + * for an outer tuple as soon as we have one match. Account for the + * effects of this by scaling down the cost estimates in proportion to + * the expected output size. (This assumes that all the quals + * attached to the join are IN quals, which should be true.) */ if (path->jpath.jointype == JOIN_IN && qptuples > path->jpath.path.parent->rows) @@ -1017,9 +1022,9 @@ cost_mergejoin(MergePath *path, Query *root) /* * The number of tuple comparisons needed is approximately number of * outer rows plus number of inner rows plus number of rescanned - * tuples (can we refine this?). At each one, we need to evaluate - * the mergejoin quals. NOTE: JOIN_IN mode does not save any work - * here, so do NOT include joininfactor. + * tuples (can we refine this?). At each one, we need to evaluate the + * mergejoin quals. NOTE: JOIN_IN mode does not save any work here, + * so do NOT include joininfactor. */ startup_cost += merge_qual_cost.startup; run_cost += merge_qual_cost.per_tuple * @@ -1028,7 +1033,7 @@ cost_mergejoin(MergePath *path, Query *root) /* * For each tuple that gets through the mergejoin proper, we charge * cpu_tuple_cost plus the cost of evaluating additional restriction - * clauses that are to be applied at the join. (This is pessimistic + * clauses that are to be applied at the join. (This is pessimistic * since not all of the quals may get evaluated at each tuple.) This * work is skipped in JOIN_IN mode, so apply the factor. */ @@ -1059,8 +1064,8 @@ cost_hashjoin(HashPath *path, Query *root) Cost startup_cost = 0; Cost run_cost = 0; Cost cpu_per_tuple; - Selectivity hash_selec; - Selectivity qp_selec; + Selectivity hash_selec; + Selectivity qp_selec; QualCost hash_qual_cost; QualCost qp_qual_cost; double hashjointuples; @@ -1076,7 +1081,7 @@ cost_hashjoin(HashPath *path, Query *root) int physicalbuckets; int numbatches; Selectivity innerbucketsize; - Selectivity joininfactor; + Selectivity joininfactor; List *hcl; List *qpquals; @@ -1086,7 +1091,8 @@ cost_hashjoin(HashPath *path, Query *root) /* * Compute cost and selectivity of the hashquals and qpquals (other * restriction clauses) separately. We use approx_selectivity here - * for speed --- in most cases, any errors won't affect the result much. + * for speed --- in most cases, any errors won't affect the result + * much. * * Note: it's probably bogus to use the normal selectivity calculation * here when either the outer or inner path is a UniquePath. @@ -1114,9 +1120,9 @@ cost_hashjoin(HashPath *path, Query *root) * Cost of computing hash function: must do it once per input tuple. * We charge one cpu_operator_cost for each column's hash function. * - * XXX when a hashclause is more complex than a single operator, - * we really should charge the extra eval costs of the left or right - * side, as appropriate, here. This seems more work than it's worth + * XXX when a hashclause is more complex than a single operator, we + * really should charge the extra eval costs of the left or right + * side, as appropriate, here. This seems more work than it's worth * at the moment. */ startup_cost += cpu_operator_cost * num_hashclauses * inner_path_rows; @@ -1131,13 +1137,13 @@ cost_hashjoin(HashPath *path, Query *root) /* * Determine bucketsize fraction for inner relation. We use the - * smallest bucketsize estimated for any individual hashclause; - * this is undoubtedly conservative. + * smallest bucketsize estimated for any individual hashclause; this + * is undoubtedly conservative. * - * BUT: if inner relation has been unique-ified, we can assume it's - * good for hashing. This is important both because it's the right - * answer, and because we avoid contaminating the cache with a value - * that's wrong for non-unique-ified paths. + * BUT: if inner relation has been unique-ified, we can assume it's good + * for hashing. This is important both because it's the right answer, + * and because we avoid contaminating the cache with a value that's + * wrong for non-unique-ified paths. */ if (IsA(inner_path, UniquePath)) innerbucketsize = 1.0 / virtualbuckets; @@ -1152,12 +1158,13 @@ cost_hashjoin(HashPath *path, Query *root) Assert(IsA(restrictinfo, RestrictInfo)); /* - * First we have to figure out which side of the hashjoin clause - * is the inner side. + * First we have to figure out which side of the hashjoin + * clause is the inner side. * * Since we tend to visit the same clauses over and over when - * planning a large query, we cache the bucketsize estimate in the - * RestrictInfo node to avoid repeated lookups of statistics. + * planning a large query, we cache the bucketsize estimate in + * the RestrictInfo node to avoid repeated lookups of + * statistics. */ if (bms_is_subset(restrictinfo->right_relids, inner_path->parent->relids)) @@ -1169,7 +1176,7 @@ cost_hashjoin(HashPath *path, Query *root) /* not cached yet */ thisbucketsize = estimate_hash_bucketsize(root, - (Var *) get_rightop(restrictinfo->clause), + (Var *) get_rightop(restrictinfo->clause), virtualbuckets); restrictinfo->right_bucketsize = thisbucketsize; } @@ -1185,7 +1192,7 @@ cost_hashjoin(HashPath *path, Query *root) /* not cached yet */ thisbucketsize = estimate_hash_bucketsize(root, - (Var *) get_leftop(restrictinfo->clause), + (Var *) get_leftop(restrictinfo->clause), virtualbuckets); restrictinfo->left_bucketsize = thisbucketsize; } @@ -1217,11 +1224,11 @@ cost_hashjoin(HashPath *path, Query *root) /* CPU costs */ /* - * If we're doing JOIN_IN then we will stop comparing inner - * tuples to an outer tuple as soon as we have one match. Account for - * the effects of this by scaling down the cost estimates in proportion - * to the expected output size. (This assumes that all the quals attached - * to the join are IN quals, which should be true.) + * If we're doing JOIN_IN then we will stop comparing inner tuples to + * an outer tuple as soon as we have one match. Account for the + * effects of this by scaling down the cost estimates in proportion to + * the expected output size. (This assumes that all the quals + * attached to the join are IN quals, which should be true.) */ if (path->jpath.jointype == JOIN_IN && qptuples > path->jpath.path.parent->rows) @@ -1243,7 +1250,7 @@ cost_hashjoin(HashPath *path, Query *root) /* * For each tuple that gets through the hashjoin proper, we charge * cpu_tuple_cost plus the cost of evaluating additional restriction - * clauses that are to be applied at the join. (This is pessimistic + * clauses that are to be applied at the join. (This is pessimistic * since not all of the quals may get evaluated at each tuple.) */ startup_cost += qp_qual_cost.startup; @@ -1254,14 +1261,14 @@ cost_hashjoin(HashPath *path, Query *root) * Bias against putting larger relation on inside. We don't want an * absolute prohibition, though, since larger relation might have * better bucketsize --- and we can't trust the size estimates - * unreservedly, anyway. Instead, inflate the run cost by the - * square root of the size ratio. (Why square root? No real good - * reason, but it seems reasonable...) + * unreservedly, anyway. Instead, inflate the run cost by the square + * root of the size ratio. (Why square root? No real good reason, + * but it seems reasonable...) * - * Note: before 7.4 we implemented this by inflating startup cost; - * but if there's a disable_cost component in the input paths' - * startup cost, that unfairly penalizes the hash. Probably it'd - * be better to keep track of disable penalty separately from cost. + * Note: before 7.4 we implemented this by inflating startup cost; but if + * there's a disable_cost component in the input paths' startup cost, + * that unfairly penalizes the hash. Probably it'd be better to keep + * track of disable penalty separately from cost. */ if (innerbytes > outerbytes && outerbytes > 0) run_cost *= sqrt(innerbytes / outerbytes); @@ -1442,7 +1449,7 @@ estimate_hash_bucketsize(Query *root, Var *var, int nbuckets) * and a per-evaluation component. */ void -cost_qual_eval(QualCost *cost, List *quals) +cost_qual_eval(QualCost * cost, List *quals) { List *l; @@ -1484,7 +1491,7 @@ cost_qual_eval(QualCost *cost, List *quals) } static bool -cost_qual_eval_walker(Node *node, QualCost *total) +cost_qual_eval_walker(Node *node, QualCost * total) { if (node == NULL) return false; @@ -1502,9 +1509,7 @@ cost_qual_eval_walker(Node *node, QualCost *total) IsA(node, OpExpr) || IsA(node, DistinctExpr) || IsA(node, NullIfExpr)) - { total->per_tuple += cpu_operator_cost; - } else if (IsA(node, ScalarArrayOpExpr)) { /* should charge more than 1 op cost, but how many? */ @@ -1519,47 +1524,48 @@ cost_qual_eval_walker(Node *node, QualCost *total) { /* * A subplan node in an expression typically indicates that the - * subplan will be executed on each evaluation, so charge accordingly. - * (Sub-selects that can be executed as InitPlans have already been - * removed from the expression.) + * subplan will be executed on each evaluation, so charge + * accordingly. (Sub-selects that can be executed as InitPlans + * have already been removed from the expression.) * * An exception occurs when we have decided we can implement the * subplan by hashing. * */ - SubPlan *subplan = (SubPlan *) node; + SubPlan *subplan = (SubPlan *) node; Plan *plan = subplan->plan; if (subplan->useHashTable) { /* * If we are using a hash table for the subquery outputs, then - * the cost of evaluating the query is a one-time cost. - * We charge one cpu_operator_cost per tuple for the work of + * the cost of evaluating the query is a one-time cost. We + * charge one cpu_operator_cost per tuple for the work of * loading the hashtable, too. */ total->startup += plan->total_cost + cpu_operator_cost * plan->plan_rows; + /* * The per-tuple costs include the cost of evaluating the - * lefthand expressions, plus the cost of probing the hashtable. - * Recursion into the exprs list will handle the lefthand - * expressions properly, and will count one cpu_operator_cost - * for each comparison operator. That is probably too low for - * the probing cost, but it's hard to make a better estimate, - * so live with it for now. + * lefthand expressions, plus the cost of probing the + * hashtable. Recursion into the exprs list will handle the + * lefthand expressions properly, and will count one + * cpu_operator_cost for each comparison operator. That is + * probably too low for the probing cost, but it's hard to + * make a better estimate, so live with it for now. */ } else { /* * Otherwise we will be rescanning the subplan output on each - * evaluation. We need to estimate how much of the output - * we will actually need to scan. NOTE: this logic should - * agree with the estimates used by make_subplan() in + * evaluation. We need to estimate how much of the output we + * will actually need to scan. NOTE: this logic should agree + * with the estimates used by make_subplan() in * plan/subselect.c. */ - Cost plan_run_cost = plan->total_cost - plan->startup_cost; + Cost plan_run_cost = plan->total_cost - plan->startup_cost; if (subplan->subLinkType == EXISTS_SUBLINK) { @@ -1579,23 +1585,20 @@ cost_qual_eval_walker(Node *node, QualCost *total) /* assume we need all tuples */ total->per_tuple += plan_run_cost; } + /* - * Also account for subplan's startup cost. - * If the subplan is uncorrelated or undirect correlated, - * AND its topmost node is a Sort or Material node, assume - * that we'll only need to pay its startup cost once; - * otherwise assume we pay the startup cost every time. + * Also account for subplan's startup cost. If the subplan is + * uncorrelated or undirect correlated, AND its topmost node + * is a Sort or Material node, assume that we'll only need to + * pay its startup cost once; otherwise assume we pay the + * startup cost every time. */ if (subplan->parParam == NIL && (IsA(plan, Sort) || IsA(plan, Material))) - { total->startup += plan->startup_cost; - } else - { total->per_tuple += plan->startup_cost; - } } } @@ -1745,7 +1748,7 @@ set_joinrel_size_estimates(Query *root, RelOptInfo *rel, UniquePath *upath; /* - * Compute joinclause selectivity. Note that we are only considering + * Compute joinclause selectivity. Note that we are only considering * clauses that become restriction clauses at this join level; we are * not double-counting them because they were not considered in * estimating the sizes of the component rels. @@ -1758,8 +1761,8 @@ set_joinrel_size_estimates(Query *root, RelOptInfo *rel, /* * Basically, we multiply size of Cartesian product by selectivity. * - * If we are doing an outer join, take that into account: the output - * must be at least as large as the non-nullable input. (Is there any + * If we are doing an outer join, take that into account: the output must + * be at least as large as the non-nullable input. (Is there any * chance of being even smarter?) * * For JOIN_IN and variants, the Cartesian product is figured with @@ -1823,8 +1826,8 @@ set_joinrel_size_estimates(Query *root, RelOptInfo *rel, rel->rows = temp; /* - * We need not compute the output width here, because build_joinrel_tlist - * already did. + * We need not compute the output width here, because + * build_joinrel_tlist already did. */ } @@ -1911,11 +1914,14 @@ set_rel_width(Query *root, RelOptInfo *rel) Assert(IsA(var, Var)); - /* The width probably hasn't been cached yet, but may as well check */ + /* + * The width probably hasn't been cached yet, but may as well + * check + */ if (rel->attr_widths[ndx] > 0) { - tuple_width += rel->attr_widths[ndx]; - continue; + tuple_width += rel->attr_widths[ndx]; + continue; } relid = getrelid(var->varno, root->rtable); @@ -1931,8 +1937,8 @@ set_rel_width(Query *root, RelOptInfo *rel) } /* - * Not a plain relation, or can't find statistics for it. - * Estimate using just the type info. + * Not a plain relation, or can't find statistics for it. Estimate + * using just the type info. */ item_width = get_typavgwidth(var->vartype, var->vartypmod); Assert(item_width > 0); diff --git a/src/backend/optimizer/path/indxpath.c b/src/backend/optimizer/path/indxpath.c index fa19abe471..67238b5361 100644 --- a/src/backend/optimizer/path/indxpath.c +++ b/src/backend/optimizer/path/indxpath.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/indxpath.c,v 1.145 2003/07/25 00:01:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/indxpath.c,v 1.146 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -64,9 +64,9 @@ static List *group_clauses_by_indexkey_for_join(Query *root, Relids outer_relids, JoinType jointype, bool isouterjoin); static bool match_clause_to_indexcol(RelOptInfo *rel, IndexOptInfo *index, - int indexcol, Oid opclass, Expr *clause); -static bool match_join_clause_to_indexcol(RelOptInfo *rel, IndexOptInfo *index, int indexcol, Oid opclass, Expr *clause); +static bool match_join_clause_to_indexcol(RelOptInfo *rel, IndexOptInfo *index, + int indexcol, Oid opclass, Expr *clause); static Oid indexable_operator(Expr *clause, Oid opclass, bool indexkey_on_left); static bool pred_test(List *predicate_list, List *restrictinfo_list, @@ -77,8 +77,8 @@ static bool pred_test_recurse_pred(Expr *predicate, Node *clause); static bool pred_test_simple_clause(Expr *predicate, Node *clause); static Relids indexable_outerrelids(RelOptInfo *rel, IndexOptInfo *index); static Path *make_innerjoin_index_path(Query *root, - RelOptInfo *rel, IndexOptInfo *index, - List *clausegroups); + RelOptInfo *rel, IndexOptInfo *index, + List *clausegroups); static bool match_index_to_operand(Node *operand, int indexcol, RelOptInfo *rel, IndexOptInfo *index); static bool match_special_index_operator(Expr *clause, Oid opclass, @@ -87,7 +87,7 @@ static List *expand_indexqual_condition(Expr *clause, Oid opclass); static List *prefix_quals(Node *leftop, Oid opclass, Const *prefix, Pattern_Prefix_Status pstatus); static List *network_prefix_quals(Node *leftop, Oid expr_op, Oid opclass, - Datum rightop); + Datum rightop); static Datum string_to_datum(const char *str, Oid datatype); static Const *string_to_const(const char *str, Oid datatype); @@ -114,7 +114,7 @@ static Const *string_to_const(const char *str, Oid datatype); * scan this routine deems potentially interesting for the current query. * * We also determine the set of other relids that participate in join - * clauses that could be used with each index. The actually best innerjoin + * clauses that could be used with each index. The actually best innerjoin * path will be generated for each outer relation later on, but knowing the * set of potential otherrels allows us to identify equivalent outer relations * and avoid repeated computation. @@ -219,10 +219,11 @@ create_index_paths(Query *root, RelOptInfo *rel) /* * 6. Examine join clauses to see which ones are potentially - * usable with this index, and generate the set of all other relids - * that participate in such join clauses. We'll use this set later - * to recognize outer rels that are equivalent for joining purposes. - * We compute both per-index and overall-for-relation sets. + * usable with this index, and generate the set of all other + * relids that participate in such join clauses. We'll use this + * set later to recognize outer rels that are equivalent for + * joining purposes. We compute both per-index and + * overall-for-relation sets. */ join_outerrelids = indexable_outerrelids(rel, index); index->outer_relids = join_outerrelids; @@ -274,7 +275,7 @@ match_index_orclauses(RelOptInfo *rel, */ restrictinfo->subclauseindices = match_index_orclause(rel, index, - ((BoolExpr *) restrictinfo->clause)->args, + ((BoolExpr *) restrictinfo->clause)->args, restrictinfo->subclauseindices); } } @@ -422,6 +423,7 @@ extract_or_indexqual_conditions(RelOptInfo *rel, Oid *classes = index->classlist; FastListInit(&quals); + /* * Extract relevant indexclauses in indexkey order. This is * essentially just like group_clauses_by_indexkey() except that the @@ -576,7 +578,7 @@ group_clauses_by_indexkey(RelOptInfo *rel, IndexOptInfo *index) * * This is much like group_clauses_by_indexkey(), but we consider both * join and restriction clauses. Any joinclause that uses only otherrels - * in the specified outer_relids is fair game. But there must be at least + * in the specified outer_relids is fair game. But there must be at least * one such joinclause in the final list, otherwise we return NIL indicating * that this index isn't interesting as an inner indexscan. (A scan using * only restriction clauses shouldn't be created here, because a regular Path @@ -641,10 +643,10 @@ group_clauses_by_indexkey_for_join(Query *root, */ if (FastListValue(&clausegroup) != NIL) { - List *nl; + List *nl; nl = remove_redundant_join_clauses(root, - FastListValue(&clausegroup), + FastListValue(&clausegroup), jointype); FastListFromList(&clausegroup, nl); } @@ -736,9 +738,9 @@ match_clause_to_indexcol(RelOptInfo *rel, return false; /* - * Check for clauses of the form: - * (indexkey operator constant) or (constant operator indexkey). - * Anything that is a "pseudo constant" expression will do. + * Check for clauses of the form: (indexkey operator constant) or + * (constant operator indexkey). Anything that is a "pseudo constant" + * expression will do. */ if (match_index_to_operand(leftop, indexcol, rel, index) && is_pseudo_constant_clause(rightop)) @@ -747,8 +749,8 @@ match_clause_to_indexcol(RelOptInfo *rel, return true; /* - * If we didn't find a member of the index's opclass, see - * whether it is a "special" indexable operator. + * If we didn't find a member of the index's opclass, see whether + * it is a "special" indexable operator. */ if (match_special_index_operator(clause, opclass, true)) return true; @@ -762,8 +764,8 @@ match_clause_to_indexcol(RelOptInfo *rel, return true; /* - * If we didn't find a member of the index's opclass, see - * whether it is a "special" indexable operator. + * If we didn't find a member of the index's opclass, see whether + * it is a "special" indexable operator. */ if (match_special_index_operator(clause, opclass, false)) return true; @@ -824,10 +826,10 @@ match_join_clause_to_indexcol(RelOptInfo *rel, return false; /* - * Check for an indexqual that could be handled by a nestloop - * join. We need the index key to be compared against an - * expression that uses none of the indexed relation's vars and - * contains no volatile functions. + * Check for an indexqual that could be handled by a nestloop join. We + * need the index key to be compared against an expression that uses + * none of the indexed relation's vars and contains no volatile + * functions. */ if (match_index_to_operand(leftop, indexcol, rel, index)) { @@ -1174,10 +1176,11 @@ pred_test_simple_clause(Expr *predicate, Node *clause) * 1. Find "btree" strategy numbers for the pred_op and clause_op. * * We must find a btree opclass that contains both operators, else the - * implication can't be determined. If there are multiple such opclasses, - * assume we can use any one to determine the logical relationship of the - * two operators and the correct corresponding test operator. This should - * work for any logically consistent opclasses. + * implication can't be determined. If there are multiple such + * opclasses, assume we can use any one to determine the logical + * relationship of the two operators and the correct corresponding + * test operator. This should work for any logically consistent + * opclasses. */ catlist = SearchSysCacheList(AMOPOPID, 1, ObjectIdGetDatum(pred_op), @@ -1269,7 +1272,7 @@ pred_test_simple_clause(Expr *predicate, Node *clause) /* And execute it. */ test_result = ExecEvalExprSwitchContext(test_exprstate, - GetPerTupleExprContext(estate), + GetPerTupleExprContext(estate), &isNull, NULL); /* Get back to outer memory context */ @@ -1295,7 +1298,7 @@ pred_test_simple_clause(Expr *predicate, Node *clause) /* * indexable_outerrelids * Finds all other relids that participate in any indexable join clause - * for the specified index. Returns a set of relids. + * for the specified index. Returns a set of relids. * * 'rel' is the relation for which 'index' is defined */ @@ -1314,16 +1317,16 @@ indexable_outerrelids(RelOptInfo *rel, IndexOptInfo *index) /* * Examine each joinclause in the JoinInfo node's list to see if * it matches any key of the index. If so, add the JoinInfo's - * otherrels to the result. We can skip examining other joinclauses - * in the same list as soon as we find a match (since by definition - * they all have the same otherrels). + * otherrels to the result. We can skip examining other + * joinclauses in the same list as soon as we find a match (since + * by definition they all have the same otherrels). */ foreach(j, joininfo->jinfo_restrictinfo) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(j); - Expr *clause = rinfo->clause; - int indexcol = 0; - Oid *classes = index->classlist; + Expr *clause = rinfo->clause; + int indexcol = 0; + Oid *classes = index->classlist; do { @@ -1398,11 +1401,13 @@ best_inner_indexscan(Query *root, RelOptInfo *rel, default: return NULL; } + /* * If there are no indexable joinclauses for this rel, exit quickly. */ if (bms_is_empty(rel->index_outer_relids)) return NULL; + /* * Otherwise, we have to do path selection in the memory context of * the given rel, so that any created path can be safely attached to @@ -1410,10 +1415,11 @@ best_inner_indexscan(Query *root, RelOptInfo *rel, * issue for normal planning, but it is an issue for GEQO planning.) */ oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel)); + /* - * Intersect the given outer_relids with index_outer_relids - * to find the set of outer relids actually relevant for this index. - * If there are none, again we can fail immediately. + * Intersect the given outer_relids with index_outer_relids to find + * the set of outer relids actually relevant for this index. If there + * are none, again we can fail immediately. */ outer_relids = bms_intersect(rel->index_outer_relids, outer_relids); if (bms_is_empty(outer_relids)) @@ -1422,11 +1428,13 @@ best_inner_indexscan(Query *root, RelOptInfo *rel, MemoryContextSwitchTo(oldcontext); return NULL; } + /* * Look to see if we already computed the result for this set of - * relevant outerrels. (We include the isouterjoin status in the + * relevant outerrels. (We include the isouterjoin status in the * cache lookup key for safety. In practice I suspect this is not - * necessary because it should always be the same for a given innerrel.) + * necessary because it should always be the same for a given + * innerrel.) */ foreach(jlist, rel->index_inner_paths) { @@ -1441,15 +1449,15 @@ best_inner_indexscan(Query *root, RelOptInfo *rel, } /* - * For each index of the rel, find the best path; then choose the - * best overall. We cache the per-index results as well as the overall - * result. (This is useful because different indexes may have different - * relevant outerrel sets, so different overall outerrel sets might still - * map to the same computation for a given index.) + * For each index of the rel, find the best path; then choose the best + * overall. We cache the per-index results as well as the overall + * result. (This is useful because different indexes may have + * different relevant outerrel sets, so different overall outerrel + * sets might still map to the same computation for a given index.) */ foreach(ilist, rel->indexlist) { - IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist); + IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist); Relids index_outer_relids; Path *path = NULL; @@ -1461,6 +1469,7 @@ best_inner_indexscan(Query *root, RelOptInfo *rel, bms_free(index_outer_relids); continue; } + /* * Look to see if we already computed the result for this index. */ @@ -1471,7 +1480,7 @@ best_inner_indexscan(Query *root, RelOptInfo *rel, info->isouterjoin == isouterjoin) { path = info->best_innerpath; - bms_free(index_outer_relids); /* not needed anymore */ + bms_free(index_outer_relids); /* not needed anymore */ break; } } @@ -1484,9 +1493,9 @@ best_inner_indexscan(Query *root, RelOptInfo *rel, clausegroups = group_clauses_by_indexkey_for_join(root, rel, index, - index_outer_relids, + index_outer_relids, jointype, - isouterjoin); + isouterjoin); if (clausegroups) { /* make the path */ @@ -1548,9 +1557,9 @@ make_innerjoin_index_path(Query *root, pathnode->path.parent = rel; /* - * There's no point in marking the path with any pathkeys, since - * it will only ever be used as the inner path of a nestloop, and - * so its ordering does not matter. + * There's no point in marking the path with any pathkeys, since it + * will only ever be used as the inner path of a nestloop, and so its + * ordering does not matter. */ pathnode->path.pathkeys = NIL; @@ -1582,19 +1591,19 @@ make_innerjoin_index_path(Query *root, /* * We must compute the estimated number of output rows for the - * indexscan. This is less than rel->rows because of the - * additional selectivity of the join clauses. Since clausegroups - * may contain both restriction and join clauses, we have to do a - * set union to get the full set of clauses that must be - * considered to compute the correct selectivity. (Without the union - * operation, we might have some restriction clauses appearing twice, - * which'd mislead restrictlist_selectivity into double-counting their - * selectivity. However, since RestrictInfo nodes aren't copied when - * linking them into different lists, it should be sufficient to use - * pointer comparison to remove duplicates.) + * indexscan. This is less than rel->rows because of the additional + * selectivity of the join clauses. Since clausegroups may contain + * both restriction and join clauses, we have to do a set union to get + * the full set of clauses that must be considered to compute the + * correct selectivity. (Without the union operation, we might have + * some restriction clauses appearing twice, which'd mislead + * restrictlist_selectivity into double-counting their selectivity. + * However, since RestrictInfo nodes aren't copied when linking them + * into different lists, it should be sufficient to use pointer + * comparison to remove duplicates.) * - * Always assume the join type is JOIN_INNER; even if some of the - * join clauses come from other contexts, that's not our problem. + * Always assume the join type is JOIN_INNER; even if some of the join + * clauses come from other contexts, that's not our problem. */ allclauses = set_ptrUnion(rel->baserestrictinfo, allclauses); pathnode->rows = rel->tuples * @@ -1656,9 +1665,9 @@ match_index_to_operand(Node *operand, else { /* - * Index expression; find the correct expression. (This search could - * be avoided, at the cost of complicating all the callers of this - * routine; doesn't seem worth it.) + * Index expression; find the correct expression. (This search + * could be avoided, at the cost of complicating all the callers + * of this routine; doesn't seem worth it.) */ List *indexprs; int i; @@ -1677,6 +1686,7 @@ match_index_to_operand(Node *operand, if (indexprs == NIL) elog(ERROR, "wrong number of index expressions"); indexkey = (Node *) lfirst(indexprs); + /* * Does it match the operand? Again, strip any relabeling. */ @@ -1776,12 +1786,12 @@ match_special_index_operator(Expr *clause, Oid opclass, case OID_NAME_LIKE_OP: /* the right-hand const is type text for all of these */ isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like, - &prefix, &rest) != Pattern_Prefix_None; + &prefix, &rest) != Pattern_Prefix_None; break; case OID_BYTEA_LIKE_OP: isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like, - &prefix, &rest) != Pattern_Prefix_None; + &prefix, &rest) != Pattern_Prefix_None; break; case OID_TEXT_ICLIKE_OP: @@ -1789,7 +1799,7 @@ match_special_index_operator(Expr *clause, Oid opclass, case OID_NAME_ICLIKE_OP: /* the right-hand const is type text for all of these */ isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like_IC, - &prefix, &rest) != Pattern_Prefix_None; + &prefix, &rest) != Pattern_Prefix_None; break; case OID_TEXT_REGEXEQ_OP: @@ -1797,7 +1807,7 @@ match_special_index_operator(Expr *clause, Oid opclass, case OID_NAME_REGEXEQ_OP: /* the right-hand const is type text for all of these */ isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Regex, - &prefix, &rest) != Pattern_Prefix_None; + &prefix, &rest) != Pattern_Prefix_None; break; case OID_TEXT_ICREGEXEQ_OP: @@ -1805,7 +1815,7 @@ match_special_index_operator(Expr *clause, Oid opclass, case OID_NAME_ICREGEXEQ_OP: /* the right-hand const is type text for all of these */ isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Regex_IC, - &prefix, &rest) != Pattern_Prefix_None; + &prefix, &rest) != Pattern_Prefix_None; break; case OID_INET_SUB_OP: @@ -1831,9 +1841,9 @@ match_special_index_operator(Expr *clause, Oid opclass, * want to apply. (A hash index, for example, will not support ">=".) * Currently, only btree supports the operators we need. * - * We insist on the opclass being the specific one we expect, - * else we'd do the wrong thing if someone were to make a reverse-sort - * opclass with the same operators. + * We insist on the opclass being the specific one we expect, else we'd + * do the wrong thing if someone were to make a reverse-sort opclass + * with the same operators. */ switch (expr_op) { @@ -1896,7 +1906,7 @@ match_special_index_operator(Expr *clause, Oid opclass, * The input list is ordered by index key, and so the output list is too. * (The latter is not depended on by any part of the planner, so far as I can * tell; but some parts of the executor do assume that the indxqual list - * ultimately delivered to the executor is so ordered. One such place is + * ultimately delivered to the executor is so ordered. One such place is * _bt_orderkeys() in the btree support. Perhaps that ought to be fixed * someday --- tgl 7/00) */ @@ -1930,7 +1940,7 @@ expand_indexqual_conditions(IndexOptInfo *index, List *clausegroups) } while (clausegroups != NIL && !DoneMatchingIndexKeys(classes)); - Assert(clausegroups == NIL); /* else more groups than indexkeys... */ + Assert(clausegroups == NIL); /* else more groups than indexkeys... */ return FastListValue(&resultquals); } @@ -1953,11 +1963,12 @@ expand_indexqual_condition(Expr *clause, Oid opclass) switch (expr_op) { - /* - * LIKE and regex operators are not members of any index - * opclass, so if we find one in an indexqual list we can - * assume that it was accepted by match_special_index_operator(). - */ + /* + * LIKE and regex operators are not members of any index + * opclass, so if we find one in an indexqual list we can + * assume that it was accepted by + * match_special_index_operator(). + */ case OID_TEXT_LIKE_OP: case OID_BPCHAR_LIKE_OP: case OID_NAME_LIKE_OP: @@ -2061,22 +2072,22 @@ prefix_quals(Node *leftop, Oid opclass, } /* - * If necessary, coerce the prefix constant to the right type. - * The given prefix constant is either text or bytea type. + * If necessary, coerce the prefix constant to the right type. The + * given prefix constant is either text or bytea type. */ if (prefix_const->consttype != datatype) { - char *prefix; + char *prefix; switch (prefix_const->consttype) { case TEXTOID: prefix = DatumGetCString(DirectFunctionCall1(textout, - prefix_const->constvalue)); + prefix_const->constvalue)); break; case BYTEAOID: prefix = DatumGetCString(DirectFunctionCall1(byteaout, - prefix_const->constvalue)); + prefix_const->constvalue)); break; default: elog(ERROR, "unexpected const type: %u", diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index cf7c4ee433..695b8c9841 100644 --- a/src/backend/optimizer/path/joinpath.c +++ b/src/backend/optimizer/path/joinpath.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/joinpath.c,v 1.79 2003/07/25 00:01:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/joinpath.c,v 1.80 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -300,7 +300,7 @@ sort_inner_and_outer(Query *root, * We always generate a nestloop path for each available outer path. * In fact we may generate as many as four: one on the cheapest-total-cost * inner path, one on the same with materialization, one on the - * cheapest-startup-cost inner path (if different), + * cheapest-startup-cost inner path (if different), * and one on the best inner-indexscan path (if any). * * We also consider mergejoins if mergejoin clauses are available. We have @@ -342,10 +342,10 @@ match_unsorted_outer(Query *root, /* * Nestloop only supports inner, left, and IN joins. Also, if we are - * doing a right or full join, we must use *all* the mergeclauses as join - * clauses, else we will not have a valid plan. (Although these two - * flags are currently inverses, keep them separate for clarity and - * possible future changes.) + * doing a right or full join, we must use *all* the mergeclauses as + * join clauses, else we will not have a valid plan. (Although these + * two flags are currently inverses, keep them separate for clarity + * and possible future changes.) */ switch (jointype) { @@ -371,8 +371,8 @@ match_unsorted_outer(Query *root, } /* - * If we need to unique-ify the inner path, we will consider only - * the cheapest inner. + * If we need to unique-ify the inner path, we will consider only the + * cheapest inner. */ if (jointype == JOIN_UNIQUE_INNER) { @@ -384,9 +384,10 @@ match_unsorted_outer(Query *root, else if (nestjoinOK) { /* - * If the cheapest inner path is a join or seqscan, we should consider - * materializing it. (This is a heuristic: we could consider it - * always, but for inner indexscans it's probably a waste of time.) + * If the cheapest inner path is a join or seqscan, we should + * consider materializing it. (This is a heuristic: we could + * consider it always, but for inner indexscans it's probably a + * waste of time.) */ if (!(IsA(inner_cheapest_total, IndexPath) || IsA(inner_cheapest_total, TidPath))) @@ -394,8 +395,8 @@ match_unsorted_outer(Query *root, create_material_path(innerrel, inner_cheapest_total); /* - * Get the best innerjoin indexpath (if any) for this outer rel. It's - * the same for all outer paths. + * Get the best innerjoin indexpath (if any) for this outer rel. + * It's the same for all outer paths. */ bestinnerjoin = best_inner_indexscan(root, innerrel, outerrel->relids, jointype); @@ -414,8 +415,8 @@ match_unsorted_outer(Query *root, int sortkeycnt; /* - * If we need to unique-ify the outer path, it's pointless to consider - * any but the cheapest outer. + * If we need to unique-ify the outer path, it's pointless to + * consider any but the cheapest outer. */ if (save_jointype == JOIN_UNIQUE_OUTER) { @@ -709,7 +710,7 @@ hash_inner_and_outer(Query *root, /* righthand side is inner */ } else if (bms_is_subset(restrictinfo->left_relids, innerrel->relids) && - bms_is_subset(restrictinfo->right_relids, outerrel->relids)) + bms_is_subset(restrictinfo->right_relids, outerrel->relids)) { /* lefthand side is inner */ } @@ -727,9 +728,9 @@ hash_inner_and_outer(Query *root, * cheapest-startup-cost outer paths. There's no need to consider * any but the cheapest-total-cost inner path, however. */ - Path *cheapest_startup_outer = outerrel->cheapest_startup_path; - Path *cheapest_total_outer = outerrel->cheapest_total_path; - Path *cheapest_total_inner = innerrel->cheapest_total_path; + Path *cheapest_startup_outer = outerrel->cheapest_startup_path; + Path *cheapest_total_outer = outerrel->cheapest_total_path; + Path *cheapest_total_inner = innerrel->cheapest_total_path; /* Unique-ify if need be */ if (jointype == JOIN_UNIQUE_OUTER) @@ -840,7 +841,7 @@ select_mergejoin_clauses(RelOptInfo *joinrel, /* righthand side is inner */ } else if (bms_is_subset(restrictinfo->left_relids, innerrel->relids) && - bms_is_subset(restrictinfo->right_relids, outerrel->relids)) + bms_is_subset(restrictinfo->right_relids, outerrel->relids)) { /* lefthand side is inner */ } diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c index 023bc39784..81e5080e4b 100644 --- a/src/backend/optimizer/path/joinrels.c +++ b/src/backend/optimizer/path/joinrels.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/joinrels.c,v 1.61 2003/07/25 00:01:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/joinrels.c,v 1.62 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -19,11 +19,11 @@ static List *make_rels_by_clause_joins(Query *root, - RelOptInfo *old_rel, - List *other_rels); + RelOptInfo *old_rel, + List *other_rels); static List *make_rels_by_clauseless_joins(Query *root, - RelOptInfo *old_rel, - List *other_rels); + RelOptInfo *old_rel, + List *other_rels); /* @@ -417,8 +417,8 @@ make_join_rel(Query *root, RelOptInfo *rel1, RelOptInfo *rel2, /* * If we are implementing IN clauses as joins, there are some joins - * that are illegal. Check to see if the proposed join is trouble. - * We can skip the work if looking at an outer join, however, because + * that are illegal. Check to see if the proposed join is trouble. We + * can skip the work if looking at an outer join, however, because * only top-level joins might be affected. */ if (jointype == JOIN_INNER) @@ -430,8 +430,8 @@ make_join_rel(Query *root, RelOptInfo *rel1, RelOptInfo *rel2, InClauseInfo *ininfo = (InClauseInfo *) lfirst(l); /* - * Cannot join if proposed join contains part, but only - * part, of the RHS, *and* it contains rels not in the RHS. + * Cannot join if proposed join contains part, but only part, + * of the RHS, *and* it contains rels not in the RHS. */ if (bms_overlap(ininfo->righthand, joinrelids) && !bms_is_subset(ininfo->righthand, joinrelids) && @@ -442,16 +442,17 @@ make_join_rel(Query *root, RelOptInfo *rel1, RelOptInfo *rel2, } /* - * No issue unless we are looking at a join of the IN's RHS - * to other stuff. + * No issue unless we are looking at a join of the IN's RHS to + * other stuff. */ - if (! (bms_is_subset(ininfo->righthand, joinrelids) && - !bms_equal(ininfo->righthand, joinrelids))) + if (!(bms_is_subset(ininfo->righthand, joinrelids) && + !bms_equal(ininfo->righthand, joinrelids))) continue; + /* - * If we already joined IN's RHS to any part of its LHS in either - * input path, then this join is not constrained (the necessary - * work was done at a lower level). + * If we already joined IN's RHS to any part of its LHS in + * either input path, then this join is not constrained (the + * necessary work was done at a lower level). */ if (bms_overlap(ininfo->lefthand, rel1->relids) && bms_is_subset(ininfo->righthand, rel1->relids)) @@ -459,6 +460,7 @@ make_join_rel(Query *root, RelOptInfo *rel1, RelOptInfo *rel2, if (bms_overlap(ininfo->lefthand, rel2->relids) && bms_is_subset(ininfo->righthand, rel2->relids)) continue; + /* * JOIN_IN technique will work if outerrel includes LHS and * innerrel is exactly RHS; conversely JOIN_REVERSE_IN handles @@ -478,22 +480,14 @@ make_join_rel(Query *root, RelOptInfo *rel1, RelOptInfo *rel2, } if (bms_is_subset(ininfo->lefthand, rel1->relids) && bms_equal(ininfo->righthand, rel2->relids)) - { jointype = JOIN_IN; - } else if (bms_is_subset(ininfo->lefthand, rel2->relids) && bms_equal(ininfo->righthand, rel1->relids)) - { jointype = JOIN_REVERSE_IN; - } else if (bms_equal(ininfo->righthand, rel1->relids)) - { jointype = JOIN_UNIQUE_OUTER; - } else if (bms_equal(ininfo->righthand, rel2->relids)) - { jointype = JOIN_UNIQUE_INNER; - } else { /* invalid join path */ diff --git a/src/backend/optimizer/path/orindxpath.c b/src/backend/optimizer/path/orindxpath.c index a078b3f5a9..40d2de4141 100644 --- a/src/backend/optimizer/path/orindxpath.c +++ b/src/backend/optimizer/path/orindxpath.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/orindxpath.c,v 1.51 2003/06/15 22:51:45 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/orindxpath.c,v 1.52 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -99,7 +99,7 @@ create_or_index_paths(Query *root, RelOptInfo *rel) best_or_subclause_indices(root, rel, - ((BoolExpr *) restrictinfo->clause)->args, + ((BoolExpr *) restrictinfo->clause)->args, restrictinfo->subclauseindices, pathnode); diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c index 9fec73e260..beb51a6996 100644 --- a/src/backend/optimizer/path/pathkeys.c +++ b/src/backend/optimizer/path/pathkeys.c @@ -11,7 +11,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/pathkeys.c,v 1.51 2003/07/25 00:01:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/pathkeys.c,v 1.52 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -198,8 +198,8 @@ generate_implied_equalities(Query *root) /* * Collect info about relids mentioned in each item. For this * routine we only really care whether there are any at all in - * each item, but process_implied_equality() needs the exact - * sets, so we may as well pull them here. + * each item, but process_implied_equality() needs the exact sets, + * so we may as well pull them here. */ relids = (Relids *) palloc(nitems * sizeof(Relids)); have_consts = false; @@ -233,8 +233,8 @@ generate_implied_equalities(Query *root) /* * If it's "const = const" then just ignore it altogether. - * There is no place in the restrictinfo structure to store - * it. (If the two consts are in fact unequal, then + * There is no place in the restrictinfo structure to + * store it. (If the two consts are in fact unequal, then * propagating the comparison to Vars will cause us to * produce zero rows out, as expected.) */ @@ -242,12 +242,12 @@ generate_implied_equalities(Query *root) { /* * Tell process_implied_equality to delete the clause, - * not add it, if it's "var = var" and we have constants - * present in the list. + * not add it, if it's "var = var" and we have + * constants present in the list. */ - bool delete_it = (have_consts && - i1_is_variable && - i2_is_variable); + bool delete_it = (have_consts && + i1_is_variable && + i2_is_variable); process_implied_equality(root, item1->key, item2->key, @@ -751,20 +751,21 @@ build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery) * element might match none, one, or more of the output columns * that are visible to the outer query. This means we may have * multiple possible representations of the sub_pathkey in the - * context of the outer query. Ideally we would generate them all - * and put them all into a pathkey list of the outer query, thereby - * propagating equality knowledge up to the outer query. Right now - * we cannot do so, because the outer query's canonical pathkey - * sets are already frozen when this is called. Instead we prefer - * the one that has the highest "score" (number of canonical pathkey - * peers, plus one if it matches the outer query_pathkeys). - * This is the most likely to be useful in the outer query. + * context of the outer query. Ideally we would generate them all + * and put them all into a pathkey list of the outer query, + * thereby propagating equality knowledge up to the outer query. + * Right now we cannot do so, because the outer query's canonical + * pathkey sets are already frozen when this is called. Instead + * we prefer the one that has the highest "score" (number of + * canonical pathkey peers, plus one if it matches the outer + * query_pathkeys). This is the most likely to be useful in the + * outer query. */ foreach(j, sub_pathkey) { PathKeyItem *sub_item = (PathKeyItem *) lfirst(j); - Node *sub_key = sub_item->key; - List *k; + Node *sub_key = sub_item->key; + List *k; foreach(k, subquery->targetList) { @@ -774,9 +775,9 @@ build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery) equal(tle->expr, sub_key)) { /* Found a representation for this sub_key */ - Var *outer_var; + Var *outer_var; PathKeyItem *outer_item; - int score; + int score; outer_var = makeVar(rel->relid, tle->resdom->resno, @@ -802,8 +803,8 @@ build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery) } /* - * If we couldn't find a representation of this sub_pathkey, - * we're done (we can't use the ones to its right, either). + * If we couldn't find a representation of this sub_pathkey, we're + * done (we can't use the ones to its right, either). */ if (!best_item) break; @@ -812,8 +813,8 @@ build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery) cpathkey = make_canonical_pathkey(root, best_item); /* - * Eliminate redundant ordering info; could happen if outer - * query equijoins subquery keys... + * Eliminate redundant ordering info; could happen if outer query + * equijoins subquery keys... */ if (!ptrMember(cpathkey, retval)) { @@ -920,7 +921,7 @@ make_pathkeys_for_sortclauses(List *sortclauses, * many times when dealing with a many-relation query. * * We have to be careful that the cached values are palloc'd in the same - * context the RestrictInfo node itself is in. This is not currently a + * context the RestrictInfo node itself is in. This is not currently a * problem for normal planning, but it is an issue for GEQO planning. */ void @@ -1090,7 +1091,7 @@ make_pathkeys_for_mergeclauses(Query *root, else { elog(ERROR, "could not identify which side of mergeclause to use"); - pathkey = NIL; /* keep compiler quiet */ + pathkey = NIL; /* keep compiler quiet */ } /* diff --git a/src/backend/optimizer/path/tidpath.c b/src/backend/optimizer/path/tidpath.c index 761f03b967..60093ec5e3 100644 --- a/src/backend/optimizer/path/tidpath.c +++ b/src/backend/optimizer/path/tidpath.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/tidpath.c,v 1.14 2003/02/08 20:20:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/tidpath.c,v 1.15 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,7 +27,7 @@ static List *TidqualFromRestrictinfo(Relids relids, List *restrictinfo); static bool isEvaluable(int varno, Node *node); -static Node *TidequalClause(int varno, OpExpr *node); +static Node *TidequalClause(int varno, OpExpr * node); static List *TidqualFromExpr(int varno, Expr *expr); static bool @@ -66,7 +66,7 @@ isEvaluable(int varno, Node *node) * or the left node if the opclause is ....=CTID */ static Node * -TidequalClause(int varno, OpExpr *node) +TidequalClause(int varno, OpExpr * node) { Node *rnode = NULL, *arg1, diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index 9ac746d34a..e4e7490d82 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/createplan.c,v 1.149 2003/07/25 00:01:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/createplan.c,v 1.150 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -40,9 +40,9 @@ static bool use_physical_tlist(RelOptInfo *rel); static void disuse_physical_tlist(Plan *plan, Path *path); static Join *create_join_plan(Query *root, JoinPath *best_path); static Append *create_append_plan(Query *root, AppendPath *best_path); -static Result *create_result_plan(Query *root, ResultPath *best_path); -static Material *create_material_plan(Query *root, MaterialPath *best_path); -static Plan *create_unique_plan(Query *root, UniquePath *best_path); +static Result *create_result_plan(Query *root, ResultPath * best_path); +static Material *create_material_plan(Query *root, MaterialPath * best_path); +static Plan *create_unique_plan(Query *root, UniquePath * best_path); static SeqScan *create_seqscan_plan(Path *best_path, List *tlist, List *scan_clauses); static IndexScan *create_indexscan_plan(Query *root, IndexPath *best_path, @@ -63,9 +63,9 @@ static void fix_indxqual_references(List *indexquals, IndexPath *index_path, List **fixed_indexquals, List **recheck_indexquals); static void fix_indxqual_sublist(List *indexqual, - Relids baserelids, int baserelid, - IndexOptInfo *index, - List **fixed_quals, List **recheck_quals); + Relids baserelids, int baserelid, + IndexOptInfo *index, + List **fixed_quals, List **recheck_quals); static Node *fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index, Oid *opclass); @@ -98,9 +98,9 @@ static MergeJoin *make_mergejoin(List *tlist, Plan *lefttree, Plan *righttree, JoinType jointype); static Sort *make_sort(Query *root, List *tlist, Plan *lefttree, int numCols, - AttrNumber *sortColIdx, Oid *sortOperators); + AttrNumber *sortColIdx, Oid *sortOperators); static Sort *make_sort_from_pathkeys(Query *root, Plan *lefttree, - Relids relids, List *pathkeys); + Relids relids, List *pathkeys); /* @@ -148,7 +148,7 @@ create_plan(Query *root, Path *best_path) break; case T_Material: plan = (Plan *) create_material_plan(root, - (MaterialPath *) best_path); + (MaterialPath *) best_path); break; case T_Unique: plan = (Plan *) create_unique_plan(root, @@ -192,12 +192,12 @@ create_scan_plan(Query *root, Path *best_path) Scan *plan; /* - * For table scans, rather than using the relation targetlist (which is - * only those Vars actually needed by the query), we prefer to generate a - * tlist containing all Vars in order. This will allow the executor to - * optimize away projection of the table tuples, if possible. (Note that - * planner.c may replace the tlist we generate here, forcing projection to - * occur.) + * For table scans, rather than using the relation targetlist (which + * is only those Vars actually needed by the query), we prefer to + * generate a tlist containing all Vars in order. This will allow the + * executor to optimize away projection of the table tuples, if + * possible. (Note that planner.c may replace the tlist we generate + * here, forcing projection to occur.) */ if (use_physical_tlist(rel)) { @@ -274,8 +274,8 @@ build_relation_tlist(RelOptInfo *rel) FastListInit(&tlist); foreach(v, FastListValue(&rel->reltargetlist)) { - /* Do we really need to copy here? Not sure */ - Var *var = (Var *) copyObject(lfirst(v)); + /* Do we really need to copy here? Not sure */ + Var *var = (Var *) copyObject(lfirst(v)); FastAppend(&tlist, create_tl_element(var, resdomno)); resdomno++; @@ -294,22 +294,24 @@ use_physical_tlist(RelOptInfo *rel) int i; /* - * Currently, can't do this for subquery or function scans. (This - * is mainly because we don't have an equivalent of build_physical_tlist + * Currently, can't do this for subquery or function scans. (This is + * mainly because we don't have an equivalent of build_physical_tlist * for them; worth adding?) */ if (rel->rtekind != RTE_RELATION) return false; + /* * Can't do it with inheritance cases either (mainly because Append * doesn't project). */ if (rel->reloptkind != RELOPT_BASEREL) return false; + /* - * Can't do it if any system columns are requested, either. (This could - * possibly be fixed but would take some fragile assumptions in setrefs.c, - * I think.) + * Can't do it if any system columns are requested, either. (This + * could possibly be fixed but would take some fragile assumptions in + * setrefs.c, I think.) */ for (i = rel->min_attr; i <= 0; i++) { @@ -325,7 +327,7 @@ use_physical_tlist(RelOptInfo *rel) * * If the plan node immediately above a scan would prefer to get only * needed Vars and not a physical tlist, it must call this routine to - * undo the decision made by use_physical_tlist(). Currently, Hash, Sort, + * undo the decision made by use_physical_tlist(). Currently, Hash, Sort, * and Material nodes want this, so they don't have to store useless columns. */ static void @@ -441,7 +443,7 @@ create_append_plan(Query *root, AppendPath *best_path) * Returns a Plan node. */ static Result * -create_result_plan(Query *root, ResultPath *best_path) +create_result_plan(Query *root, ResultPath * best_path) { Result *plan; List *tlist; @@ -473,7 +475,7 @@ create_result_plan(Query *root, ResultPath *best_path) * Returns a Plan node. */ static Material * -create_material_plan(Query *root, MaterialPath *best_path) +create_material_plan(Query *root, MaterialPath * best_path) { Material *plan; Plan *subplan; @@ -498,7 +500,7 @@ create_material_plan(Query *root, MaterialPath *best_path) * Returns a Plan node. */ static Plan * -create_unique_plan(Query *root, UniquePath *best_path) +create_unique_plan(Query *root, UniquePath * best_path) { Plan *plan; Plan *subplan; @@ -509,9 +511,9 @@ create_unique_plan(Query *root, UniquePath *best_path) subplan = create_plan(root, best_path->subpath); /* - * If the subplan came from an IN subselect (currently always the case), - * we need to instantiate the correct output targetlist for the subselect, - * rather than using the flattened tlist. + * If the subplan came from an IN subselect (currently always the + * case), we need to instantiate the correct output targetlist for the + * subselect, rather than using the flattened tlist. */ sub_targetlist = NIL; foreach(l, root->in_info_list) @@ -530,8 +532,8 @@ create_unique_plan(Query *root, UniquePath *best_path) /* * Transform list of plain Vars into targetlist */ - List *newtlist = NIL; - int resno = 1; + List *newtlist = NIL; + int resno = 1; foreach(l, sub_targetlist) { @@ -547,12 +549,13 @@ create_unique_plan(Query *root, UniquePath *best_path) newtlist = lappend(newtlist, tle); resno++; } + /* * If the top plan node can't do projections, we need to add a * Result node to help it along. * - * Currently, the only non-projection-capable plan type - * we can see here is Append. + * Currently, the only non-projection-capable plan type we can see + * here is Append. */ if (IsA(subplan, Append)) subplan = (Plan *) make_result(newtlist, NULL, subplan); @@ -564,16 +567,16 @@ create_unique_plan(Query *root, UniquePath *best_path) if (best_path->use_hash) { - int numGroupCols = length(my_tlist); - long numGroups; + int numGroupCols = length(my_tlist); + long numGroups; AttrNumber *groupColIdx; - int i; + int i; numGroups = (long) Min(best_path->rows, (double) LONG_MAX); groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber)); for (i = 0; i < numGroupCols; i++) - groupColIdx[i] = i+1; + groupColIdx[i] = i + 1; plan = (Plan *) make_agg(root, my_tlist, @@ -700,9 +703,7 @@ create_indexscan_plan(Query *root, FastListInit(&orclauses); foreach(orclause, indxqual) - { FastAppend(&orclauses, make_ands_explicit(lfirst(orclause))); - } indxqual_or_expr = make_orclause(FastListValue(&orclauses)); qpqual = set_difference(scan_clauses, makeList1(indxqual_or_expr)); @@ -861,9 +862,9 @@ create_nestloop_plan(Query *root, /* * An index is being used to reduce the number of tuples scanned * in the inner relation. If there are join clauses being used - * with the index, we may remove those join clauses from the list of - * clauses that have to be checked as qpquals at the join node --- - * but only if there's just one indexscan in the inner path + * with the index, we may remove those join clauses from the list + * of clauses that have to be checked as qpquals at the join node + * --- but only if there's just one indexscan in the inner path * (otherwise, several different sets of clauses are being ORed * together). * @@ -873,13 +874,14 @@ create_nestloop_plan(Query *root, * been put in the same joininfo list. * * This would be a waste of time if the indexpath was an ordinary - * indexpath and not a special innerjoin path. We will skip it in - * that case since indexjoinclauses is NIL in an ordinary indexpath. + * indexpath and not a special innerjoin path. We will skip it in + * that case since indexjoinclauses is NIL in an ordinary + * indexpath. */ IndexPath *innerpath = (IndexPath *) best_path->innerjoinpath; List *indexjoinclauses = innerpath->indexjoinclauses; - if (length(indexjoinclauses) == 1) /* single indexscan? */ + if (length(indexjoinclauses) == 1) /* single indexscan? */ { joinrestrictclauses = select_nonredundant_join_clauses(root, @@ -947,11 +949,11 @@ create_mergejoin_plan(Query *root, joinclauses = set_difference(joinclauses, mergeclauses); /* - * Rearrange mergeclauses, if needed, so that the outer variable - * is always on the left. + * Rearrange mergeclauses, if needed, so that the outer variable is + * always on the left. */ mergeclauses = get_switched_clauses(best_path->path_mergeclauses, - best_path->jpath.outerjoinpath->parent->relids); + best_path->jpath.outerjoinpath->parent->relids); /* * Create explicit sort nodes for the outer and inner join paths if @@ -964,7 +966,7 @@ create_mergejoin_plan(Query *root, outer_plan = (Plan *) make_sort_from_pathkeys(root, outer_plan, - best_path->jpath.outerjoinpath->parent->relids, + best_path->jpath.outerjoinpath->parent->relids, best_path->outersortkeys); } @@ -974,7 +976,7 @@ create_mergejoin_plan(Query *root, inner_plan = (Plan *) make_sort_from_pathkeys(root, inner_plan, - best_path->jpath.innerjoinpath->parent->relids, + best_path->jpath.innerjoinpath->parent->relids, best_path->innersortkeys); } @@ -1030,21 +1032,19 @@ create_hashjoin_plan(Query *root, joinclauses = set_difference(joinclauses, hashclauses); /* - * Rearrange hashclauses, if needed, so that the outer variable - * is always on the left. + * Rearrange hashclauses, if needed, so that the outer variable is + * always on the left. */ hashclauses = get_switched_clauses(best_path->path_hashclauses, - best_path->jpath.outerjoinpath->parent->relids); + best_path->jpath.outerjoinpath->parent->relids); /* - * Extract the inner hash keys (right-hand operands of the hashclauses) - * to put in the Hash node. + * Extract the inner hash keys (right-hand operands of the + * hashclauses) to put in the Hash node. */ innerhashkeys = NIL; foreach(hcl, hashclauses) - { innerhashkeys = lappend(innerhashkeys, get_rightop(lfirst(hcl))); - } /* We don't want any excess columns in the hashed tuples */ disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath); @@ -1362,7 +1362,7 @@ order_qual_clauses(Query *root, List *clauses) FastListInit(&withsubplans); foreach(l, clauses) { - Node *clause = lfirst(l); + Node *clause = lfirst(l); if (contain_subplans(clause)) FastAppend(&withsubplans, clause); @@ -1507,8 +1507,8 @@ make_subqueryscan(List *qptlist, /* * Cost is figured here for the convenience of prepunion.c. Note this - * is only correct for the case where qpqual is empty; otherwise caller - * should overwrite cost with a better estimate. + * is only correct for the case where qpqual is empty; otherwise + * caller should overwrite cost with a better estimate. */ copy_plan_costsize(plan, subplan); plan->total_cost += cpu_tuple_cost * subplan->plan_rows; @@ -1709,7 +1709,7 @@ make_sort(Query *root, List *tlist, Plan *lefttree, int numCols, * once as a sort key column; if so, the extra mentions are redundant. * * Caller is assumed to have allocated the arrays large enough for the - * max possible number of columns. Return value is the new column count. + * max possible number of columns. Return value is the new column count. */ static int add_sort_column(AttrNumber colIdx, Oid sortOp, @@ -1777,8 +1777,8 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, /* * We can sort by any one of the sort key items listed in this * sublist. For now, we take the first one that corresponds to an - * available Var in the tlist. If there isn't any, use the - * first one that is an expression in the input's vars. + * available Var in the tlist. If there isn't any, use the first + * one that is an expression in the input's vars. * * XXX if we have a choice, is there any way of figuring out which * might be cheapest to execute? (For example, int4lt is likely @@ -1805,17 +1805,19 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, } if (!j) elog(ERROR, "could not find pathkey item to sort"); + /* * Do we need to insert a Result node? * - * Currently, the only non-projection-capable plan type - * we can see here is Append. + * Currently, the only non-projection-capable plan type we can + * see here is Append. */ if (IsA(lefttree, Append)) { tlist = copyObject(tlist); lefttree = (Plan *) make_result(tlist, NULL, lefttree); } + /* * Add resjunk entry to input's tlist */ @@ -1827,8 +1829,9 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, tlist = lappend(tlist, makeTargetEntry(resdom, (Expr *) pathkey->key)); - lefttree->targetlist = tlist; /* just in case NIL before */ + lefttree->targetlist = tlist; /* just in case NIL before */ } + /* * The column might already be selected as a sort key, if the * pathkeys contain duplicate entries. (This can happen in @@ -1836,7 +1839,7 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, * var, for example.) So enter it only once in the sort arrays. */ numsortkeys = add_sort_column(resdom->resno, pathkey->sortop, - numsortkeys, sortColIdx, sortOperators); + numsortkeys, sortColIdx, sortOperators); } Assert(numsortkeys > 0); @@ -1881,10 +1884,11 @@ make_sort_from_sortclauses(Query *root, List *tlist, /* * Check for the possibility of duplicate order-by clauses --- the - * parser should have removed 'em, but no point in sorting redundantly. + * parser should have removed 'em, but no point in sorting + * redundantly. */ numsortkeys = add_sort_column(resdom->resno, sortcl->sortop, - numsortkeys, sortColIdx, sortOperators); + numsortkeys, sortColIdx, sortOperators); } Assert(numsortkeys > 0); @@ -1938,10 +1942,11 @@ make_sort_from_groupcols(Query *root, /* * Check for the possibility of duplicate group-by clauses --- the - * parser should have removed 'em, but no point in sorting redundantly. + * parser should have removed 'em, but no point in sorting + * redundantly. */ numsortkeys = add_sort_column(resdom->resno, grpcl->sortop, - numsortkeys, sortColIdx, sortOperators); + numsortkeys, sortColIdx, sortOperators); grpno++; } @@ -1973,7 +1978,7 @@ make_material(List *tlist, Plan *lefttree) * materialize_finished_plan: stick a Material node atop a completed plan * * There are a couple of places where we want to attach a Material node - * after completion of subquery_planner(). This currently requires hackery. + * after completion of subquery_planner(). This currently requires hackery. * Since subquery_planner has already run SS_finalize_plan on the subplan * tree, we have to kluge up parameter lists for the Material node. * Possibly this could be fixed by postponing SS_finalize_plan processing @@ -2032,8 +2037,8 @@ make_agg(Query *root, List *tlist, List *qual, plan->total_cost = agg_path.total_cost; /* - * We will produce a single output tuple if not grouping, - * and a tuple per group otherwise. + * We will produce a single output tuple if not grouping, and a tuple + * per group otherwise. */ if (aggstrategy == AGG_PLAIN) plan->plan_rows = 1; @@ -2041,10 +2046,10 @@ make_agg(Query *root, List *tlist, List *qual, plan->plan_rows = numGroups; /* - * We also need to account for the cost of evaluation of the qual - * (ie, the HAVING clause) and the tlist. Note that cost_qual_eval - * doesn't charge anything for Aggref nodes; this is okay since - * they are really comparable to Vars. + * We also need to account for the cost of evaluation of the qual (ie, + * the HAVING clause) and the tlist. Note that cost_qual_eval doesn't + * charge anything for Aggref nodes; this is okay since they are + * really comparable to Vars. * * See notes in grouping_planner about why this routine and make_group * are the only ones in this file that worry about tlist eval cost. @@ -2100,13 +2105,13 @@ make_group(Query *root, /* * We also need to account for the cost of evaluation of the tlist. * - * XXX this double-counts the cost of evaluation of any expressions - * used for grouping, since in reality those will have been evaluated - * at a lower plan level and will only be copied by the Group node. - * Worth fixing? + * XXX this double-counts the cost of evaluation of any expressions used + * for grouping, since in reality those will have been evaluated at a + * lower plan level and will only be copied by the Group node. Worth + * fixing? * - * See notes in grouping_planner about why this routine and make_agg - * are the only ones in this file that worry about tlist eval cost. + * See notes in grouping_planner about why this routine and make_agg are + * the only ones in this file that worry about tlist eval cost. */ cost_qual_eval(&qual_cost, tlist); plan->startup_cost += qual_cost.startup; @@ -2139,15 +2144,15 @@ make_unique(List *tlist, Plan *lefttree, List *distinctList) /* * Charge one cpu_operator_cost per comparison per input tuple. We - * assume all columns get compared at most of the tuples. (XXX probably - * this is an overestimate.) + * assume all columns get compared at most of the tuples. (XXX + * probably this is an overestimate.) */ plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols; /* * plan->plan_rows is left as a copy of the input subplan's plan_rows; - * ie, we assume the filter removes nothing. The caller must alter this - * if he has a better idea. + * ie, we assume the filter removes nothing. The caller must alter + * this if he has a better idea. */ plan->targetlist = tlist; diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index afcb452832..61edf1c22d 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/initsplan.c,v 1.88 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/initsplan.c,v 1.89 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -36,12 +36,12 @@ static void mark_baserels_for_outer_join(Query *root, Relids rels, Relids outerrels); static void distribute_qual_to_rels(Query *root, Node *clause, - bool ispusheddown, - bool isdeduced, - Relids outerjoin_nonnullable, - Relids qualscope); + bool ispusheddown, + bool isdeduced, + Relids outerjoin_nonnullable, + Relids qualscope); static void add_vars_to_targetlist(Query *root, List *vars, - Relids where_needed); + Relids where_needed); static bool qual_is_redundant(Query *root, RestrictInfo *restrictinfo, List *restrictlist); static void check_mergejoinable(RestrictInfo *restrictinfo); @@ -83,9 +83,7 @@ add_base_rels_to_query(Query *root, Node *jtnode) List *l; foreach(l, f->fromlist) - { add_base_rels_to_query(root, lfirst(l)); - } } else if (IsA(jtnode, JoinExpr)) { @@ -93,13 +91,14 @@ add_base_rels_to_query(Query *root, Node *jtnode) add_base_rels_to_query(root, j->larg); add_base_rels_to_query(root, j->rarg); + /* * Safety check: join RTEs should not be SELECT FOR UPDATE targets */ if (intMember(j->rtindex, root->rowMarks)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("SELECT FOR UPDATE cannot be applied to a join"))); + errmsg("SELECT FOR UPDATE cannot be applied to a join"))); } else elog(ERROR, "unrecognized node type: %d", @@ -247,14 +246,14 @@ distribute_quals_to_rels(Query *root, Node *jtnode) * Order of operations here is subtle and critical. First we * recurse to handle sub-JOINs. Their join quals will be placed * without regard for whether this level is an outer join, which - * is correct. Then we place our own join quals, which are restricted - * by lower outer joins in any case, and are forced to this level if - * this is an outer join and they mention the outer side. Finally, if - * this is an outer join, we mark baserels contained within the inner - * side(s) with our own rel set; this will prevent quals above us in - * the join tree that use those rels from being pushed down below this - * level. (It's okay for upper quals to be pushed down to the outer - * side, however.) + * is correct. Then we place our own join quals, which are + * restricted by lower outer joins in any case, and are forced to + * this level if this is an outer join and they mention the outer + * side. Finally, if this is an outer join, we mark baserels + * contained within the inner side(s) with our own rel set; this + * will prevent quals above us in the join tree that use those + * rels from being pushed down below this level. (It's okay for + * upper quals to be pushed down to the outer side, however.) */ leftids = distribute_quals_to_rels(root, j->larg); rightids = distribute_quals_to_rels(root, j->rarg); @@ -390,9 +389,10 @@ distribute_qual_to_rels(Query *root, Node *clause, restrictinfo->clause = (Expr *) clause; restrictinfo->subclauseindices = NIL; - restrictinfo->eval_cost.startup = -1; /* not computed until needed */ + restrictinfo->eval_cost.startup = -1; /* not computed until + * needed */ restrictinfo->this_selec = -1; /* not computed until needed */ - restrictinfo->left_relids = NULL; /* set below, if join clause */ + restrictinfo->left_relids = NULL; /* set below, if join clause */ restrictinfo->right_relids = NULL; restrictinfo->mergejoinoperator = InvalidOid; restrictinfo->left_sortop = InvalidOid; @@ -435,10 +435,10 @@ distribute_qual_to_rels(Query *root, Node *clause, if (isdeduced) { /* - * If the qual came from implied-equality deduction, we can evaluate - * the qual at its natural semantic level. It is not affected by - * any outer-join rules (else we'd not have decided the vars were - * equal). + * If the qual came from implied-equality deduction, we can + * evaluate the qual at its natural semantic level. It is not + * affected by any outer-join rules (else we'd not have decided + * the vars were equal). */ Assert(bms_equal(relids, qualscope)); can_be_equijoin = true; @@ -446,12 +446,13 @@ distribute_qual_to_rels(Query *root, Node *clause, else if (bms_overlap(relids, outerjoin_nonnullable)) { /* - * The qual is attached to an outer join and mentions (some of the) - * rels on the nonnullable side. Force the qual to be evaluated - * exactly at the level of joining corresponding to the outer join. - * We cannot let it get pushed down into the nonnullable side, since - * then we'd produce no output rows, rather than the intended single - * null-extended row, for any nonnullable-side rows failing the qual. + * The qual is attached to an outer join and mentions (some of + * the) rels on the nonnullable side. Force the qual to be + * evaluated exactly at the level of joining corresponding to the + * outer join. We cannot let it get pushed down into the + * nonnullable side, since then we'd produce no output rows, + * rather than the intended single null-extended row, for any + * nonnullable-side rows failing the qual. * * Note: an outer-join qual that mentions only nullable-side rels can * be pushed down into the nullable side without changing the join @@ -464,13 +465,14 @@ distribute_qual_to_rels(Query *root, Node *clause, { /* * For a non-outer-join qual, we can evaluate the qual as soon as - * (1) we have all the rels it mentions, and (2) we are at or above - * any outer joins that can null any of these rels and are below the - * syntactic location of the given qual. To enforce the latter, scan - * the base rels listed in relids, and merge their outer-join sets - * into the clause's own reference list. At the time we are called, - * the outerjoinset of each baserel will show exactly those outer - * joins that are below the qual in the join tree. + * (1) we have all the rels it mentions, and (2) we are at or + * above any outer joins that can null any of these rels and are + * below the syntactic location of the given qual. To enforce the + * latter, scan the base rels listed in relids, and merge their + * outer-join sets into the clause's own reference list. At the + * time we are called, the outerjoinset of each baserel will show + * exactly those outer joins that are below the qual in the join + * tree. */ Relids addrelids = NULL; Relids tmprelids; @@ -496,9 +498,10 @@ distribute_qual_to_rels(Query *root, Node *clause, relids = bms_union(relids, addrelids); /* Should still be a subset of current scope ... */ Assert(bms_is_subset(relids, qualscope)); + /* - * Because application of the qual will be delayed by outer join, - * we mustn't assume its vars are equal everywhere. + * Because application of the qual will be delayed by outer + * join, we mustn't assume its vars are equal everywhere. */ can_be_equijoin = false; } @@ -518,6 +521,7 @@ distribute_qual_to_rels(Query *root, Node *clause, switch (bms_membership(relids)) { case BMS_SINGLETON: + /* * There is only one relation participating in 'clause', so * 'clause' is a restriction clause for that relation. @@ -525,28 +529,29 @@ distribute_qual_to_rels(Query *root, Node *clause, rel = find_base_rel(root, bms_singleton_member(relids)); /* - * Check for a "mergejoinable" clause even though it's not a join - * clause. This is so that we can recognize that "a.x = a.y" - * makes x and y eligible to be considered equal, even when they - * belong to the same rel. Without this, we would not recognize - * that "a.x = a.y AND a.x = b.z AND a.y = c.q" allows us to - * consider z and q equal after their rels are joined. + * Check for a "mergejoinable" clause even though it's not a + * join clause. This is so that we can recognize that "a.x = + * a.y" makes x and y eligible to be considered equal, even + * when they belong to the same rel. Without this, we would + * not recognize that "a.x = a.y AND a.x = b.z AND a.y = c.q" + * allows us to consider z and q equal after their rels are + * joined. */ if (can_be_equijoin) check_mergejoinable(restrictinfo); /* - * If the clause was deduced from implied equality, check to see - * whether it is redundant with restriction clauses we already - * have for this rel. Note we cannot apply this check to - * user-written clauses, since we haven't found the canonical - * pathkey sets yet while processing user clauses. (NB: no - * comparable check is done in the join-clause case; redundancy - * will be detected when the join clause is moved into a join - * rel's restriction list.) + * If the clause was deduced from implied equality, check to + * see whether it is redundant with restriction clauses we + * already have for this rel. Note we cannot apply this check + * to user-written clauses, since we haven't found the + * canonical pathkey sets yet while processing user clauses. + * (NB: no comparable check is done in the join-clause case; + * redundancy will be detected when the join clause is moved + * into a join rel's restriction list.) */ if (!isdeduced || - !qual_is_redundant(root, restrictinfo, rel->baserestrictinfo)) + !qual_is_redundant(root, restrictinfo, rel->baserestrictinfo)) { /* Add clause to rel's restriction list */ rel->baserestrictinfo = lappend(rel->baserestrictinfo, @@ -554,13 +559,14 @@ distribute_qual_to_rels(Query *root, Node *clause, } break; case BMS_MULTIPLE: + /* - * 'clause' is a join clause, since there is more than one rel in - * the relid set. Set additional RestrictInfo fields for - * joining. First, does it look like a normal join clause, i.e., - * a binary operator relating expressions that come from distinct - * relations? If so we might be able to use it in a join - * algorithm. + * 'clause' is a join clause, since there is more than one rel + * in the relid set. Set additional RestrictInfo fields for + * joining. First, does it look like a normal join clause, + * i.e., a binary operator relating expressions that come from + * distinct relations? If so we might be able to use it in a + * join algorithm. */ if (is_opclause(clause) && length(((OpExpr *) clause)->args) == 2) { @@ -582,9 +588,9 @@ distribute_qual_to_rels(Query *root, Node *clause, * Now check for hash or mergejoinable operators. * * We don't bother setting the hashjoin info if we're not going - * to need it. We do want to know about mergejoinable ops in all - * cases, however, because we use mergejoinable ops for other - * purposes such as detecting redundant clauses. + * to need it. We do want to know about mergejoinable ops in + * all cases, however, because we use mergejoinable ops for + * other purposes such as detecting redundant clauses. */ check_mergejoinable(restrictinfo); if (enable_hashjoin) @@ -597,16 +603,18 @@ distribute_qual_to_rels(Query *root, Node *clause, /* * Add vars used in the join clause to targetlists of their - * relations, so that they will be emitted by the plan nodes that - * scan those relations (else they won't be available at the join - * node!). + * relations, so that they will be emitted by the plan nodes + * that scan those relations (else they won't be available at + * the join node!). */ add_vars_to_targetlist(root, vars, relids); break; default: + /* - * 'clause' references no rels, and therefore we have no place to - * attach it. Shouldn't get here if callers are working properly. + * 'clause' references no rels, and therefore we have no place + * to attach it. Shouldn't get here if callers are working + * properly. */ elog(ERROR, "cannot cope with variable-free clause"); break; @@ -634,7 +642,7 @@ distribute_qual_to_rels(Query *root, Node *clause, * * This processing is a consequence of transitivity of mergejoin equality: * if we have mergejoinable clauses A = B and B = C, we can deduce A = C - * (where = is an appropriate mergejoinable operator). See path/pathkeys.c + * (where = is an appropriate mergejoinable operator). See path/pathkeys.c * for more details. */ void @@ -695,8 +703,8 @@ process_implied_equality(Query *root, } /* - * Scan to see if equality is already known. If so, we're done in - * the add case, and done after removing it in the delete case. + * Scan to see if equality is already known. If so, we're done in the + * add case, and done after removing it in the delete case. */ foreach(itm, restrictlist) { @@ -719,7 +727,7 @@ process_implied_equality(Query *root, { /* delete it from local restrictinfo list */ rel1->baserestrictinfo = lremove(restrictinfo, - rel1->baserestrictinfo); + rel1->baserestrictinfo); } else { @@ -768,9 +776,9 @@ process_implied_equality(Query *root, errmsg("equality operator for types %s and %s should be mergejoinable, but isn't", format_type_be(ltype), format_type_be(rtype)))); - clause = make_opclause(oprid(eq_operator), /* opno */ - BOOLOID, /* opresulttype */ - false, /* opretset */ + clause = make_opclause(oprid(eq_operator), /* opno */ + BOOLOID, /* opresulttype */ + false, /* opretset */ (Expr *) item1, (Expr *) item2); @@ -797,9 +805,9 @@ process_implied_equality(Query *root, * too-small selectivity, not to mention wasting time at execution. * * Note: quals of the form "var = const" are never considered redundant, - * only those of the form "var = var". This is needed because when we + * only those of the form "var = var". This is needed because when we * have constants in an implied-equality set, we use a different strategy - * that suppresses all "var = var" deductions. We must therefore keep + * that suppresses all "var = var" deductions. We must therefore keep * all the "var = const" quals. */ static bool @@ -858,7 +866,8 @@ qual_is_redundant(Query *root, * left side of the new qual. We traverse the old-quals list * repeatedly to transitively expand the exprs list. If at any point * we find we can reach the right-side expr of the new qual, we are - * done. We give up when we can't expand the equalexprs list any more. + * done. We give up when we can't expand the equalexprs list any + * more. */ equalexprs = makeList1(newleft); do @@ -945,7 +954,7 @@ check_mergejoinable(RestrictInfo *restrictinfo) * info fields in the restrictinfo. * * Currently, we support hashjoin for binary opclauses where - * the operator is a hashjoinable operator. The arguments can be + * the operator is a hashjoinable operator. The arguments can be * anything --- as long as there are no volatile functions in them. */ static void diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 8883310f66..4f0ede3452 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -14,7 +14,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planmain.c,v 1.76 2003/07/25 00:01:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planmain.c,v 1.77 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -33,7 +33,7 @@ * which may involve joins but not any fancier features. * * Since query_planner does not handle the toplevel processing (grouping, - * sorting, etc) it cannot select the best path by itself. It selects + * sorting, etc) it cannot select the best path by itself. It selects * two paths: the cheapest path that produces all the required tuples, * independent of any ordering considerations, and the cheapest path that * produces the expected fraction of the required tuples in the required @@ -84,7 +84,7 @@ query_planner(Query *root, List *tlist, double tuple_fraction, if (root->jointree->fromlist == NIL) { *cheapest_path = (Path *) create_result_path(NULL, NULL, - (List *) root->jointree->quals); + (List *) root->jointree->quals); *sorted_path = NULL; return; } @@ -125,9 +125,9 @@ query_planner(Query *root, List *tlist, double tuple_fraction, * relations. We also build lists of equijoined keys for pathkey * construction. * - * Note: all subplan nodes will have "flat" (var-only) tlists. - * This implies that all expression evaluations are done at the root of - * the plan tree. Once upon a time there was code to try to push + * Note: all subplan nodes will have "flat" (var-only) tlists. This + * implies that all expression evaluations are done at the root of the + * plan tree. Once upon a time there was code to try to push * expensive function calls down to lower plan nodes, but that's dead * code and has been for a long time... */ @@ -223,7 +223,8 @@ query_planner(Query *root, List *tlist, double tuple_fraction, } /* - * If we have constant quals, add a toplevel Result step to process them. + * If we have constant quals, add a toplevel Result step to process + * them. */ if (constant_quals) { diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 1896982f02..c2aec37470 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.157 2003/07/25 00:01:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.158 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,10 +45,10 @@ /* Expression kind codes for preprocess_expression */ #define EXPRKIND_QUAL 0 -#define EXPRKIND_TARGET 1 -#define EXPRKIND_RTFUNC 2 +#define EXPRKIND_TARGET 1 +#define EXPRKIND_RTFUNC 2 #define EXPRKIND_LIMIT 3 -#define EXPRKIND_ININFO 4 +#define EXPRKIND_ININFO 4 static Node *preprocess_expression(Query *parse, Node *expr, int kind); @@ -59,9 +59,9 @@ static bool hash_safe_grouping(Query *parse); static List *make_subplanTargetList(Query *parse, List *tlist, AttrNumber **groupColIdx, bool *need_tlist_eval); static void locate_grouping_columns(Query *parse, - List *tlist, - List *sub_tlist, - AttrNumber *groupColIdx); + List *tlist, + List *sub_tlist, + AttrNumber *groupColIdx); static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist); @@ -103,9 +103,9 @@ planner(Query *parse, bool isCursor, int cursorOptions) { /* * We have no real idea how many tuples the user will ultimately - * FETCH from a cursor, but it seems a good bet that he - * doesn't want 'em all. Optimize for 10% retrieval (you - * gotta better number? Should this be a SETtable parameter?) + * FETCH from a cursor, but it seems a good bet that he doesn't + * want 'em all. Optimize for 10% retrieval (you gotta better + * number? Should this be a SETtable parameter?) */ tuple_fraction = 0.10; } @@ -121,8 +121,8 @@ planner(Query *parse, bool isCursor, int cursorOptions) Assert(PlannerQueryLevel == 0); /* - * If creating a plan for a scrollable cursor, make sure it can - * run backwards on demand. Add a Material node at the top at need. + * If creating a plan for a scrollable cursor, make sure it can run + * backwards on demand. Add a Material node at the top at need. */ if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL)) { @@ -181,14 +181,14 @@ subquery_planner(Query *parse, double tuple_fraction) /* * Look for IN clauses at the top level of WHERE, and transform them - * into joins. Note that this step only handles IN clauses originally - * at top level of WHERE; if we pull up any subqueries in the next step, - * their INs are processed just before pulling them up. + * into joins. Note that this step only handles IN clauses originally + * at top level of WHERE; if we pull up any subqueries in the next + * step, their INs are processed just before pulling them up. */ parse->in_info_list = NIL; if (parse->hasSubLinks) parse->jointree->quals = pull_up_IN_clauses(parse, - parse->jointree->quals); + parse->jointree->quals); /* * Check to see if any subqueries in the rangetable can be merged into @@ -198,10 +198,11 @@ subquery_planner(Query *parse, double tuple_fraction) pull_up_subqueries(parse, (Node *) parse->jointree, false); /* - * Detect whether any rangetable entries are RTE_JOIN kind; if not, - * we can avoid the expense of doing flatten_join_alias_vars(). Also - * check for outer joins --- if none, we can skip reduce_outer_joins(). - * This must be done after we have done pull_up_subqueries, of course. + * Detect whether any rangetable entries are RTE_JOIN kind; if not, we + * can avoid the expense of doing flatten_join_alias_vars(). Also + * check for outer joins --- if none, we can skip + * reduce_outer_joins(). This must be done after we have done + * pull_up_subqueries, of course. */ parse->hasJoinRTEs = false; hasOuterJoins = false; @@ -283,19 +284,20 @@ subquery_planner(Query *parse, double tuple_fraction) parse->havingQual = (Node *) newHaving; /* - * If we have any outer joins, try to reduce them to plain inner joins. - * This step is most easily done after we've done expression preprocessing. + * If we have any outer joins, try to reduce them to plain inner + * joins. This step is most easily done after we've done expression + * preprocessing. */ if (hasOuterJoins) reduce_outer_joins(parse); /* - * See if we can simplify the jointree; opportunities for this may come - * from having pulled up subqueries, or from flattening explicit JOIN - * syntax. We must do this after flattening JOIN alias variables, since - * eliminating explicit JOIN nodes from the jointree will cause - * get_relids_for_join() to fail. But it should happen after - * reduce_outer_joins, anyway. + * See if we can simplify the jointree; opportunities for this may + * come from having pulled up subqueries, or from flattening explicit + * JOIN syntax. We must do this after flattening JOIN alias + * variables, since eliminating explicit JOIN nodes from the jointree + * will cause get_relids_for_join() to fail. But it should happen + * after reduce_outer_joins, anyway. */ parse->jointree = (FromExpr *) simplify_jointree(parse, (Node *) parse->jointree); @@ -318,26 +320,26 @@ subquery_planner(Query *parse, double tuple_fraction) */ if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1) { - Cost initplan_cost = 0; + Cost initplan_cost = 0; /* Prepare extParam/allParam sets for all nodes in tree */ SS_finalize_plan(plan, parse->rtable); /* - * SS_finalize_plan doesn't handle initPlans, so we have to manually - * attach them to the topmost plan node, and add their extParams to - * the topmost node's, too. + * SS_finalize_plan doesn't handle initPlans, so we have to + * manually attach them to the topmost plan node, and add their + * extParams to the topmost node's, too. * - * We also add the total_cost of each initPlan to the startup cost - * of the top node. This is a conservative overestimate, since in - * fact each initPlan might be executed later than plan startup, or - * even not at all. + * We also add the total_cost of each initPlan to the startup cost of + * the top node. This is a conservative overestimate, since in + * fact each initPlan might be executed later than plan startup, + * or even not at all. */ plan->initPlan = PlannerInitPlan; foreach(lst, plan->initPlan) { - SubPlan *initplan = (SubPlan *) lfirst(lst); + SubPlan *initplan = (SubPlan *) lfirst(lst); plan->extParam = bms_add_members(plan->extParam, initplan->plan->extParam); @@ -368,7 +370,8 @@ preprocess_expression(Query *parse, Node *expr, int kind) /* * If the query has any join RTEs, replace join alias variables with * base-relation variables. We must do this before sublink processing, - * else sublinks expanded out from join aliases wouldn't get processed. + * else sublinks expanded out from join aliases wouldn't get + * processed. */ if (parse->hasJoinRTEs) expr = flatten_join_alias_vars(parse, expr); @@ -403,8 +406,8 @@ preprocess_expression(Query *parse, Node *expr, int kind) expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL)); /* - * XXX do not insert anything here unless you have grokked the comments - * in SS_replace_correlation_vars ... + * XXX do not insert anything here unless you have grokked the + * comments in SS_replace_correlation_vars ... */ /* Replace uplevel vars with Param nodes */ @@ -498,20 +501,21 @@ inheritance_planner(Query *parse, List *inheritlist) /* Generate plan */ subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ ); subplans = lappend(subplans, subplan); + /* * It's possible that additional RTEs got added to the rangetable * due to expansion of inherited source tables (see allpaths.c). * If so, we must copy 'em back to the main parse tree's rtable. * - * XXX my goodness this is ugly. Really need to think about ways - * to rein in planner's habit of scribbling on its input. + * XXX my goodness this is ugly. Really need to think about ways to + * rein in planner's habit of scribbling on its input. */ subrtlength = length(subquery->rtable); if (subrtlength > mainrtlength) { - List *subrt = subquery->rtable; + List *subrt = subquery->rtable; - while (mainrtlength-- > 0) /* wish we had nthcdr() */ + while (mainrtlength-- > 0) /* wish we had nthcdr() */ subrt = lnext(subrt); parse->rtable = nconc(parse->rtable, subrt); mainrtlength = subrtlength; @@ -684,7 +688,7 @@ grouping_planner(Query *parse, double tuple_fraction) * from tlist if grouping or aggregation is needed. */ sub_tlist = make_subplanTargetList(parse, tlist, - &groupColIdx, &need_tlist_eval); + &groupColIdx, &need_tlist_eval); /* * Calculate pathkeys that represent grouping/ordering @@ -700,8 +704,8 @@ grouping_planner(Query *parse, double tuple_fraction) * Also, it's possible that optimization has eliminated all * aggregates, and we may as well check for that here. * - * Note: we do not attempt to detect duplicate aggregates here; - * a somewhat-overestimated count is okay for our present purposes. + * Note: we do not attempt to detect duplicate aggregates here; a + * somewhat-overestimated count is okay for our present purposes. */ if (parse->hasAggs) { @@ -892,8 +896,8 @@ grouping_planner(Query *parse, double tuple_fraction) &cheapest_path, &sorted_path); /* - * We couldn't canonicalize group_pathkeys and sort_pathkeys before - * running query_planner(), so do it now. + * We couldn't canonicalize group_pathkeys and sort_pathkeys + * before running query_planner(), so do it now. */ group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys); sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys); @@ -903,9 +907,9 @@ grouping_planner(Query *parse, double tuple_fraction) */ if (parse->groupClause) { - List *groupExprs; - double cheapest_path_rows; - int cheapest_path_width; + List *groupExprs; + double cheapest_path_rows; + int cheapest_path_width; /* * Beware in this section of the possibility that @@ -919,13 +923,13 @@ grouping_planner(Query *parse, double tuple_fraction) } else { - cheapest_path_rows = 1; /* assume non-set result */ - cheapest_path_width = 100; /* arbitrary */ + cheapest_path_rows = 1; /* assume non-set result */ + cheapest_path_width = 100; /* arbitrary */ } /* - * Always estimate the number of groups. We can't do this until - * after running query_planner(), either. + * Always estimate the number of groups. We can't do this + * until after running query_planner(), either. */ groupExprs = get_sortgrouplist_exprs(parse->groupClause, parse->targetList); @@ -936,12 +940,13 @@ grouping_planner(Query *parse, double tuple_fraction) numGroups = (long) Min(dNumGroups, (double) LONG_MAX); /* - * Check can't-do-it conditions, including whether the grouping - * operators are hashjoinable. + * Check can't-do-it conditions, including whether the + * grouping operators are hashjoinable. * * Executor doesn't support hashed aggregation with DISTINCT - * aggregates. (Doing so would imply storing *all* the input - * values in the hash table, which seems like a certain loser.) + * aggregates. (Doing so would imply storing *all* the input + * values in the hash table, which seems like a certain + * loser.) */ if (!enable_hashagg || !hash_safe_grouping(parse)) use_hashed_grouping = false; @@ -953,32 +958,30 @@ grouping_planner(Query *parse, double tuple_fraction) { /* * Use hashed grouping if (a) we think we can fit the - * hashtable into SortMem, *and* (b) the estimated cost - * is no more than doing it the other way. While avoiding + * hashtable into SortMem, *and* (b) the estimated cost is + * no more than doing it the other way. While avoiding * the need for sorted input is usually a win, the fact * that the output won't be sorted may be a loss; so we * need to do an actual cost comparison. * * In most cases we have no good way to estimate the size of - * the transition value needed by an aggregate; arbitrarily - * assume it is 100 bytes. Also set the overhead per hashtable - * entry at 64 bytes. + * the transition value needed by an aggregate; + * arbitrarily assume it is 100 bytes. Also set the + * overhead per hashtable entry at 64 bytes. */ - int hashentrysize = cheapest_path_width + 64 + numAggs * 100; + int hashentrysize = cheapest_path_width + 64 + numAggs * 100; if (hashentrysize * dNumGroups <= SortMem * 1024L) { /* * Okay, do the cost comparison. We need to consider - * cheapest_path + hashagg [+ final sort] - * versus either - * cheapest_path [+ sort] + group or agg [+ final sort] - * or - * presorted_path + group or agg [+ final sort] - * where brackets indicate a step that may not be needed. - * We assume query_planner() will have returned a - * presorted path only if it's a winner compared to - * cheapest_path for this purpose. + * cheapest_path + hashagg [+ final sort] versus + * either cheapest_path [+ sort] + group or agg [+ + * final sort] or presorted_path + group or agg [+ + * final sort] where brackets indicate a step that may + * not be needed. We assume query_planner() will have + * returned a presorted path only if it's a winner + * compared to cheapest_path for this purpose. * * These path variables are dummies that just hold cost * fields; we don't make actual Paths for these steps. @@ -1065,9 +1068,9 @@ grouping_planner(Query *parse, double tuple_fraction) /* * Select the best path and create a plan to execute it. * - * If we are doing hashed grouping, we will always read all the - * input tuples, so use the cheapest-total path. Otherwise, - * trust query_planner's decision about which to use. + * If we are doing hashed grouping, we will always read all the input + * tuples, so use the cheapest-total path. Otherwise, trust + * query_planner's decision about which to use. */ if (sorted_path && !use_hashed_grouping) { @@ -1081,19 +1084,19 @@ grouping_planner(Query *parse, double tuple_fraction) } /* - * create_plan() returns a plan with just a "flat" tlist of required - * Vars. Usually we need to insert the sub_tlist as the tlist of the - * top plan node. However, we can skip that if we determined that - * whatever query_planner chose to return will be good enough. + * create_plan() returns a plan with just a "flat" tlist of + * required Vars. Usually we need to insert the sub_tlist as the + * tlist of the top plan node. However, we can skip that if we + * determined that whatever query_planner chose to return will be + * good enough. */ if (need_tlist_eval) { /* * If the top-level plan node is one that cannot do expression - * evaluation, we must insert a Result node to project the desired - * tlist. - * Currently, the only plan node we might see here that falls into - * that category is Append. + * evaluation, we must insert a Result node to project the + * desired tlist. Currently, the only plan node we might see + * here that falls into that category is Append. */ if (IsA(result_plan, Append)) { @@ -1108,23 +1111,25 @@ grouping_planner(Query *parse, double tuple_fraction) */ result_plan->targetlist = sub_tlist; } + /* * Also, account for the cost of evaluation of the sub_tlist. * * Up to now, we have only been dealing with "flat" tlists, * containing just Vars. So their evaluation cost is zero * according to the model used by cost_qual_eval() (or if you - * prefer, the cost is factored into cpu_tuple_cost). Thus we can - * avoid accounting for tlist cost throughout query_planner() and - * subroutines. But now we've inserted a tlist that might contain - * actual operators, sub-selects, etc --- so we'd better account - * for its cost. + * prefer, the cost is factored into cpu_tuple_cost). Thus we + * can avoid accounting for tlist cost throughout + * query_planner() and subroutines. But now we've inserted a + * tlist that might contain actual operators, sub-selects, etc + * --- so we'd better account for its cost. * - * Below this point, any tlist eval cost for added-on nodes should - * be accounted for as we create those nodes. Presently, of the - * node types we can add on, only Agg and Group project new tlists - * (the rest just copy their input tuples) --- so make_agg() and - * make_group() are responsible for computing the added cost. + * Below this point, any tlist eval cost for added-on nodes + * should be accounted for as we create those nodes. + * Presently, of the node types we can add on, only Agg and + * Group project new tlists (the rest just copy their input + * tuples) --- so make_agg() and make_group() are responsible + * for computing the added cost. */ cost_qual_eval(&tlist_cost, sub_tlist); result_plan->startup_cost += tlist_cost.startup; @@ -1135,8 +1140,8 @@ grouping_planner(Query *parse, double tuple_fraction) { /* * Since we're using query_planner's tlist and not the one - * make_subplanTargetList calculated, we have to refigure - * any grouping-column indexes make_subplanTargetList computed. + * make_subplanTargetList calculated, we have to refigure any + * grouping-column indexes make_subplanTargetList computed. */ locate_grouping_columns(parse, tlist, result_plan->targetlist, groupColIdx); @@ -1180,6 +1185,7 @@ grouping_planner(Query *parse, double tuple_fraction) current_pathkeys = group_pathkeys; } aggstrategy = AGG_SORTED; + /* * The AGG node will not change the sort ordering of its * groups, so current_pathkeys describes the result too. @@ -1205,7 +1211,8 @@ grouping_planner(Query *parse, double tuple_fraction) else { /* - * If there are no Aggs, we shouldn't have any HAVING qual anymore + * If there are no Aggs, we shouldn't have any HAVING qual + * anymore */ Assert(parse->havingQual == NULL); @@ -1216,8 +1223,8 @@ grouping_planner(Query *parse, double tuple_fraction) if (parse->groupClause) { /* - * Add an explicit sort if we couldn't make the path come out - * the way the GROUP node needs it. + * Add an explicit sort if we couldn't make the path come + * out the way the GROUP node needs it. */ if (!pathkeys_contained_in(group_pathkeys, current_pathkeys)) { @@ -1238,7 +1245,7 @@ grouping_planner(Query *parse, double tuple_fraction) /* The Group node won't change sort ordering */ } } - } /* end of if (setOperations) */ + } /* end of if (setOperations) */ /* * If we were not able to make the plan come out in the right order, @@ -1264,6 +1271,7 @@ grouping_planner(Query *parse, double tuple_fraction) { result_plan = (Plan *) make_unique(tlist, result_plan, parse->distinctClause); + /* * If there was grouping or aggregation, leave plan_rows as-is * (ie, assume the result was already mostly unique). If not, @@ -1272,13 +1280,13 @@ grouping_planner(Query *parse, double tuple_fraction) */ if (!parse->groupClause && !parse->hasAggs) { - List *distinctExprs; + List *distinctExprs; distinctExprs = get_sortgrouplist_exprs(parse->distinctClause, parse->targetList); result_plan->plan_rows = estimate_num_groups(parse, distinctExprs, - result_plan->plan_rows); + result_plan->plan_rows); } } @@ -1443,7 +1451,7 @@ make_subplanTargetList(Query *parse, false), (Expr *) groupexpr); sub_tlist = lappend(sub_tlist, te); - *need_tlist_eval = true; /* it's not flat anymore */ + *need_tlist_eval = true; /* it's not flat anymore */ } /* and save its resno */ @@ -1459,7 +1467,7 @@ make_subplanTargetList(Query *parse, * Locate grouping columns in the tlist chosen by query_planner. * * This is only needed if we don't use the sub_tlist chosen by - * make_subplanTargetList. We have to forget the column indexes found + * make_subplanTargetList. We have to forget the column indexes found * by that routine and re-locate the grouping vars in the real sub_tlist. */ static void @@ -1528,7 +1536,7 @@ postprocess_setop_tlist(List *new_tlist, List *orig_tlist) Assert(orig_tlist != NIL); orig_tle = (TargetEntry *) lfirst(orig_tlist); orig_tlist = lnext(orig_tlist); - if (orig_tle->resdom->resjunk) /* should not happen */ + if (orig_tle->resdom->resjunk) /* should not happen */ elog(ERROR, "resjunk output columns are not implemented"); Assert(new_tle->resdom->resno == orig_tle->resdom->resno); Assert(new_tle->resdom->restype == orig_tle->resdom->restype); diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 18395be022..91396575b3 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/setrefs.c,v 1.94 2003/07/25 00:01:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/setrefs.c,v 1.95 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -46,11 +46,11 @@ static void set_join_references(Join *join, List *rtable); static void set_uppernode_references(Plan *plan, Index subvarno); static bool targetlist_has_non_vars(List *tlist); static List *join_references(List *clauses, - List *rtable, - List *outer_tlist, - List *inner_tlist, - Index acceptable_rel, - bool tlists_have_non_vars); + List *rtable, + List *outer_tlist, + List *inner_tlist, + Index acceptable_rel, + bool tlists_have_non_vars); static Node *join_references_mutator(Node *node, join_references_context *context); static Node *replace_vars_with_subplan_refs(Node *node, @@ -60,7 +60,7 @@ static Node *replace_vars_with_subplan_refs(Node *node, static Node *replace_vars_with_subplan_refs_mutator(Node *node, replace_vars_with_subplan_refs_context *context); static bool fix_opfuncids_walker(Node *node, void *context); -static void set_sa_opfuncid(ScalarArrayOpExpr *opexpr); +static void set_sa_opfuncid(ScalarArrayOpExpr * opexpr); /***************************************************************************** @@ -167,12 +167,13 @@ set_plan_references(Plan *plan, List *rtable) (Node *) ((HashJoin *) plan)->hashclauses); break; case T_Hash: + /* * Hash does not evaluate its targetlist or quals, so don't - * touch those (see comments below). But we do need to fix its - * hashkeys. The hashkeys are a little bizarre because they - * need to match the hashclauses of the parent HashJoin node, - * so we use join_references to fix them. + * touch those (see comments below). But we do need to fix + * its hashkeys. The hashkeys are a little bizarre because + * they need to match the hashclauses of the parent HashJoin + * node, so we use join_references to fix them. */ ((Hash *) plan)->hashkeys = join_references(((Hash *) plan)->hashkeys, @@ -180,7 +181,7 @@ set_plan_references(Plan *plan, List *rtable) NIL, plan->lefttree->targetlist, (Index) 0, - targetlist_has_non_vars(plan->lefttree->targetlist)); + targetlist_has_non_vars(plan->lefttree->targetlist)); fix_expr_references(plan, (Node *) ((Hash *) plan)->hashkeys); break; @@ -196,9 +197,9 @@ set_plan_references(Plan *plan, List *rtable) * unmodified input tuples). The optimizer is lazy about * creating really valid targetlists for them. Best to just * leave the targetlist alone. In particular, we do not want - * to process subplans for them, since we will likely end - * up reprocessing subplans that also appear in lower levels - * of the plan tree! + * to process subplans for them, since we will likely end up + * reprocessing subplans that also appear in lower levels of + * the plan tree! */ break; case T_Agg: @@ -253,7 +254,7 @@ set_plan_references(Plan *plan, List *rtable) foreach(pl, plan->initPlan) { - SubPlan *sp = (SubPlan *) lfirst(pl); + SubPlan *sp = (SubPlan *) lfirst(pl); Assert(IsA(sp, SubPlan)); set_plan_references(sp->plan, sp->rtable); @@ -284,14 +285,14 @@ fix_expr_references_walker(Node *node, void *context) if (IsA(node, OpExpr)) set_opfuncid((OpExpr *) node); else if (IsA(node, DistinctExpr)) - set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ + set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ else if (IsA(node, ScalarArrayOpExpr)) set_sa_opfuncid((ScalarArrayOpExpr *) node); else if (IsA(node, NullIfExpr)) - set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ + set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ else if (IsA(node, SubPlan)) { - SubPlan *sp = (SubPlan *) node; + SubPlan *sp = (SubPlan *) node; set_plan_references(sp->plan, sp->rtable); } @@ -350,10 +351,10 @@ set_join_references(Join *join, List *rtable) if (IsA(inner_plan, IndexScan)) { /* - * An index is being used to reduce the number of tuples scanned - * in the inner relation. If there are join clauses being used - * with the index, we must update their outer-rel var nodes to - * refer to the outer side of the join. + * An index is being used to reduce the number of tuples + * scanned in the inner relation. If there are join clauses + * being used with the index, we must update their outer-rel + * var nodes to refer to the outer side of the join. */ IndexScan *innerscan = (IndexScan *) inner_plan; List *indxqualorig = innerscan->indxqualorig; @@ -369,17 +370,18 @@ set_join_references(Join *join, List *rtable) outer_tlist, NIL, innerrel, - tlists_have_non_vars); + tlists_have_non_vars); innerscan->indxqual = join_references(innerscan->indxqual, rtable, outer_tlist, NIL, innerrel, - tlists_have_non_vars); + tlists_have_non_vars); + /* - * We must fix the inner qpqual too, if it has join clauses - * (this could happen if the index is lossy: some indxquals - * may get rechecked as qpquals). + * We must fix the inner qpqual too, if it has join + * clauses (this could happen if the index is lossy: some + * indxquals may get rechecked as qpquals). */ if (NumRelids((Node *) inner_plan->qual) > 1) inner_plan->qual = join_references(inner_plan->qual, @@ -387,7 +389,7 @@ set_join_references(Join *join, List *rtable) outer_tlist, NIL, innerrel, - tlists_have_non_vars); + tlists_have_non_vars); } } else if (IsA(inner_plan, TidScan)) @@ -470,8 +472,8 @@ set_uppernode_references(Plan *plan, Index subvarno) subplan_targetlist, tlist_has_non_vars); output_targetlist = lappend(output_targetlist, - makeTargetEntry(tle->resdom, - (Expr *) newexpr)); + makeTargetEntry(tle->resdom, + (Expr *) newexpr)); } plan->targetlist = output_targetlist; @@ -491,7 +493,7 @@ set_uppernode_references(Plan *plan, Index subvarno) static bool targetlist_has_non_vars(List *tlist) { - List *l; + List *l; foreach(l, tlist) { @@ -740,11 +742,11 @@ fix_opfuncids_walker(Node *node, void *context) if (IsA(node, OpExpr)) set_opfuncid((OpExpr *) node); else if (IsA(node, DistinctExpr)) - set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ + set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ else if (IsA(node, ScalarArrayOpExpr)) set_sa_opfuncid((ScalarArrayOpExpr *) node); else if (IsA(node, NullIfExpr)) - set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ + set_opfuncid((OpExpr *) node); /* rely on struct equivalence */ return expression_tree_walker(node, fix_opfuncids_walker, context); } @@ -757,7 +759,7 @@ fix_opfuncids_walker(Node *node, void *context) * DistinctExpr and NullIfExpr nodes. */ void -set_opfuncid(OpExpr *opexpr) +set_opfuncid(OpExpr * opexpr) { if (opexpr->opfuncid == InvalidOid) opexpr->opfuncid = get_opcode(opexpr->opno); @@ -768,7 +770,7 @@ set_opfuncid(OpExpr *opexpr) * As above, for ScalarArrayOpExpr nodes. */ static void -set_sa_opfuncid(ScalarArrayOpExpr *opexpr) +set_sa_opfuncid(ScalarArrayOpExpr * opexpr) { if (opexpr->opfuncid == InvalidOid) opexpr->opfuncid = get_opcode(opexpr->opno); diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c index 780bed6c2b..154804d3d0 100644 --- a/src/backend/optimizer/plan/subselect.c +++ b/src/backend/optimizer/plan/subselect.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/subselect.c,v 1.79 2003/07/25 00:01:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/subselect.c,v 1.80 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -71,26 +71,26 @@ typedef struct PlannerParamItem { Node *item; /* the Var, Aggref, or Param */ Index abslevel; /* its absolute query level */ -} PlannerParamItem; +} PlannerParamItem; typedef struct finalize_primnode_context { - Bitmapset *paramids; /* Set of PARAM_EXEC paramids found */ - Bitmapset *outer_params; /* Set of accessible outer paramids */ -} finalize_primnode_context; + Bitmapset *paramids; /* Set of PARAM_EXEC paramids found */ + Bitmapset *outer_params; /* Set of accessible outer paramids */ +} finalize_primnode_context; static List *convert_sublink_opers(List *lefthand, List *operOids, - List *targetlist, int rtindex, - List **righthandIds); + List *targetlist, int rtindex, + List **righthandIds); static bool subplan_is_hashable(SubLink *slink, SubPlan *node); static Node *replace_correlation_vars_mutator(Node *node, void *context); static Node *process_sublinks_mutator(Node *node, bool *isTopQual); static Bitmapset *finalize_plan(Plan *plan, List *rtable, - Bitmapset *outer_params, - Bitmapset *valid_params); -static bool finalize_primnode(Node *node, finalize_primnode_context *context); + Bitmapset * outer_params, + Bitmapset * valid_params); +static bool finalize_primnode(Node *node, finalize_primnode_context * context); /* @@ -125,7 +125,7 @@ replace_outer_var(Var *var) pitem = (PlannerParamItem *) lfirst(ppl); if (pitem->abslevel == abslevel && IsA(pitem->item, Var)) { - Var *pvar = (Var *) pitem->item; + Var *pvar = (Var *) pitem->item; if (pvar->varno == var->varno && pvar->varattno == var->varattno && @@ -177,7 +177,7 @@ replace_outer_agg(Aggref *agg) * Just make a new slot every time. */ agg = (Aggref *) copyObject(agg); - IncrementVarSublevelsUp((Node *) agg, - ((int) agg->agglevelsup), 0); + IncrementVarSublevelsUp((Node *) agg, -((int) agg->agglevelsup), 0); Assert(agg->agglevelsup == 0); pitem = (PlannerParamItem *) palloc(sizeof(PlannerParamItem)); @@ -238,7 +238,7 @@ generate_new_param(Oid paramtype, int32 paramtypmod) static Node * make_subplan(SubLink *slink, List *lefthand, bool isTopQual) { - SubPlan *node = makeNode(SubPlan); + SubPlan *node = makeNode(SubPlan); Query *subquery = (Query *) (slink->subselect); double tuple_fraction; Plan *plan; @@ -268,8 +268,8 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) * in path/costsize.c. * * XXX If an ALL/ANY subplan is uncorrelated, we may decide to hash or - * materialize its result below. In that case it would've been better to - * specify full retrieval. At present, however, we can only detect + * materialize its result below. In that case it would've been better + * to specify full retrieval. At present, however, we can only detect * correlation or lack of it after we've made the subplan :-(. Perhaps * detection of correlation should be done as a separate step. * Meanwhile, we don't want to be too optimistic about the percentage @@ -323,12 +323,13 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) bms_free(tmpset); /* - * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY, or - * MULTIEXPR types can be used as initPlans. For EXISTS, EXPR, or ARRAY, - * we just produce a Param referring to the result of evaluating the - * initPlan. For MULTIEXPR, we must build an AND or OR-clause of the - * individual comparison operators, using the appropriate lefthand - * side expressions and Params for the initPlan's target items. + * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY, + * or MULTIEXPR types can be used as initPlans. For EXISTS, EXPR, or + * ARRAY, we just produce a Param referring to the result of + * evaluating the initPlan. For MULTIEXPR, we must build an AND or + * OR-clause of the individual comparison operators, using the + * appropriate lefthand side expressions and Params for the initPlan's + * target items. */ if (node->parParam == NIL && slink->subLinkType == EXISTS_SUBLINK) { @@ -368,7 +369,7 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) } else if (node->parParam == NIL && slink->subLinkType == MULTIEXPR_SUBLINK) { - List *exprs; + List *exprs; /* Convert the lefthand exprs and oper OIDs into executable exprs */ exprs = convert_sublink_opers(lefthand, @@ -378,6 +379,7 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) &node->paramIds); node->setParam = listCopy(node->paramIds); PlannerInitPlan = lappend(PlannerInitPlan, node); + /* * The executable expressions are returned to become part of the * outer plan's expression tree; they are not kept in the initplan @@ -402,15 +404,16 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) */ if (subplan_is_hashable(slink, node)) node->useHashTable = true; + /* - * Otherwise, we have the option to tack a MATERIAL node onto the top - * of the subplan, to reduce the cost of reading it repeatedly. This - * is pointless for a direct-correlated subplan, since we'd have to - * recompute its results each time anyway. For uncorrelated/undirect - * correlated subplans, we add MATERIAL if the subplan's top plan node - * is anything more complicated than a plain sequential scan, and we - * do it even for seqscan if the qual appears selective enough to - * eliminate many tuples. + * Otherwise, we have the option to tack a MATERIAL node onto the + * top of the subplan, to reduce the cost of reading it + * repeatedly. This is pointless for a direct-correlated subplan, + * since we'd have to recompute its results each time anyway. For + * uncorrelated/undirect correlated subplans, we add MATERIAL if + * the subplan's top plan node is anything more complicated than a + * plain sequential scan, and we do it even for seqscan if the + * qual appears selective enough to eliminate many tuples. */ else if (node->parParam == NIL) { @@ -448,9 +451,7 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) break; } if (use_material) - { node->plan = plan = materialize_finished_plan(plan); - } } /* Convert the lefthand exprs and oper OIDs into executable exprs */ @@ -470,7 +471,7 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) /* * The Var or Aggref has already been adjusted to have the - * correct varlevelsup or agglevelsup. We probably don't even + * correct varlevelsup or agglevelsup. We probably don't even * need to copy it again, but be safe. */ args = lappend(args, copyObject(pitem->item)); @@ -485,14 +486,14 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual) /* * convert_sublink_opers: given a lefthand-expressions list and a list of - * operator OIDs, build a list of actually executable expressions. The + * operator OIDs, build a list of actually executable expressions. The * righthand sides of the expressions are Params or Vars representing the * results of the sub-select. * * If rtindex is 0, we build Params to represent the sub-select outputs. * The paramids of the Params created are returned in the *righthandIds list. * - * If rtindex is not 0, we build Vars using that rtindex as varno. The + * If rtindex is not 0, we build Vars using that rtindex as varno. The * Vars themselves are returned in *righthandIds (this is a bit of a type * cheat, but we can get away with it). */ @@ -549,10 +550,10 @@ convert_sublink_opers(List *lefthand, List *operOids, /* * Make the expression node. * - * Note: we use make_op_expr in case runtime type conversion - * function calls must be inserted for this operator! (But we - * are not expecting to have to resolve unknown Params, so - * it's okay to pass a null pstate.) + * Note: we use make_op_expr in case runtime type conversion function + * calls must be inserted for this operator! (But we are not + * expecting to have to resolve unknown Params, so it's okay to + * pass a null pstate.) */ result = lappend(result, make_op_expr(NULL, @@ -584,9 +585,9 @@ subplan_is_hashable(SubLink *slink, SubPlan *node) List *opids; /* - * The sublink type must be "= ANY" --- that is, an IN operator. - * (We require the operator name to be unqualified, which may be - * overly paranoid, or may not be.) XXX since we also check that the + * The sublink type must be "= ANY" --- that is, an IN operator. (We + * require the operator name to be unqualified, which may be overly + * paranoid, or may not be.) XXX since we also check that the * operators are hashable, the test on operator name may be redundant? */ if (slink->subLinkType != ANY_SUBLINK) @@ -594,33 +595,37 @@ subplan_is_hashable(SubLink *slink, SubPlan *node) if (length(slink->operName) != 1 || strcmp(strVal(lfirst(slink->operName)), "=") != 0) return false; + /* * The subplan must not have any direct correlation vars --- else we'd - * have to recompute its output each time, so that the hashtable wouldn't - * gain anything. + * have to recompute its output each time, so that the hashtable + * wouldn't gain anything. */ if (node->parParam != NIL) return false; + /* - * The estimated size of the subquery result must fit in SortMem. - * (XXX what about hashtable overhead?) + * The estimated size of the subquery result must fit in SortMem. (XXX + * what about hashtable overhead?) */ subquery_size = node->plan->plan_rows * (MAXALIGN(node->plan->plan_width) + MAXALIGN(sizeof(HeapTupleData))); if (subquery_size > SortMem * 1024L) return false; + /* - * The combining operators must be hashable, strict, and self-commutative. - * The need for hashability is obvious, since we want to use hashing. - * Without strictness, behavior in the presence of nulls is too - * unpredictable. (We actually must assume even more than plain - * strictness, see nodeSubplan.c for details.) And commutativity ensures - * that the left and right datatypes are the same; this allows us to - * assume that the combining operators are equality for the righthand - * datatype, so that they can be used to compare righthand tuples as - * well as comparing lefthand to righthand tuples. (This last restriction - * could be relaxed by using two different sets of operators with the - * hash table, but there is no obvious usefulness to that at present.) + * The combining operators must be hashable, strict, and + * self-commutative. The need for hashability is obvious, since we + * want to use hashing. Without strictness, behavior in the presence + * of nulls is too unpredictable. (We actually must assume even more + * than plain strictness, see nodeSubplan.c for details.) And + * commutativity ensures that the left and right datatypes are the + * same; this allows us to assume that the combining operators are + * equality for the righthand datatype, so that they can be used to + * compare righthand tuples as well as comparing lefthand to righthand + * tuples. (This last restriction could be relaxed by using two + * different sets of operators with the hash table, but there is no + * obvious usefulness to that at present.) */ foreach(opids, slink->operOids) { @@ -665,25 +670,27 @@ convert_IN_to_join(Query *parse, SubLink *sublink) int rtindex; RangeTblEntry *rte; RangeTblRef *rtr; - InClauseInfo *ininfo; + InClauseInfo *ininfo; List *exprs; /* - * The sublink type must be "= ANY" --- that is, an IN operator. - * (We require the operator name to be unqualified, which may be - * overly paranoid, or may not be.) + * The sublink type must be "= ANY" --- that is, an IN operator. (We + * require the operator name to be unqualified, which may be overly + * paranoid, or may not be.) */ if (sublink->subLinkType != ANY_SUBLINK) return NULL; if (length(sublink->operName) != 1 || strcmp(strVal(lfirst(sublink->operName)), "=") != 0) return NULL; + /* * The sub-select must not refer to any Vars of the parent query. * (Vars of higher levels should be okay, though.) */ if (contain_vars_of_level((Node *) subselect, 1)) return NULL; + /* * The left-hand expressions must contain some Vars of the current * query, else it's not gonna be a join. @@ -691,6 +698,7 @@ convert_IN_to_join(Query *parse, SubLink *sublink) left_varnos = pull_varnos((Node *) sublink->lefthand); if (bms_is_empty(left_varnos)) return NULL; + /* * The left-hand expressions mustn't be volatile. (Perhaps we should * test the combining operators, too? We'd only need to point the @@ -698,13 +706,14 @@ convert_IN_to_join(Query *parse, SubLink *sublink) */ if (contain_volatile_functions((Node *) sublink->lefthand)) return NULL; + /* * Okay, pull up the sub-select into top range table and jointree. * * We rely here on the assumption that the outer query has no references * to the inner (necessarily true, other than the Vars that we build - * below). Therefore this is a lot easier than what pull_up_subqueries - * has to go through. + * below). Therefore this is a lot easier than what + * pull_up_subqueries has to go through. */ rte = addRangeTableEntryForSubquery(NULL, subselect, @@ -715,6 +724,7 @@ convert_IN_to_join(Query *parse, SubLink *sublink) rtr = makeNode(RangeTblRef); rtr->rtindex = rtindex; parse->jointree->fromlist = lappend(parse->jointree->fromlist, rtr); + /* * Now build the InClauseInfo node. */ @@ -722,6 +732,7 @@ convert_IN_to_join(Query *parse, SubLink *sublink) ininfo->lefthand = left_varnos; ininfo->righthand = bms_make_singleton(rtindex); parse->in_info_list = lcons(ininfo, parse->in_info_list); + /* * Build the result qual expressions. As a side effect, * ininfo->sub_targetlist is filled with a list of the Vars @@ -744,9 +755,9 @@ convert_IN_to_join(Query *parse, SubLink *sublink) * Since we do not recurse into the arguments of uplevel aggregates, they will * get copied to the appropriate subplan args list in the parent query with * uplevel vars not replaced by Params, but only adjusted in level (see - * replace_outer_agg). That's exactly what we want for the vars of the parent + * replace_outer_agg). That's exactly what we want for the vars of the parent * level --- but if an aggregate's argument contains any further-up variables, - * they have to be replaced with Params in their turn. That will happen when + * they have to be replaced with Params in their turn. That will happen when * the parent level runs SS_replace_correlation_vars. Therefore it must do * so after expanding its sublinks to subplans. And we don't want any steps * in between, else those steps would never get applied to the aggregate @@ -796,7 +807,7 @@ SS_process_sublinks(Node *expr, bool isQual) static Node * process_sublinks_mutator(Node *node, bool *isTopQual) { - bool locTopQual; + bool locTopQual; if (node == NULL) return NULL; @@ -806,11 +817,13 @@ process_sublinks_mutator(Node *node, bool *isTopQual) List *lefthand; /* - * First, recursively process the lefthand-side expressions, if any. + * First, recursively process the lefthand-side expressions, if + * any. */ locTopQual = false; lefthand = (List *) process_sublinks_mutator((Node *) sublink->lefthand, &locTopQual); + /* * Now build the SubPlan node and make the expr to return. */ @@ -818,9 +831,9 @@ process_sublinks_mutator(Node *node, bool *isTopQual) } /* - * We should never see a SubPlan expression in the input (since this is - * the very routine that creates 'em to begin with). We shouldn't find - * ourselves invoked directly on a Query, either. + * We should never see a SubPlan expression in the input (since this + * is the very routine that creates 'em to begin with). We shouldn't + * find ourselves invoked directly on a Query, either. */ Assert(!is_subplan(node)); Assert(!IsA(node, Query)); @@ -854,9 +867,9 @@ SS_finalize_plan(Plan *plan, List *rtable) List *lst; /* - * First, scan the param list to discover the sets of params that - * are available from outer query levels and my own query level. - * We do this once to save time in the per-plan recursion steps. + * First, scan the param list to discover the sets of params that are + * available from outer query levels and my own query level. We do + * this once to save time in the per-plan recursion steps. */ paramid = 0; foreach(lst, PlannerParamList) @@ -896,7 +909,7 @@ SS_finalize_plan(Plan *plan, List *rtable) */ static Bitmapset * finalize_plan(Plan *plan, List *rtable, - Bitmapset *outer_params, Bitmapset *valid_params) + Bitmapset * outer_params, Bitmapset * valid_params) { finalize_primnode_context context; List *lst; @@ -1038,8 +1051,8 @@ finalize_plan(Plan *plan, List *rtable, plan->allParam = context.paramids; /* - * For speed at execution time, make sure extParam/allParam are actually - * NULL if they are empty sets. + * For speed at execution time, make sure extParam/allParam are + * actually NULL if they are empty sets. */ if (bms_is_empty(plan->extParam)) { @@ -1060,7 +1073,7 @@ finalize_plan(Plan *plan, List *rtable, * expression tree to the result set. */ static bool -finalize_primnode(Node *node, finalize_primnode_context *context) +finalize_primnode(Node *node, finalize_primnode_context * context) { if (node == NULL) return false; @@ -1076,12 +1089,12 @@ finalize_primnode(Node *node, finalize_primnode_context *context) } if (is_subplan(node)) { - SubPlan *subplan = (SubPlan *) node; + SubPlan *subplan = (SubPlan *) node; /* Add outer-level params needed by the subplan to paramids */ context->paramids = bms_join(context->paramids, - bms_intersect(subplan->plan->extParam, - context->outer_params)); + bms_intersect(subplan->plan->extParam, + context->outer_params)); /* fall through to recurse into subplan args */ } return expression_tree_walker(node, finalize_primnode, diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 6bddf04206..25617206d4 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -16,7 +16,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.8 2003/07/25 00:01:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.9 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -32,28 +32,28 @@ /* These parameters are set by GUC */ -int from_collapse_limit; -int join_collapse_limit; +int from_collapse_limit; +int join_collapse_limit; typedef struct reduce_outer_joins_state { Relids relids; /* base relids within this subtree */ - bool contains_outer; /* does subtree contain outer join(s)? */ + bool contains_outer; /* does subtree contain outer join(s)? */ List *sub_states; /* List of states for subtree components */ -} reduce_outer_joins_state; +} reduce_outer_joins_state; static bool is_simple_subquery(Query *subquery); static bool has_nullable_targetlist(Query *subquery); static void resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist); static reduce_outer_joins_state *reduce_outer_joins_pass1(Node *jtnode); static void reduce_outer_joins_pass2(Node *jtnode, - reduce_outer_joins_state *state, - Query *parse, - Relids nonnullable_rels); + reduce_outer_joins_state * state, + Query *parse, + Relids nonnullable_rels); static Relids find_nonnullable_rels(Node *node, bool top_level); static void fix_in_clause_relids(List *in_info_list, int varno, - Relids subrelids); + Relids subrelids); static Node *find_jointree_node_for_rel(Node *jtnode, int relid); @@ -84,7 +84,7 @@ pull_up_IN_clauses(Query *parse, Node *node) return NULL; if (IsA(node, SubLink)) { - SubLink *sublink = (SubLink *) node; + SubLink *sublink = (SubLink *) node; Node *subst; /* Is it a convertible IN clause? If not, return it as-is */ @@ -95,12 +95,12 @@ pull_up_IN_clauses(Query *parse, Node *node) } if (and_clause(node)) { - List *newclauses = NIL; - List *oldclauses; + List *newclauses = NIL; + List *oldclauses; foreach(oldclauses, ((BoolExpr *) node)->args) { - Node *oldclause = lfirst(oldclauses); + Node *oldclause = lfirst(oldclauses); newclauses = lappend(newclauses, pull_up_IN_clauses(parse, @@ -172,22 +172,22 @@ pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join) */ if (subquery->hasSubLinks) subquery->jointree->quals = pull_up_IN_clauses(subquery, - subquery->jointree->quals); + subquery->jointree->quals); /* - * Now, recursively pull up the subquery's subqueries, so - * that this routine's processing is complete for its jointree - * and rangetable. NB: if the same subquery is referenced - * from multiple jointree items (which can't happen normally, - * but might after rule rewriting), then we will invoke this + * Now, recursively pull up the subquery's subqueries, so that + * this routine's processing is complete for its jointree and + * rangetable. NB: if the same subquery is referenced from + * multiple jointree items (which can't happen normally, but + * might after rule rewriting), then we will invoke this * processing multiple times on that subquery. OK because * nothing will happen after the first time. We do have to be * careful to copy everything we pull up, however, or risk * having chunks of structure multiply linked. * * Note: 'false' is correct here even if we are within an outer - * join in the upper query; the lower query starts with a clean - * slate for outer-join semantics. + * join in the upper query; the lower query starts with a + * clean slate for outer-join semantics. */ subquery->jointree = (FromExpr *) pull_up_subqueries(subquery, (Node *) subquery->jointree, @@ -207,8 +207,8 @@ pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join) OffsetVarNodes((Node *) subquery, rtoffset, 0); /* - * Upper-level vars in subquery are now one level closer to their - * parent than before. + * Upper-level vars in subquery are now one level closer to + * their parent than before. */ IncrementVarSublevelsUp((Node *) subquery, -1, 1); @@ -257,13 +257,14 @@ pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join) parse->rowMarks = nconc(parse->rowMarks, subquery->rowMarks); /* - * We also have to fix the relid sets of any parent InClauseInfo - * nodes. (This could perhaps be done by ResolveNew, but it - * would clutter that routine's API unreasonably.) + * We also have to fix the relid sets of any parent + * InClauseInfo nodes. (This could perhaps be done by + * ResolveNew, but it would clutter that routine's API + * unreasonably.) */ if (parse->in_info_list) { - Relids subrelids; + Relids subrelids; subrelids = get_relids_in_jointree((Node *) subquery->jointree); fix_in_clause_relids(parse->in_info_list, varno, subrelids); @@ -513,14 +514,14 @@ reduce_outer_joins(Query *parse) reduce_outer_joins_state *state; /* - * To avoid doing strictness checks on more quals than necessary, - * we want to stop descending the jointree as soon as there are no - * outer joins below our current point. This consideration forces - * a two-pass process. The first pass gathers information about which + * To avoid doing strictness checks on more quals than necessary, we + * want to stop descending the jointree as soon as there are no outer + * joins below our current point. This consideration forces a + * two-pass process. The first pass gathers information about which * base rels appear below each side of each join clause, and about - * whether there are outer join(s) below each side of each join clause. - * The second pass examines qual clauses and changes join types as - * it descends the tree. + * whether there are outer join(s) below each side of each join + * clause. The second pass examines qual clauses and changes join + * types as it descends the tree. */ state = reduce_outer_joins_pass1((Node *) parse->jointree); @@ -608,7 +609,7 @@ reduce_outer_joins_pass1(Node *jtnode) */ static void reduce_outer_joins_pass2(Node *jtnode, - reduce_outer_joins_state *state, + reduce_outer_joins_state * state, Query *parse, Relids nonnullable_rels) { @@ -619,9 +620,7 @@ reduce_outer_joins_pass2(Node *jtnode, if (jtnode == NULL) elog(ERROR, "reached empty jointree"); if (IsA(jtnode, RangeTblRef)) - { elog(ERROR, "reached base rel"); - } else if (IsA(jtnode, FromExpr)) { FromExpr *f = (FromExpr *) jtnode; @@ -701,10 +700,11 @@ reduce_outer_joins_pass2(Node *jtnode, /* * If this join is (now) inner, we can add any nonnullability * constraints its quals provide to those we got from above. - * But if it is outer, we can only pass down the local constraints - * into the nullable side, because an outer join never eliminates - * any rows from its non-nullable side. If it's a FULL join then - * it doesn't eliminate anything from either side. + * But if it is outer, we can only pass down the local + * constraints into the nullable side, because an outer join + * never eliminates any rows from its non-nullable side. If + * it's a FULL join then it doesn't eliminate anything from + * either side. */ if (jointype != JOIN_FULL) { @@ -713,7 +713,8 @@ reduce_outer_joins_pass2(Node *jtnode, nonnullable_rels); } else - local_nonnullable = NULL; /* no use in calculating it */ + local_nonnullable = NULL; /* no use in calculating + * it */ if (left_state->contains_outer) { @@ -747,7 +748,7 @@ reduce_outer_joins_pass2(Node *jtnode, * * We don't use expression_tree_walker here because we don't want to * descend through very many kinds of nodes; only the ones we can be sure - * are strict. We can descend through the top level of implicit AND'ing, + * are strict. We can descend through the top level of implicit AND'ing, * but not through any explicit ANDs (or ORs) below that, since those are not * strict constructs. The List case handles the top-level implicit AND list * as well as lists of arguments to strict operators/functions. @@ -785,7 +786,7 @@ find_nonnullable_rels(Node *node, bool top_level) } else if (IsA(node, OpExpr)) { - OpExpr *expr = (OpExpr *) node; + OpExpr *expr = (OpExpr *) node; if (op_strict(expr->opno)) result = find_nonnullable_rels((Node *) expr->args, false); @@ -800,7 +801,7 @@ find_nonnullable_rels(Node *node, bool top_level) } else if (IsA(node, RelabelType)) { - RelabelType *expr = (RelabelType *) node; + RelabelType *expr = (RelabelType *) node; result = find_nonnullable_rels((Node *) expr->arg, top_level); } @@ -817,7 +818,7 @@ find_nonnullable_rels(Node *node, bool top_level) } else if (IsA(node, BooleanTest)) { - BooleanTest *expr = (BooleanTest *) node; + BooleanTest *expr = (BooleanTest *) node; /* * Appropriate boolean tests are strict at top level. @@ -894,10 +895,11 @@ simplify_jointree(Query *parse, Node *jtnode) (childlen + myothers) <= from_collapse_limit) { newlist = nconc(newlist, subf->fromlist); + /* - * By now, the quals have been converted to implicit-AND - * lists, so we just need to join the lists. NOTE: we - * put the pulled-up quals first. + * By now, the quals have been converted to + * implicit-AND lists, so we just need to join the + * lists. NOTE: we put the pulled-up quals first. */ f->quals = (Node *) nconc((List *) subf->quals, (List *) f->quals); @@ -917,16 +919,17 @@ simplify_jointree(Query *parse, Node *jtnode) /* Recursively simplify the children... */ j->larg = simplify_jointree(parse, j->larg); j->rarg = simplify_jointree(parse, j->rarg); + /* - * If it is an outer join, we must not flatten it. An inner join + * If it is an outer join, we must not flatten it. An inner join * is semantically equivalent to a FromExpr; we convert it to one, * allowing it to be flattened into its parent, if the resulting * FromExpr would have no more than join_collapse_limit members. */ if (j->jointype == JOIN_INNER && join_collapse_limit > 1) { - int leftlen, - rightlen; + int leftlen, + rightlen; if (j->larg && IsA(j->larg, FromExpr)) leftlen = length(((FromExpr *) j->larg)->fromlist); diff --git a/src/backend/optimizer/prep/prepqual.c b/src/backend/optimizer/prep/prepqual.c index 24ea1316e1..cbe822448e 100644 --- a/src/backend/optimizer/prep/prepqual.c +++ b/src/backend/optimizer/prep/prepqual.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepqual.c,v 1.35 2003/05/28 22:32:49 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepqual.c,v 1.36 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,12 +21,12 @@ #include "utils/lsyscache.h" static Expr *flatten_andors(Expr *qual); -static void flatten_andors_and_walker(FastList *out_list, List *andlist); -static void flatten_andors_or_walker(FastList *out_list, List *orlist); +static void flatten_andors_and_walker(FastList * out_list, List *andlist); +static void flatten_andors_or_walker(FastList * out_list, List *orlist); static List *pull_ands(List *andlist); -static void pull_ands_walker(FastList *out_list, List *andlist); +static void pull_ands_walker(FastList * out_list, List *andlist); static List *pull_ors(List *orlist); -static void pull_ors_walker(FastList *out_list, List *orlist); +static void pull_ors_walker(FastList * out_list, List *orlist); static Expr *find_nots(Expr *qual); static Expr *push_nots(Expr *qual); static Expr *find_ors(Expr *qual); @@ -328,7 +328,7 @@ flatten_andors(Expr *qual) } static void -flatten_andors_and_walker(FastList *out_list, List *andlist) +flatten_andors_and_walker(FastList * out_list, List *andlist) { List *arg; @@ -344,7 +344,7 @@ flatten_andors_and_walker(FastList *out_list, List *andlist) } static void -flatten_andors_or_walker(FastList *out_list, List *orlist) +flatten_andors_or_walker(FastList * out_list, List *orlist) { List *arg; @@ -377,7 +377,7 @@ pull_ands(List *andlist) } static void -pull_ands_walker(FastList *out_list, List *andlist) +pull_ands_walker(FastList * out_list, List *andlist) { List *arg; @@ -410,7 +410,7 @@ pull_ors(List *orlist) } static void -pull_ors_walker(FastList *out_list, List *orlist) +pull_ors_walker(FastList * out_list, List *orlist) { List *arg; diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index 9c937f1760..d33ff7417d 100644 --- a/src/backend/optimizer/prep/preptlist.c +++ b/src/backend/optimizer/prep/preptlist.c @@ -15,7 +15,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/preptlist.c,v 1.62 2003/07/25 00:01:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/preptlist.c,v 1.63 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -174,12 +174,12 @@ expand_targetlist(List *tlist, int command_type, * * When generating a NULL constant for a dropped column, we label * it INT4 (any other guaranteed-to-exist datatype would do as - * well). We can't label it with the dropped column's datatype - * since that might not exist anymore. It does not really - * matter what we claim the type is, since NULL is NULL --- its - * representation is datatype-independent. This could perhaps - * confuse code comparing the finished plan to the target - * relation, however. + * well). We can't label it with the dropped column's + * datatype since that might not exist anymore. It does not + * really matter what we claim the type is, since NULL is NULL + * --- its representation is datatype-independent. This could + * perhaps confuse code comparing the finished plan to the + * target relation, however. */ Oid atttype = att_tup->atttypid; int32 atttypmod = att_tup->atttypmod; @@ -193,7 +193,7 @@ expand_targetlist(List *tlist, int command_type, new_expr = (Node *) makeConst(atttype, att_tup->attlen, (Datum) 0, - true, /* isnull */ + true, /* isnull */ att_tup->attbyval); new_expr = coerce_to_domain(new_expr, InvalidOid, @@ -206,8 +206,8 @@ expand_targetlist(List *tlist, int command_type, new_expr = (Node *) makeConst(INT4OID, sizeof(int32), (Datum) 0, - true, /* isnull */ - true /* byval */); + true, /* isnull */ + true /* byval */ ); /* label resdom with INT4, too */ atttype = INT4OID; atttypmod = -1; @@ -228,8 +228,8 @@ expand_targetlist(List *tlist, int command_type, new_expr = (Node *) makeConst(INT4OID, sizeof(int32), (Datum) 0, - true, /* isnull */ - true /* byval */); + true, /* isnull */ + true /* byval */ ); /* label resdom with INT4, too */ atttype = INT4OID; atttypmod = -1; diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c index 5422d59172..49ebc82208 100644 --- a/src/backend/optimizer/prep/prepunion.c +++ b/src/backend/optimizer/prep/prepunion.c @@ -14,7 +14,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepunion.c,v 1.101 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepunion.c,v 1.102 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -427,7 +427,7 @@ generate_setop_tlist(List *colTypes, int flag, } else { - expr = coerce_to_common_type(NULL, /* no UNKNOWNs here */ + expr = coerce_to_common_type(NULL, /* no UNKNOWNs here */ expr, colType, "UNION/INTERSECT/EXCEPT"); @@ -849,11 +849,11 @@ adjust_inherited_attrs_mutator(Node *node, if (IsA(node, InClauseInfo)) { /* Copy the InClauseInfo node with correct mutation of subnodes */ - InClauseInfo *ininfo; + InClauseInfo *ininfo; ininfo = (InClauseInfo *) expression_tree_mutator(node, adjust_inherited_attrs_mutator, - (void *) context); + (void *) context); /* now fix InClauseInfo's relid sets */ ininfo->lefthand = adjust_relid_set(ininfo->lefthand, context->old_rt_index, @@ -880,9 +880,9 @@ adjust_inherited_attrs_mutator(Node *node, adjust_inherited_attrs_mutator((Node *) oldinfo->clause, context); /* - * We do NOT want to copy the original subclauseindices list, since - * the new rel will have different indices. The list will be rebuilt - * when needed during later planning. + * We do NOT want to copy the original subclauseindices list, + * since the new rel will have different indices. The list will + * be rebuilt when needed during later planning. */ newinfo->subclauseindices = NIL; @@ -896,7 +896,7 @@ adjust_inherited_attrs_mutator(Node *node, context->old_rt_index, context->new_rt_index); - newinfo->eval_cost.startup = -1; /* reset these too */ + newinfo->eval_cost.startup = -1; /* reset these too */ newinfo->this_selec = -1; newinfo->left_pathkey = NIL; /* and these */ newinfo->right_pathkey = NIL; @@ -925,7 +925,7 @@ adjust_inherited_attrs_mutator(Node *node, */ if (is_subplan(node)) { - SubPlan *subplan; + SubPlan *subplan; /* Copy the node and process subplan args */ node = expression_tree_mutator(node, adjust_inherited_attrs_mutator, @@ -963,7 +963,7 @@ adjust_relid_set(Relids relids, Index oldrelid, Index newrelid) * * The expressions have already been fixed, but we have to make sure that * the target resnos match the child table (they may not, in the case of - * a column that was added after-the-fact by ALTER TABLE). In some cases + * a column that was added after-the-fact by ALTER TABLE). In some cases * this can force us to re-order the tlist to preserve resno ordering. * (We do all this work in special cases so that preptlist.c is fast for * the typical case.) diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 3ebc1c650e..4a419a35dc 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.149 2003/08/03 23:46:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.150 2003/08/04 00:43:20 momjian Exp $ * * HISTORY * AUTHOR DATE MAJOR EVENT @@ -50,7 +50,7 @@ typedef struct int nargs; List *args; int *usecounts; -} substitute_actual_parameters_context; +} substitute_actual_parameters_context; static bool contain_agg_clause_walker(Node *node, void *context); static bool contain_distinct_agg_clause_walker(Node *node, void *context); @@ -62,15 +62,15 @@ static bool contain_volatile_functions_walker(Node *node, void *context); static bool contain_nonstrict_functions_walker(Node *node, void *context); static Node *eval_const_expressions_mutator(Node *node, List *active_fns); static Expr *simplify_function(Oid funcid, Oid result_type, List *args, - bool allow_inline, List *active_fns); + bool allow_inline, List *active_fns); static Expr *evaluate_function(Oid funcid, Oid result_type, List *args, - HeapTuple func_tuple); + HeapTuple func_tuple); static Expr *inline_function(Oid funcid, Oid result_type, List *args, - HeapTuple func_tuple, List *active_fns); + HeapTuple func_tuple, List *active_fns); static Node *substitute_actual_parameters(Node *expr, int nargs, List *args, - int *usecounts); + int *usecounts); static Node *substitute_actual_parameters_mutator(Node *node, - substitute_actual_parameters_context *context); + substitute_actual_parameters_context * context); static void sql_inline_error_callback(void *arg); static Expr *evaluate_expr(Expr *expr, Oid result_type); @@ -110,7 +110,7 @@ make_opclause(Oid opno, Oid opresulttype, bool opretset, Node * get_leftop(Expr *clause) { - OpExpr *expr = (OpExpr *) clause; + OpExpr *expr = (OpExpr *) clause; if (expr->args != NIL) return lfirst(expr->args); @@ -127,7 +127,7 @@ get_leftop(Expr *clause) Node * get_rightop(Expr *clause) { - OpExpr *expr = (OpExpr *) clause; + OpExpr *expr = (OpExpr *) clause; if (expr->args != NIL && lnext(expr->args) != NIL) return lfirst(lnext(expr->args)); @@ -408,7 +408,7 @@ count_agg_clause_walker(Node *node, int *count) if (contain_agg_clause((Node *) ((Aggref *) node)->target)) ereport(ERROR, (errcode(ERRCODE_GROUPING_ERROR), - errmsg("aggregate function calls may not be nested"))); + errmsg("aggregate function calls may not be nested"))); /* * Having checked that, we need not recurse into the argument. @@ -454,7 +454,7 @@ expression_returns_set_walker(Node *node, void *context) } if (IsA(node, OpExpr)) { - OpExpr *expr = (OpExpr *) node; + OpExpr *expr = (OpExpr *) node; if (expr->opretset) return true; @@ -556,7 +556,7 @@ contain_mutable_functions_walker(Node *node, void *context) } if (IsA(node, OpExpr)) { - OpExpr *expr = (OpExpr *) node; + OpExpr *expr = (OpExpr *) node; if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE) return true; @@ -564,7 +564,7 @@ contain_mutable_functions_walker(Node *node, void *context) } if (IsA(node, DistinctExpr)) { - DistinctExpr *expr = (DistinctExpr *) node; + DistinctExpr *expr = (DistinctExpr *) node; if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE) return true; @@ -572,7 +572,7 @@ contain_mutable_functions_walker(Node *node, void *context) } if (IsA(node, ScalarArrayOpExpr)) { - ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node; + ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node; if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE) return true; @@ -580,7 +580,7 @@ contain_mutable_functions_walker(Node *node, void *context) } if (IsA(node, NullIfExpr)) { - NullIfExpr *expr = (NullIfExpr *) node; + NullIfExpr *expr = (NullIfExpr *) node; if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE) return true; @@ -588,7 +588,7 @@ contain_mutable_functions_walker(Node *node, void *context) } if (IsA(node, SubLink)) { - SubLink *sublink = (SubLink *) node; + SubLink *sublink = (SubLink *) node; List *opid; foreach(opid, sublink->operOids) @@ -639,7 +639,7 @@ contain_volatile_functions_walker(Node *node, void *context) } if (IsA(node, OpExpr)) { - OpExpr *expr = (OpExpr *) node; + OpExpr *expr = (OpExpr *) node; if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE) return true; @@ -647,7 +647,7 @@ contain_volatile_functions_walker(Node *node, void *context) } if (IsA(node, DistinctExpr)) { - DistinctExpr *expr = (DistinctExpr *) node; + DistinctExpr *expr = (DistinctExpr *) node; if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE) return true; @@ -655,7 +655,7 @@ contain_volatile_functions_walker(Node *node, void *context) } if (IsA(node, ScalarArrayOpExpr)) { - ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node; + ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node; if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE) return true; @@ -663,7 +663,7 @@ contain_volatile_functions_walker(Node *node, void *context) } if (IsA(node, NullIfExpr)) { - NullIfExpr *expr = (NullIfExpr *) node; + NullIfExpr *expr = (NullIfExpr *) node; if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE) return true; @@ -671,7 +671,7 @@ contain_volatile_functions_walker(Node *node, void *context) } if (IsA(node, SubLink)) { - SubLink *sublink = (SubLink *) node; + SubLink *sublink = (SubLink *) node; List *opid; foreach(opid, sublink->operOids) @@ -698,7 +698,7 @@ contain_volatile_functions_walker(Node *node, void *context) * could produce non-NULL output with a NULL input. * * XXX we do not examine sub-selects to see if they contain uses of - * nonstrict functions. It's not real clear if that is correct or not... + * nonstrict functions. It's not real clear if that is correct or not... * for the current usage it does not matter, since inline_function() * rejects cases with sublinks. */ @@ -723,7 +723,7 @@ contain_nonstrict_functions_walker(Node *node, void *context) } if (IsA(node, OpExpr)) { - OpExpr *expr = (OpExpr *) node; + OpExpr *expr = (OpExpr *) node; if (!op_strict(expr->opno)) return true; @@ -766,7 +766,7 @@ contain_nonstrict_functions_walker(Node *node, void *context) return true; if (IsA(node, SubLink)) { - SubLink *sublink = (SubLink *) node; + SubLink *sublink = (SubLink *) node; List *opid; foreach(opid, sublink->operOids) @@ -981,7 +981,7 @@ NumRelids(Node *clause) * XXX the clause is destructively modified! */ void -CommuteClause(OpExpr *clause) +CommuteClause(OpExpr * clause) { Oid opoid; Node *temp; @@ -1062,18 +1062,20 @@ eval_const_expressions_mutator(Node *node, List *active_fns) args = (List *) expression_tree_mutator((Node *) expr->args, eval_const_expressions_mutator, (void *) active_fns); + /* - * Code for op/func reduction is pretty bulky, so split it out - * as a separate function. + * Code for op/func reduction is pretty bulky, so split it out as + * a separate function. */ simple = simplify_function(expr->funcid, expr->funcresulttype, args, true, active_fns); if (simple) /* successfully simplified it */ return (Node *) simple; + /* * The expression cannot be simplified any further, so build and - * return a replacement FuncExpr node using the possibly-simplified - * arguments. + * return a replacement FuncExpr node using the + * possibly-simplified arguments. */ newexpr = makeNode(FuncExpr); newexpr->funcid = expr->funcid; @@ -1098,19 +1100,22 @@ eval_const_expressions_mutator(Node *node, List *active_fns) args = (List *) expression_tree_mutator((Node *) expr->args, eval_const_expressions_mutator, (void *) active_fns); + /* - * Need to get OID of underlying function. Okay to scribble on + * Need to get OID of underlying function. Okay to scribble on * input to this extent. */ set_opfuncid(expr); + /* - * Code for op/func reduction is pretty bulky, so split it out - * as a separate function. + * Code for op/func reduction is pretty bulky, so split it out as + * a separate function. */ simple = simplify_function(expr->opfuncid, expr->opresulttype, args, true, active_fns); if (simple) /* successfully simplified it */ return (Node *) simple; + /* * The expression cannot be simplified any further, so build and * return a replacement OpExpr node using the possibly-simplified @@ -1136,8 +1141,8 @@ eval_const_expressions_mutator(Node *node, List *active_fns) DistinctExpr *newexpr; /* - * Reduce constants in the DistinctExpr's arguments. We know args is - * either NIL or a List node, so we can call + * Reduce constants in the DistinctExpr's arguments. We know args + * is either NIL or a List node, so we can call * expression_tree_mutator directly rather than recursing to self. */ args = (List *) expression_tree_mutator((Node *) expr->args, @@ -1145,9 +1150,9 @@ eval_const_expressions_mutator(Node *node, List *active_fns) (void *) active_fns); /* - * We must do our own check for NULLs because - * DistinctExpr has different results for NULL input - * than the underlying operator does. + * We must do our own check for NULLs because DistinctExpr has + * different results for NULL input than the underlying operator + * does. */ foreach(arg, args) { @@ -1175,10 +1180,12 @@ eval_const_expressions_mutator(Node *node, List *active_fns) /* (NOT okay to try to inline it, though!) */ /* - * Need to get OID of underlying function. Okay to scribble on - * input to this extent. + * Need to get OID of underlying function. Okay to scribble + * on input to this extent. */ - set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */ + set_opfuncid((OpExpr *) expr); /* rely on struct + * equivalence */ + /* * Code for op/func reduction is pretty bulky, so split it out * as a separate function. @@ -1191,7 +1198,7 @@ eval_const_expressions_mutator(Node *node, List *active_fns) * Since the underlying operator is "=", must negate its * result */ - Const *csimple = (Const *) simple; + Const *csimple = (Const *) simple; Assert(IsA(csimple, Const)); csimple->constvalue = @@ -1359,8 +1366,7 @@ eval_const_expressions_mutator(Node *node, List *active_fns) if (IsA(node, SubPlan)) { /* - * Return a SubPlan unchanged --- too late to do anything - * with it. + * Return a SubPlan unchanged --- too late to do anything with it. * * XXX should we ereport() here instead? Probably this routine * should never be invoked after SubPlan creation. @@ -1487,16 +1493,16 @@ eval_const_expressions_mutator(Node *node, List *active_fns) } if (IsA(node, ArrayExpr)) { - ArrayExpr *arrayexpr = (ArrayExpr *) node; - ArrayExpr *newarray; - bool all_const = true; + ArrayExpr *arrayexpr = (ArrayExpr *) node; + ArrayExpr *newarray; + bool all_const = true; FastList newelems; - List *element; + List *element; FastListInit(&newelems); foreach(element, arrayexpr->elements) { - Node *e; + Node *e; e = eval_const_expressions_mutator((Node *) lfirst(element), active_fns); @@ -1522,19 +1528,20 @@ eval_const_expressions_mutator(Node *node, List *active_fns) CoalesceExpr *coalesceexpr = (CoalesceExpr *) node; CoalesceExpr *newcoalesce; FastList newargs; - List *arg; + List *arg; FastListInit(&newargs); foreach(arg, coalesceexpr->args) { - Node *e; + Node *e; e = eval_const_expressions_mutator((Node *) lfirst(arg), active_fns); - /* - * We can remove null constants from the list. - * For a non-null constant, if it has not been preceded by any - * other non-null-constant expressions then that is the result. + + /* + * We can remove null constants from the list. For a non-null + * constant, if it has not been preceded by any other + * non-null-constant expressions then that is the result. */ if (IsA(e, Const)) { @@ -1555,10 +1562,11 @@ eval_const_expressions_mutator(Node *node, List *active_fns) { /* * We can optimize field selection from a whole-row Var into a - * simple Var. (This case won't be generated directly by the - * parser, because ParseComplexProjection short-circuits it. - * But it can arise while simplifying functions.) If the argument - * isn't a whole-row Var, just fall through to do generic processing. + * simple Var. (This case won't be generated directly by the + * parser, because ParseComplexProjection short-circuits it. But + * it can arise while simplifying functions.) If the argument + * isn't a whole-row Var, just fall through to do generic + * processing. */ FieldSelect *fselect = (FieldSelect *) node; Var *argvar = (Var *) fselect->arg; @@ -1604,12 +1612,12 @@ simplify_function(Oid funcid, Oid result_type, List *args, Expr *newexpr; /* - * We have two strategies for simplification: either execute the function - * to deliver a constant result, or expand in-line the body of the - * function definition (which only works for simple SQL-language - * functions, but that is a common case). In either case we need access - * to the function's pg_proc tuple, so fetch it just once to use in both - * attempts. + * We have two strategies for simplification: either execute the + * function to deliver a constant result, or expand in-line the body + * of the function definition (which only works for simple + * SQL-language functions, but that is a common case). In either case + * we need access to the function's pg_proc tuple, so fetch it just + * once to use in both attempts. */ func_tuple = SearchSysCache(PROCOID, ObjectIdGetDatum(funcid), @@ -1668,15 +1676,15 @@ evaluate_function(Oid funcid, Oid result_type, List *args, /* * If the function is strict and has a constant-NULL input, it will * never be called at all, so we can replace the call by a NULL - * constant, even if there are other inputs that aren't constant, - * and even if the function is not otherwise immutable. + * constant, even if there are other inputs that aren't constant, and + * even if the function is not otherwise immutable. */ if (funcform->proisstrict && has_null_input) return (Expr *) makeNullConst(result_type); /* - * Otherwise, can simplify only if the function is immutable and - * all inputs are constants. (For a non-strict function, constant NULL + * Otherwise, can simplify only if the function is immutable and all + * inputs are constants. (For a non-strict function, constant NULL * inputs are treated the same as constant non-NULL inputs.) */ if (funcform->provolatile != PROVOLATILE_IMMUTABLE || @@ -1692,7 +1700,7 @@ evaluate_function(Oid funcid, Oid result_type, List *args, newexpr->funcid = funcid; newexpr->funcresulttype = result_type; newexpr->funcretset = false; - newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */ + newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */ newexpr->args = args; return evaluate_expr((Expr *) newexpr, result_type); @@ -1712,7 +1720,7 @@ evaluate_function(Oid funcid, Oid result_type, List *args, * do not re-expand them. Also, if a parameter is used more than once * in the SQL-function body, we require it not to contain any volatile * functions (volatiles might deliver inconsistent answers) nor to be - * unreasonably expensive to evaluate. The expensiveness check not only + * unreasonably expensive to evaluate. The expensiveness check not only * prevents us from doing multiple evaluations of an expensive parameter * at runtime, but is a safety value to limit growth of an expression due * to repeated inlining. @@ -1747,7 +1755,7 @@ inline_function(Oid funcid, Oid result_type, List *args, /* * Forget it if the function is not SQL-language or has other - * showstopper properties. (The nargs check is just paranoia.) + * showstopper properties. (The nargs check is just paranoia.) */ if (funcform->prolang != SQLlanguageId || funcform->prosecdef || @@ -1755,7 +1763,10 @@ inline_function(Oid funcid, Oid result_type, List *args, funcform->pronargs != length(args)) return NULL; - /* Forget it if declared return type is not base, domain, or polymorphic */ + /* + * Forget it if declared return type is not base, domain, or + * polymorphic + */ result_typtype = get_typtype(funcform->prorettype); if (result_typtype != 'b' && result_typtype != 'd') @@ -1788,8 +1799,8 @@ inline_function(Oid funcid, Oid result_type, List *args, } /* - * Setup error traceback support for ereport(). This is so that we can - * finger the function that bad information came from. + * Setup error traceback support for ereport(). This is so that we + * can finger the function that bad information came from. */ sqlerrcontext.callback = sql_inline_error_callback; sqlerrcontext.arg = funcform; @@ -1818,9 +1829,9 @@ inline_function(Oid funcid, Oid result_type, List *args, /* * We just do parsing and parse analysis, not rewriting, because - * rewriting will not affect table-free-SELECT-only queries, which is all - * that we care about. Also, we can punt as soon as we detect more than - * one command in the function body. + * rewriting will not affect table-free-SELECT-only queries, which is + * all that we care about. Also, we can punt as soon as we detect + * more than one command in the function body. */ raw_parsetree_list = pg_parse_query(src); if (length(raw_parsetree_list) != 1) @@ -1863,8 +1874,8 @@ inline_function(Oid funcid, Oid result_type, List *args, * then it wasn't type-checked at definition time; must do so now. * (This will raise an error if wrong, but that's okay since the * function would fail at runtime anyway. Note we do not try this - * until we have verified that no rewriting was needed; that's probably - * not important, but let's be careful.) + * until we have verified that no rewriting was needed; that's + * probably not important, but let's be careful.) */ if (polymorphic) check_sql_fn_retval(result_type, get_typtype(result_type), @@ -1875,9 +1886,9 @@ inline_function(Oid funcid, Oid result_type, List *args, * set, and it mustn't be more volatile than the surrounding function * (this is to avoid breaking hacks that involve pretending a function * is immutable when it really ain't). If the surrounding function is - * declared strict, then the expression must contain only strict constructs - * and must use all of the function parameters (this is overkill, but - * an exact analysis is hard). + * declared strict, then the expression must contain only strict + * constructs and must use all of the function parameters (this is + * overkill, but an exact analysis is hard). */ if (expression_returns_set(newexpr)) goto fail; @@ -1886,7 +1897,7 @@ inline_function(Oid funcid, Oid result_type, List *args, contain_mutable_functions(newexpr)) goto fail; else if (funcform->provolatile == PROVOLATILE_STABLE && - contain_volatile_functions(newexpr)) + contain_volatile_functions(newexpr)) goto fail; if (funcform->proisstrict && @@ -1907,7 +1918,7 @@ inline_function(Oid funcid, Oid result_type, List *args, i = 0; foreach(arg, args) { - Node *param = lfirst(arg); + Node *param = lfirst(arg); if (usecounts[i] == 0) { @@ -1932,6 +1943,7 @@ inline_function(Oid funcid, Oid result_type, List *args, if (eval_cost.startup + eval_cost.per_tuple > 10 * cpu_operator_cost) goto fail; + /* * Check volatility last since this is more expensive than the * above tests @@ -1943,8 +1955,8 @@ inline_function(Oid funcid, Oid result_type, List *args, } /* - * Whew --- we can make the substitution. Copy the modified expression - * out of the temporary memory context, and clean up. + * Whew --- we can make the substitution. Copy the modified + * expression out of the temporary memory context, and clean up. */ MemoryContextSwitchTo(oldcxt); @@ -1981,7 +1993,7 @@ substitute_actual_parameters(Node *expr, int nargs, List *args, { substitute_actual_parameters_context context; - context.nargs = nargs; + context.nargs = nargs; context.args = args; context.usecounts = usecounts; @@ -1990,7 +2002,7 @@ substitute_actual_parameters(Node *expr, int nargs, List *args, static Node * substitute_actual_parameters_mutator(Node *node, - substitute_actual_parameters_context *context) + substitute_actual_parameters_context * context) { if (node == NULL) return NULL; @@ -2059,10 +2071,10 @@ evaluate_expr(Expr *expr, Oid result_type) /* * And evaluate it. * - * It is OK to use a default econtext because none of the - * ExecEvalExpr() code used in this situation will use econtext. That - * might seem fortuitous, but it's not so unreasonable --- a constant - * expression does not depend on context, by definition, n'est ce pas? + * It is OK to use a default econtext because none of the ExecEvalExpr() + * code used in this situation will use econtext. That might seem + * fortuitous, but it's not so unreasonable --- a constant expression + * does not depend on context, by definition, n'est ce pas? */ const_val = ExecEvalExprSwitchContext(exprstate, GetPerTupleExprContext(estate), @@ -2177,7 +2189,7 @@ evaluate_expr(Expr *expr, Oid result_type) * * expression_tree_walker will handle SubPlan nodes by recursing normally * into the "exprs" and "args" lists (which are expressions belonging to - * the outer plan). It will not touch the completed subplan, however. Since + * the outer plan). It will not touch the completed subplan, however. Since * there is no link to the original Query, it is not possible to recurse into * subselects of an already-planned expression tree. This is OK for current * uses, but may need to be revisited in future. @@ -2283,6 +2295,7 @@ expression_tree_walker(Node *node, if (expression_tree_walker((Node *) sublink->lefthand, walker, context)) return true; + /* * Also invoke the walker on the sublink's Query node, so * it can recurse into the sub-query if it wants to. @@ -2292,7 +2305,7 @@ expression_tree_walker(Node *node, break; case T_SubPlan: { - SubPlan *subplan = (SubPlan *) node; + SubPlan *subplan = (SubPlan *) node; /* recurse into the exprs list, but not into the Plan */ if (expression_tree_walker((Node *) subplan->exprs, @@ -2457,12 +2470,12 @@ query_tree_walker(Query *query, /* nothing to do */ break; case RTE_SUBQUERY: - if (! (flags & QTW_IGNORE_RT_SUBQUERIES)) + if (!(flags & QTW_IGNORE_RT_SUBQUERIES)) if (walker(rte->subquery, context)) return true; break; case RTE_JOIN: - if (! (flags & QTW_IGNORE_JOINALIASES)) + if (!(flags & QTW_IGNORE_JOINALIASES)) if (walker(rte->joinaliasvars, context)) return true; break; @@ -2622,8 +2635,8 @@ expression_tree_mutator(Node *node, break; case T_DistinctExpr: { - DistinctExpr *expr = (DistinctExpr *) node; - DistinctExpr *newnode; + DistinctExpr *expr = (DistinctExpr *) node; + DistinctExpr *newnode; FLATCOPY(newnode, expr, DistinctExpr); MUTATE(newnode->args, expr->args, List *); @@ -2632,8 +2645,8 @@ expression_tree_mutator(Node *node, break; case T_ScalarArrayOpExpr: { - ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node; - ScalarArrayOpExpr *newnode; + ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node; + ScalarArrayOpExpr *newnode; FLATCOPY(newnode, expr, ScalarArrayOpExpr); MUTATE(newnode->args, expr->args, List *); @@ -2657,6 +2670,7 @@ expression_tree_mutator(Node *node, FLATCOPY(newnode, sublink, SubLink); MUTATE(newnode->lefthand, sublink->lefthand, List *); + /* * Also invoke the mutator on the sublink's Query node, so * it can recurse into the sub-query if it wants to. @@ -2667,8 +2681,8 @@ expression_tree_mutator(Node *node, break; case T_SubPlan: { - SubPlan *subplan = (SubPlan *) node; - SubPlan *newnode; + SubPlan *subplan = (SubPlan *) node; + SubPlan *newnode; FLATCOPY(newnode, subplan, SubPlan); /* transform exprs list */ @@ -2725,8 +2739,8 @@ expression_tree_mutator(Node *node, break; case T_ArrayExpr: { - ArrayExpr *arrayexpr = (ArrayExpr *) node; - ArrayExpr *newnode; + ArrayExpr *arrayexpr = (ArrayExpr *) node; + ArrayExpr *newnode; FLATCOPY(newnode, arrayexpr, ArrayExpr); MUTATE(newnode->elements, arrayexpr->elements, List *); @@ -2745,8 +2759,8 @@ expression_tree_mutator(Node *node, break; case T_NullIfExpr: { - NullIfExpr *expr = (NullIfExpr *) node; - NullIfExpr *newnode; + NullIfExpr *expr = (NullIfExpr *) node; + NullIfExpr *newnode; FLATCOPY(newnode, expr, NullIfExpr); MUTATE(newnode->args, expr->args, List *); @@ -2891,7 +2905,7 @@ expression_tree_mutator(Node *node, * indicated items. (More flag bits may be added as needed.) * * Normally the Query node itself is copied, but some callers want it to be - * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All + * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All * modified substructure is safely copied in any case. */ Query * @@ -2905,9 +2919,9 @@ query_tree_mutator(Query *query, Assert(query != NULL && IsA(query, Query)); - if (! (flags & QTW_DONT_COPY_QUERY)) + if (!(flags & QTW_DONT_COPY_QUERY)) { - Query *newquery; + Query *newquery; FLATCOPY(newquery, query, Query); query = newquery; @@ -2933,7 +2947,7 @@ query_tree_mutator(Query *query, /* nothing to do, don't bother to make a copy */ break; case RTE_SUBQUERY: - if (! (flags & QTW_IGNORE_RT_SUBQUERIES)) + if (!(flags & QTW_IGNORE_RT_SUBQUERIES)) { FLATCOPY(newrte, rte, RangeTblEntry); CHECKFLATCOPY(newrte->subquery, rte->subquery, Query); @@ -2942,7 +2956,7 @@ query_tree_mutator(Query *query, } break; case RTE_JOIN: - if (! (flags & QTW_IGNORE_JOINALIASES)) + if (!(flags & QTW_IGNORE_JOINALIASES)) { FLATCOPY(newrte, rte, RangeTblEntry); MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *); diff --git a/src/backend/optimizer/util/joininfo.c b/src/backend/optimizer/util/joininfo.c index 599dcf44d9..add36b55d3 100644 --- a/src/backend/optimizer/util/joininfo.c +++ b/src/backend/optimizer/util/joininfo.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/joininfo.c,v 1.34 2003/02/08 20:20:55 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/joininfo.c,v 1.35 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -73,7 +73,7 @@ make_joininfo_node(RelOptInfo *this_rel, Relids join_relids) * appropriate rel node if necessary). * * Note that the same copy of the restrictinfo node is linked to by all the - * lists it is in. This allows us to exploit caching of information about + * lists it is in. This allows us to exploit caching of information about * the restriction clause (but we must be careful that the information does * not depend on context). * @@ -109,9 +109,10 @@ add_join_clause_to_rels(Query *root, unjoined_relids); joininfo->jinfo_restrictinfo = lappend(joininfo->jinfo_restrictinfo, restrictinfo); + /* * Can't bms_free(unjoined_relids) because new joininfo node may - * link to it. We could avoid leaking memory by doing bms_copy() + * link to it. We could avoid leaking memory by doing bms_copy() * in make_joininfo_node, but for now speed seems better. */ } @@ -156,13 +157,14 @@ remove_join_clause_from_rels(Query *root, joininfo = find_joininfo_node(find_base_rel(root, cur_relid), unjoined_relids); Assert(joininfo); + /* - * Remove the restrictinfo from the list. Pointer comparison - * is sufficient. + * Remove the restrictinfo from the list. Pointer comparison is + * sufficient. */ Assert(ptrMember(restrictinfo, joininfo->jinfo_restrictinfo)); joininfo->jinfo_restrictinfo = lremove(restrictinfo, - joininfo->jinfo_restrictinfo); + joininfo->jinfo_restrictinfo); bms_free(unjoined_relids); } bms_free(tmprelids); diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c index 61ab51747c..3a14d6b871 100644 --- a/src/backend/optimizer/util/pathnode.c +++ b/src/backend/optimizer/util/pathnode.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/pathnode.c,v 1.93 2003/07/25 00:01:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/pathnode.c,v 1.94 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -159,7 +159,7 @@ set_cheapest(RelOptInfo *parent_rel) parent_rel->cheapest_startup_path = cheapest_startup_path; parent_rel->cheapest_total_path = cheapest_total_path; - parent_rel->cheapest_unique_path = NULL; /* computed only if needed */ + parent_rel->cheapest_unique_path = NULL; /* computed only if needed */ } /* @@ -452,7 +452,7 @@ create_result_path(RelOptInfo *rel, Path *subpath, List *constantqual) ResultPath *pathnode = makeNode(ResultPath); pathnode->path.pathtype = T_Result; - pathnode->path.parent = rel; /* may be NULL */ + pathnode->path.parent = rel; /* may be NULL */ if (subpath) pathnode->path.pathkeys = subpath->pathkeys; @@ -545,8 +545,8 @@ create_unique_path(Query *root, RelOptInfo *rel, Path *subpath) pathnode->path.parent = rel; /* - * Treat the output as always unsorted, since we don't necessarily have - * pathkeys to represent it. + * Treat the output as always unsorted, since we don't necessarily + * have pathkeys to represent it. */ pathnode->path.pathkeys = NIL; @@ -591,26 +591,28 @@ create_unique_path(Query *root, RelOptInfo *rel, Path *subpath) subpath->total_cost, rel->rows, rel->width); + /* * Charge one cpu_operator_cost per comparison per input tuple. We - * assume all columns get compared at most of the tuples. (XXX probably - * this is an overestimate.) This should agree with make_unique. + * assume all columns get compared at most of the tuples. (XXX + * probably this is an overestimate.) This should agree with + * make_unique. */ sort_path.total_cost += cpu_operator_cost * rel->rows * numCols; /* * Is it safe to use a hashed implementation? If so, estimate and - * compare costs. We only try this if we know the targetlist for - * sure (else we can't be sure about the datatypes involved). + * compare costs. We only try this if we know the targetlist for sure + * (else we can't be sure about the datatypes involved). */ pathnode->use_hash = false; if (enable_hashagg && sub_targetlist && hash_safe_tlist(sub_targetlist)) { /* - * Estimate the overhead per hashtable entry at 64 bytes (same - * as in planner.c). + * Estimate the overhead per hashtable entry at 64 bytes (same as + * in planner.c). */ - int hashentrysize = rel->width + 64; + int hashentrysize = rel->width + 64; if (hashentrysize * pathnode->rows <= SortMem * 1024L) { @@ -647,7 +649,7 @@ create_unique_path(Query *root, RelOptInfo *rel, Path *subpath) * We assume hashed aggregation will work if the datatype's equality operator * is marked hashjoinable. * - * XXX this probably should be somewhere else. See also hash_safe_grouping + * XXX this probably should be somewhere else. See also hash_safe_grouping * in plan/planner.c. */ static bool @@ -788,6 +790,7 @@ create_mergejoin_path(Query *root, if (innersortkeys && pathkeys_contained_in(innersortkeys, inner_path->pathkeys)) innersortkeys = NIL; + /* * If we are not sorting the inner path, we may need a materialize * node to ensure it can be marked/restored. (Sort does support diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c index 6823f03267..3ae98ed253 100644 --- a/src/backend/optimizer/util/plancat.c +++ b/src/backend/optimizer/util/plancat.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/plancat.c,v 1.85 2003/07/25 00:01:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/plancat.c,v 1.86 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -65,7 +65,8 @@ get_relation_info(Oid relationObjectId, RelOptInfo *rel) rel->max_attr = RelationGetNumberOfAttributes(relation); /* - * Make list of indexes. Ignore indexes on system catalogs if told to. + * Make list of indexes. Ignore indexes on system catalogs if told + * to. */ if (IsIgnoringSystemIndexes() && IsSystemClass(relation->rd_rel)) hasindex = false; @@ -99,8 +100,8 @@ get_relation_info(Oid relationObjectId, RelOptInfo *rel) info->ncolumns = ncolumns = index->indnatts; /* - * Need to make classlist and ordering arrays large enough to put - * a terminating 0 at the end of each one. + * Need to make classlist and ordering arrays large enough to + * put a terminating 0 at the end of each one. */ info->indexkeys = (int *) palloc(sizeof(int) * ncolumns); info->classlist = (Oid *) palloc0(sizeof(Oid) * (ncolumns + 1)); @@ -118,7 +119,8 @@ get_relation_info(Oid relationObjectId, RelOptInfo *rel) info->amcostestimate = index_cost_estimator(indexRelation); /* - * Fetch the ordering operators associated with the index, if any. + * Fetch the ordering operators associated with the index, if + * any. */ amorderstrategy = indexRelation->rd_am->amorderstrategy; if (amorderstrategy != 0) @@ -135,8 +137,8 @@ get_relation_info(Oid relationObjectId, RelOptInfo *rel) /* * Fetch the index expressions and predicate, if any. We must * modify the copies we obtain from the relcache to have the - * correct varno for the parent relation, so that they match up - * correctly against qual clauses. + * correct varno for the parent relation, so that they match + * up correctly against qual clauses. */ info->indexprs = RelationGetIndexExpressions(indexRelation); info->indpred = RelationGetIndexPredicate(indexRelation); @@ -177,7 +179,7 @@ get_relation_info(Oid relationObjectId, RelOptInfo *rel) * Exception: if there are any dropped columns, we punt and return NIL. * Ideally we would like to handle the dropped-column case too. However this * creates problems for ExecTypeFromTL, which may be asked to build a tupdesc - * for a tlist that includes vars of no-longer-existent types. In theory we + * for a tlist that includes vars of no-longer-existent types. In theory we * could dig out the required info from the pg_attribute entries of the * relation, but that data is not readily available to ExecTypeFromTL. * For now, we don't apply the physical-tlist optimization when there are @@ -389,11 +391,11 @@ has_unique_index(RelOptInfo *rel, AttrNumber attno) IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist); /* - * Note: ignore partial indexes, since they don't allow us to conclude - * that all attr values are distinct. We don't take any interest in - * expressional indexes either. Also, a multicolumn unique index - * doesn't allow us to conclude that just the specified attr is - * unique. + * Note: ignore partial indexes, since they don't allow us to + * conclude that all attr values are distinct. We don't take any + * interest in expressional indexes either. Also, a multicolumn + * unique index doesn't allow us to conclude that just the + * specified attr is unique. */ if (index->unique && index->ncolumns == 1 && diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 9a4a206976..cc8632899e 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/relnode.c,v 1.50 2003/07/25 00:01:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/relnode.c,v 1.51 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -322,7 +322,8 @@ build_join_rel(Query *root, /* * Create a new tlist containing just the vars that need to be output - * from this join (ie, are needed for higher joinclauses or final output). + * from this join (ie, are needed for higher joinclauses or final + * output). */ build_joinrel_tlist(root, joinrel); @@ -389,8 +390,8 @@ build_joinrel_tlist(Query *root, RelOptInfo *joinrel) foreach(vars, FastListValue(&baserel->reltargetlist)) { - Var *var = (Var *) lfirst(vars); - int ndx = var->varattno - baserel->min_attr; + Var *var = (Var *) lfirst(vars); + int ndx = var->varattno - baserel->min_attr; if (bms_nonempty_difference(baserel->attr_needed[ndx], relids)) { diff --git a/src/backend/optimizer/util/restrictinfo.c b/src/backend/optimizer/util/restrictinfo.c index 334fc5784c..673e76c8c3 100644 --- a/src/backend/optimizer/util/restrictinfo.c +++ b/src/backend/optimizer/util/restrictinfo.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/restrictinfo.c,v 1.17 2003/06/15 22:51:45 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/restrictinfo.c,v 1.18 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,9 +21,9 @@ static bool join_clause_is_redundant(Query *root, - RestrictInfo *rinfo, - List *reference_list, - JoinType jointype); + RestrictInfo *rinfo, + List *reference_list, + JoinType jointype); /* @@ -174,7 +174,7 @@ select_nonredundant_join_clauses(Query *root, * left and right pathkeys, which uniquely identify the sets of equijoined * variables in question. All the members of a pathkey set that are in the * left relation have already been forced to be equal; likewise for those in - * the right relation. So, we need to have only one clause that checks + * the right relation. So, we need to have only one clause that checks * equality between any set member on the left and any member on the right; * by transitivity, all the rest are then equal. * @@ -228,10 +228,9 @@ join_clause_is_redundant(Query *root, if (redundant) { /* - * It looks redundant, now check for "var = const" case. - * If left_relids/right_relids are set, then there are - * definitely vars on both sides; else we must check the - * hard way. + * It looks redundant, now check for "var = const" case. If + * left_relids/right_relids are set, then there are definitely + * vars on both sides; else we must check the hard way. */ if (rinfo->left_relids) return true; /* var = var, so redundant */ diff --git a/src/backend/optimizer/util/tlist.c b/src/backend/optimizer/util/tlist.c index 26d7d6fb24..1056837142 100644 --- a/src/backend/optimizer/util/tlist.c +++ b/src/backend/optimizer/util/tlist.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/tlist.c,v 1.58 2003/07/25 00:01:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/tlist.c,v 1.59 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -211,8 +211,8 @@ get_sortgroupclause_expr(SortClause *sortClause, List *targetList) List * get_sortgrouplist_exprs(List *sortClauses, List *targetList) { - List *result = NIL; - List *l; + List *result = NIL; + List *l; foreach(l, sortClauses) { diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index bdd5baf521..edbb5f085c 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/util/var.c,v 1.51 2003/06/06 15:04:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/var.c,v 1.52 2003/08/04 00:43:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -39,7 +39,7 @@ typedef struct { int min_varlevel; int sublevels_up; -} find_minimum_var_level_context; +} find_minimum_var_level_context; typedef struct { @@ -61,7 +61,7 @@ static bool contain_var_clause_walker(Node *node, void *context); static bool contain_vars_of_level_walker(Node *node, int *sublevels_up); static bool contain_vars_above_level_walker(Node *node, int *sublevels_up); static bool find_minimum_var_level_walker(Node *node, - find_minimum_var_level_context *context); + find_minimum_var_level_context * context); static bool pull_var_clause_walker(Node *node, pull_var_clause_context *context); static Node *flatten_join_alias_vars_mutator(Node *node, @@ -242,12 +242,12 @@ contain_var_clause_walker(Node *node, void *context) * * Returns true if any such Var found. * - * Will recurse into sublinks. Also, may be invoked directly on a Query. + * Will recurse into sublinks. Also, may be invoked directly on a Query. */ bool contain_vars_of_level(Node *node, int levelsup) { - int sublevels_up = levelsup; + int sublevels_up = levelsup; return query_or_expression_tree_walker(node, contain_vars_of_level_walker, @@ -286,20 +286,20 @@ contain_vars_of_level_walker(Node *node, int *sublevels_up) /* * contain_vars_above_level * Recursively scan a clause to discover whether it contains any Var nodes - * above the specified query level. (For example, pass zero to detect + * above the specified query level. (For example, pass zero to detect * all nonlocal Vars.) * * Returns true if any such Var found. * - * Will recurse into sublinks. Also, may be invoked directly on a Query. + * Will recurse into sublinks. Also, may be invoked directly on a Query. */ bool contain_vars_above_level(Node *node, int levelsup) { - int sublevels_up = levelsup; + int sublevels_up = levelsup; return query_or_expression_tree_walker(node, - contain_vars_above_level_walker, + contain_vars_above_level_walker, (void *) &sublevels_up, 0); } @@ -344,7 +344,7 @@ contain_vars_above_level_walker(Node *node, int *sublevels_up) * * -1 is returned if the clause has no variables at all. * - * Will recurse into sublinks. Also, may be invoked directly on a Query. + * Will recurse into sublinks. Also, may be invoked directly on a Query. */ int find_minimum_var_level(Node *node) @@ -364,13 +364,13 @@ find_minimum_var_level(Node *node) static bool find_minimum_var_level_walker(Node *node, - find_minimum_var_level_context *context) + find_minimum_var_level_context * context) { if (node == NULL) return false; if (IsA(node, Var)) { - int varlevelsup = ((Var *) node)->varlevelsup; + int varlevelsup = ((Var *) node)->varlevelsup; /* convert levelsup to frame of reference of original query */ varlevelsup -= context->sublevels_up; @@ -381,6 +381,7 @@ find_minimum_var_level_walker(Node *node, context->min_varlevel > varlevelsup) { context->min_varlevel = varlevelsup; + /* * As soon as we find a local variable, we can abort the * tree traversal, since min_varlevel is then certainly 0. @@ -390,14 +391,16 @@ find_minimum_var_level_walker(Node *node, } } } + /* - * An Aggref must be treated like a Var of its level. Normally we'd get - * the same result from looking at the Vars in the aggregate's argument, - * but this fails in the case of a Var-less aggregate call (COUNT(*)). + * An Aggref must be treated like a Var of its level. Normally we'd + * get the same result from looking at the Vars in the aggregate's + * argument, but this fails in the case of a Var-less aggregate call + * (COUNT(*)). */ if (IsA(node, Aggref)) { - int agglevelsup = ((Aggref *) node)->agglevelsup; + int agglevelsup = ((Aggref *) node)->agglevelsup; /* convert levelsup to frame of reference of original query */ agglevelsup -= context->sublevels_up; @@ -408,6 +411,7 @@ find_minimum_var_level_walker(Node *node, context->min_varlevel > agglevelsup) { context->min_varlevel = agglevelsup; + /* * As soon as we find a local aggregate, we can abort the * tree traversal, since min_varlevel is then certainly 0. @@ -519,6 +523,7 @@ flatten_join_alias_vars_mutator(Node *node, Assert(var->varattno > 0); /* Okay, must expand it */ newvar = (Node *) nth(var->varattno - 1, rte->joinaliasvars); + /* * If we are expanding an alias carried down from an upper query, * must adjust its varlevelsup fields. @@ -534,11 +539,11 @@ flatten_join_alias_vars_mutator(Node *node, if (IsA(node, InClauseInfo)) { /* Copy the InClauseInfo node with correct mutation of subnodes */ - InClauseInfo *ininfo; + InClauseInfo *ininfo; ininfo = (InClauseInfo *) expression_tree_mutator(node, - flatten_join_alias_vars_mutator, - (void *) context); + flatten_join_alias_vars_mutator, + (void *) context); /* now fix InClauseInfo's relid sets */ if (context->sublevels_up == 0) { diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index ef8fa510ab..3cbdcc6231 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.283 2003/08/01 00:15:22 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.284 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -89,7 +89,7 @@ typedef struct { Oid *paramTypes; int numParams; -} check_parameter_resolution_context; +} check_parameter_resolution_context; static List *do_parse_analyze(Node *parseTree, ParseState *pstate); @@ -106,7 +106,7 @@ static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt); static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt); static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt); static Query *transformDeclareCursorStmt(ParseState *pstate, - DeclareCursorStmt *stmt); + DeclareCursorStmt * stmt); static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt); static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt); static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt, @@ -114,18 +114,18 @@ static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt, static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt, List **extras_before, List **extras_after); static void transformColumnDefinition(ParseState *pstate, - CreateStmtContext *cxt, - ColumnDef *column); + CreateStmtContext *cxt, + ColumnDef *column); static void transformTableConstraint(ParseState *pstate, - CreateStmtContext *cxt, - Constraint *constraint); + CreateStmtContext *cxt, + Constraint *constraint); static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt, - InhRelation *inhrelation); + InhRelation * inhrelation); static void transformIndexConstraints(ParseState *pstate, - CreateStmtContext *cxt); + CreateStmtContext *cxt); static void transformFKConstraints(ParseState *pstate, - CreateStmtContext *cxt, - bool isAddConstraint); + CreateStmtContext *cxt, + bool isAddConstraint); static void applyColumnNames(List *dst, List *src); static List *getSetColTypes(ParseState *pstate, Node *node); static void transformForUpdate(Query *qry, List *forUpdate); @@ -135,7 +135,7 @@ static bool relationHasPrimaryKey(Oid relationOid); static void release_pstate_resources(ParseState *pstate); static FromExpr *makeFromExpr(List *fromlist, Node *quals); static bool check_parameter_resolution_walker(Node *node, - check_parameter_resolution_context *context); + check_parameter_resolution_context * context); /* @@ -229,6 +229,7 @@ static List * do_parse_analyze(Node *parseTree, ParseState *pstate) { List *result = NIL; + /* Lists to return extra commands from transformation */ List *extras_before = NIL; List *extras_after = NIL; @@ -258,9 +259,10 @@ do_parse_analyze(Node *parseTree, ParseState *pstate) /* * Make sure that only the original query is marked original. We have - * to do this explicitly since recursive calls of do_parse_analyze will - * have marked some of the added-on queries as "original". Also mark - * only the original query as allowed to set the command-result tag. + * to do this explicitly since recursive calls of do_parse_analyze + * will have marked some of the added-on queries as "original". Also + * mark only the original query as allowed to set the command-result + * tag. */ foreach(listscan, result) { @@ -419,7 +421,7 @@ transformStmt(ParseState *pstate, Node *parseTree, case T_DeclareCursorStmt: result = transformDeclareCursorStmt(pstate, - (DeclareCursorStmt *) parseTree); + (DeclareCursorStmt *) parseTree); break; default: @@ -593,10 +595,10 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt, * * HACK: unknown-type constants and params in the INSERT's targetlist * are copied up as-is rather than being referenced as subquery - * outputs. This is to ensure that when we try to coerce them - * to the target column's datatype, the right things happen (see - * special cases in coerce_type). Otherwise, this fails: - * INSERT INTO foo SELECT 'bar', ... FROM baz + * outputs. This is to ensure that when we try to coerce them to + * the target column's datatype, the right things happen (see + * special cases in coerce_type). Otherwise, this fails: INSERT + * INTO foo SELECT 'bar', ... FROM baz */ qry->targetList = NIL; foreach(tl, selectQuery->targetList) @@ -608,7 +610,7 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt, if (resnode->resjunk) continue; if (tle->expr && - (IsA(tle->expr, Const) || IsA(tle->expr, Param)) && + (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) && exprType((Node *) tle->expr) == UNKNOWNOID) expr = tle->expr; else @@ -661,7 +663,7 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt, if (icolumns == NIL || attnos == NIL) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("INSERT has more expressions than target columns"))); + errmsg("INSERT has more expressions than target columns"))); col = (ResTarget *) lfirst(icolumns); Assert(IsA(col, ResTarget)); @@ -675,15 +677,14 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt, } /* - * Ensure that the targetlist has the same number of entries that - * were present in the columns list. Don't do the check unless - * an explicit columns list was given, though. - * statements. + * Ensure that the targetlist has the same number of entries that were + * present in the columns list. Don't do the check unless an explicit + * columns list was given, though. statements. */ if (stmt->cols != NIL && (icolumns != NIL || attnos != NIL)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("INSERT has more target columns than expressions"))); + errmsg("INSERT has more target columns than expressions"))); /* done building the range table and jointree */ qry->rtable = pstate->p_rtable; @@ -1054,7 +1055,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting NULL/NOT NULL declarations for \"%s.%s\"", - cxt->relation->relname, column->colname))); + cxt->relation->relname, column->colname))); column->is_not_null = FALSE; saw_nullable = true; break; @@ -1064,7 +1065,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting NULL/NOT NULL declarations for \"%s.%s\"", - cxt->relation->relname, column->colname))); + cxt->relation->relname, column->colname))); column->is_not_null = TRUE; saw_nullable = true; break; @@ -1074,7 +1075,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("multiple DEFAULT values specified for \"%s.%s\"", - cxt->relation->relname, column->colname))); + cxt->relation->relname, column->colname))); column->raw_default = constraint->raw_expr; Assert(constraint->cooked_expr == NULL); break; @@ -1170,7 +1171,7 @@ transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt, */ static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt, - InhRelation *inhRelation) + InhRelation * inhRelation) { AttrNumber parent_attno; @@ -1188,7 +1189,7 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt, inhRelation->relation->relname))); /* - * Check for SELECT privilages + * Check for SELECT privilages */ aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(), ACL_SELECT); @@ -1200,8 +1201,8 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt, constr = tupleDesc->constr; /* - * Insert the inherited attributes into the cxt for the - * new table definition. + * Insert the inherited attributes into the cxt for the new table + * definition. */ for (parent_attno = 1; parent_attno <= tupleDesc->natts; parent_attno++) @@ -1220,8 +1221,8 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt, /* * Create a new inherited column. * - * For constraints, ONLY the NOT NULL constraint is inherited - * by the new column definition per SQL99. + * For constraints, ONLY the NOT NULL constraint is inherited by the + * new column definition per SQL99. */ def = makeNode(ColumnDef); def->colname = pstrdup(attributeName); @@ -1265,9 +1266,8 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt, Assert(this_default != NULL); /* - * If default expr could contain any vars, we'd need to - * fix 'em, but it can't; so default is ready to apply to - * child. + * If default expr could contain any vars, we'd need to fix + * 'em, but it can't; so default is ready to apply to child. */ def->cooked_default = pstrdup(this_default); @@ -1275,9 +1275,9 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt, } /* - * Close the parent rel, but keep our AccessShareLock on it until - * xact commit. That will prevent someone else from deleting or - * ALTERing the parent before the child is committed. + * Close the parent rel, but keep our AccessShareLock on it until xact + * commit. That will prevent someone else from deleting or ALTERing + * the parent before the child is committed. */ heap_close(relation, NoLock); } @@ -1340,8 +1340,8 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) /* * Make sure referenced keys exist. If we are making a PRIMARY * KEY index, also make sure they are NOT NULL, if possible. - * (Although we could leave it to DefineIndex to mark the columns NOT - * NULL, it's more efficient to get it right the first time.) + * (Although we could leave it to DefineIndex to mark the columns + * NOT NULL, it's more efficient to get it right the first time.) */ foreach(keys, constraint->keys) { @@ -1390,8 +1390,8 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) if (rel->rd_rel->relkind != RELKIND_RELATION) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("inherited table \"%s\" is not a relation", - inh->relname))); + errmsg("inherited table \"%s\" is not a relation", + inh->relname))); for (count = 0; count < rel->rd_att->natts; count++) { Form_pg_attribute inhattr = rel->rd_att->attrs[count]; @@ -1402,11 +1402,13 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) if (strcmp(key, inhname) == 0) { found = true; + /* * We currently have no easy way to force an - * inherited column to be NOT NULL at creation, if - * its parent wasn't so already. We leave it to - * DefineIndex to fix things up in this case. + * inherited column to be NOT NULL at + * creation, if its parent wasn't so already. + * We leave it to DefineIndex to fix things up + * in this case. */ break; } @@ -1425,9 +1427,10 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) if (HeapTupleIsValid(atttuple)) { found = true; + /* - * If it's not already NOT NULL, leave it to DefineIndex - * to fix later. + * If it's not already NOT NULL, leave it to + * DefineIndex to fix later. */ ReleaseSysCache(atttuple); } @@ -1436,8 +1439,8 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) if (!found) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("column \"%s\" named in key does not exist", - key))); + errmsg("column \"%s\" named in key does not exist", + key))); /* Check for PRIMARY KEY(foo, foo) */ foreach(columns, index->indexParams) @@ -1446,10 +1449,10 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) if (iparam->name && strcmp(key, iparam->name) == 0) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), - /* translator: second %s is PRIMARY KEY or UNIQUE */ - errmsg("column \"%s\" appears twice in %s constraint", - key, - index->primary ? "PRIMARY KEY" : "UNIQUE"))); + /* translator: second %s is PRIMARY KEY or UNIQUE */ + errmsg("column \"%s\" appears twice in %s constraint", + key, + index->primary ? "PRIMARY KEY" : "UNIQUE"))); } /* OK, add it to the index definition */ @@ -1543,7 +1546,7 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) ereport(NOTICE, (errmsg("%s / %s%s will create implicit index \"%s\" for table \"%s\"", cxt->stmtType, - (strcmp(cxt->stmtType, "ALTER TABLE") == 0) ? "ADD " : "", + (strcmp(cxt->stmtType, "ALTER TABLE") == 0) ? "ADD " : "", (index->primary ? "PRIMARY KEY" : "UNIQUE"), index->idxname, cxt->relation->relname))); } @@ -1557,13 +1560,13 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt, return; ereport(NOTICE, - (errmsg("%s will create implicit trigger(s) for FOREIGN KEY check(s)", - cxt->stmtType))); + (errmsg("%s will create implicit trigger(s) for FOREIGN KEY check(s)", + cxt->stmtType))); /* * For ALTER TABLE ADD CONSTRAINT, nothing to do. For CREATE TABLE or - * ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD CONSTRAINT command - * to execute after the basic command is complete. + * ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD CONSTRAINT + * command to execute after the basic command is complete. * * Note: the ADD CONSTRAINT command must also execute after any index * creation commands. Thus, this should run after @@ -1575,7 +1578,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt, AlterTableStmt *alterstmt = makeNode(AlterTableStmt); List *fkclist; - alterstmt->subtype = 'c'; /* preprocessed add constraint */ + alterstmt->subtype = 'c'; /* preprocessed add constraint */ alterstmt->relation = cxt->relation; alterstmt->name = NULL; alterstmt->def = (Node *) cxt->fkconstraints; @@ -1628,7 +1631,7 @@ transformIndexStmt(ParseState *pstate, IndexStmt *stmt) /* take care of any index expressions */ foreach(l, stmt->indexParams) { - IndexElem *ielem = (IndexElem *) lfirst(l); + IndexElem *ielem = (IndexElem *) lfirst(l); if (ielem->expr) { @@ -1641,6 +1644,7 @@ transformIndexStmt(ParseState *pstate, IndexStmt *stmt) addRTEtoQuery(pstate, rte, false, true); } ielem->expr = transformExpr(pstate, ielem->expr); + /* * We check only that the result type is legitimate; this is * for consistency with what transformWhereClause() checks for @@ -1649,7 +1653,7 @@ transformIndexStmt(ParseState *pstate, IndexStmt *stmt) if (expression_returns_set(ielem->expr)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("index expression may not return a set"))); + errmsg("index expression may not return a set"))); } } @@ -1829,10 +1833,10 @@ transformRuleStmt(ParseState *pstate, RuleStmt *stmt, sub_qry = getInsertSelectQuery(top_subqry, NULL); /* - * If the sub_qry is a setop, we cannot attach any qualifications - * to it, because the planner won't notice them. This could - * perhaps be relaxed someday, but for now, we may as well reject - * such a rule immediately. + * If the sub_qry is a setop, we cannot attach any + * qualifications to it, because the planner won't notice + * them. This could perhaps be relaxed someday, but for now, + * we may as well reject such a rule immediately. */ if (sub_qry->setOperations != NULL && stmt->whereClause != NULL) ereport(ERROR, @@ -1854,12 +1858,12 @@ transformRuleStmt(ParseState *pstate, RuleStmt *stmt, case CMD_SELECT: if (has_old) ereport(ERROR, - (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("ON SELECT rule may not use OLD"))); + (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("ON SELECT rule may not use OLD"))); if (has_new) ereport(ERROR, - (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("ON SELECT rule may not use NEW"))); + (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("ON SELECT rule may not use NEW"))); break; case CMD_UPDATE: /* both are OK */ @@ -1867,14 +1871,14 @@ transformRuleStmt(ParseState *pstate, RuleStmt *stmt, case CMD_INSERT: if (has_old) ereport(ERROR, - (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("ON INSERT rule may not use OLD"))); + (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("ON INSERT rule may not use OLD"))); break; case CMD_DELETE: if (has_new) ereport(ERROR, - (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("ON DELETE rule may not use NEW"))); + (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("ON DELETE rule may not use NEW"))); break; default: elog(ERROR, "unrecognized event type: %d", @@ -1902,9 +1906,10 @@ transformRuleStmt(ParseState *pstate, RuleStmt *stmt, if (has_old || (has_new && stmt->event == CMD_UPDATE)) { /* - * If sub_qry is a setop, manipulating its jointree will do - * no good at all, because the jointree is dummy. (This - * should be a can't-happen case because of prior tests.) + * If sub_qry is a setop, manipulating its jointree will + * do no good at all, because the jointree is dummy. + * (This should be a can't-happen case because of prior + * tests.) */ if (sub_qry->setOperations != NULL) ereport(ERROR, @@ -1978,7 +1983,7 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt) qry->sortClause = transformSortClause(pstate, stmt->sortClause, qry->targetList, - true /* fix unknowns */); + true /* fix unknowns */ ); qry->groupClause = transformGroupClause(pstate, stmt->groupClause, @@ -2107,10 +2112,10 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt) * make lists of the dummy vars and their names for use in parsing * ORDER BY. * - * Note: we use leftmostRTI as the varno of the dummy variables. - * It shouldn't matter too much which RT index they have, as long - * as they have one that corresponds to a real RT entry; else funny - * things may happen when the tree is mashed by rule rewriting. + * Note: we use leftmostRTI as the varno of the dummy variables. It + * shouldn't matter too much which RT index they have, as long as they + * have one that corresponds to a real RT entry; else funny things may + * happen when the tree is mashed by rule rewriting. */ qry->targetList = NIL; targetvars = NIL; @@ -2144,8 +2149,8 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt) /* * Handle SELECT INTO/CREATE TABLE AS. * - * Any column names from CREATE TABLE AS need to be attached to both - * the top level and the leftmost subquery. We do not do this earlier + * Any column names from CREATE TABLE AS need to be attached to both the + * top level and the leftmost subquery. We do not do this earlier * because we do *not* want the targetnames list to be affected. */ qry->into = into; @@ -2192,7 +2197,7 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt) qry->sortClause = transformSortClause(pstate, sortClause, qry->targetList, - false /* no unknowns expected */); + false /* no unknowns expected */ ); pstate->p_namespace = sv_namespace; pstate->p_rtable = sv_rtable; @@ -2290,9 +2295,9 @@ transformSetOperationTree(ParseState *pstate, SelectStmt *stmt) /* * Check for bogus references to Vars on the current query level - * (but upper-level references are okay). - * Normally this can't happen because the namespace will be empty, - * but it could happen if we are inside a rule. + * (but upper-level references are okay). Normally this can't + * happen because the namespace will be empty, but it could happen + * if we are inside a rule. */ if (pstate->p_namespace) { @@ -2352,8 +2357,8 @@ transformSetOperationTree(ParseState *pstate, SelectStmt *stmt) if (length(lcoltypes) != length(rcoltypes)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("each %s query must have the same number of columns", - context))); + errmsg("each %s query must have the same number of columns", + context))); op->colTypes = NIL; while (lcoltypes != NIL) { @@ -2422,7 +2427,7 @@ applyColumnNames(List *dst, List *src) if (length(src) > length(dst)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("CREATE TABLE AS specifies too many column names"))); + errmsg("CREATE TABLE AS specifies too many column names"))); while (src != NIL && dst != NIL) { @@ -2538,8 +2543,8 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt, * handling are 'A'dd column and Add 'C'onstraint. These largely * re-use code from CREATE TABLE. * - * If we need to do any parse transformation, get exclusive lock on - * the relation to make sure it won't change before we execute the + * If we need to do any parse transformation, get exclusive lock on the + * relation to make sure it won't change before we execute the * command. */ switch (stmt->subtype) @@ -2574,7 +2579,7 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt, *extras_before = nconc(*extras_before, cxt.blist); *extras_after = nconc(cxt.alist, *extras_after); - heap_close(rel, NoLock); /* close rel, keep lock */ + heap_close(rel, NoLock); /* close rel, keep lock */ break; case 'C': @@ -2614,7 +2619,7 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt, *extras_before = nconc(*extras_before, cxt.blist); *extras_after = nconc(cxt.alist, *extras_after); - heap_close(rel, NoLock); /* close rel, keep lock */ + heap_close(rel, NoLock); /* close rel, keep lock */ break; case 'c': @@ -2638,7 +2643,7 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt, } static Query * -transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt) +transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt * stmt) { Query *result = makeNode(Query); List *extras_before = NIL, @@ -2672,7 +2677,7 @@ transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt) { Query *result = makeNode(Query); List *argtype_oids = NIL; /* argtype OIDs in a list */ - Oid *argtoids = NULL; /* and as an array */ + Oid *argtoids = NULL; /* and as an array */ int nargs; List *queries; @@ -2757,11 +2762,11 @@ transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt) if (pstate->p_hasSubLinks) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot use sub-select in EXECUTE parameter"))); + errmsg("cannot use sub-select in EXECUTE parameter"))); if (pstate->p_hasAggs) ereport(ERROR, (errcode(ERRCODE_GROUPING_ERROR), - errmsg("cannot use aggregate in EXECUTE parameter"))); + errmsg("cannot use aggregate in EXECUTE parameter"))); given_type_id = exprType(expr); expected_type_id = lfirsto(paramtypes); @@ -2801,15 +2806,15 @@ CheckSelectForUpdate(Query *qry) if (qry->distinctClause != NIL) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("SELECT FOR UPDATE is not allowed with DISTINCT clause"))); + errmsg("SELECT FOR UPDATE is not allowed with DISTINCT clause"))); if (qry->groupClause != NIL) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("SELECT FOR UPDATE is not allowed with GROUP BY clause"))); + errmsg("SELECT FOR UPDATE is not allowed with GROUP BY clause"))); if (qry->hasAggs) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("SELECT FOR UPDATE is not allowed with AGGREGATE"))); + errmsg("SELECT FOR UPDATE is not allowed with AGGREGATE"))); } static void @@ -2915,7 +2920,7 @@ relationHasPrimaryKey(Oid relationOid) indexTuple = SearchSysCache(INDEXRELID, ObjectIdGetDatum(indexoid), 0, 0, 0); - if (!HeapTupleIsValid(indexTuple)) /* should not happen */ + if (!HeapTupleIsValid(indexTuple)) /* should not happen */ elog(ERROR, "cache lookup failed for index %u", indexoid); result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary; ReleaseSysCache(indexTuple); @@ -2981,7 +2986,7 @@ transformConstraintAttrs(List *constraintList) !IsA(lastprimarynode, FkConstraint)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("misplaced NOT DEFERRABLE clause"))); + errmsg("misplaced NOT DEFERRABLE clause"))); if (saw_deferrability) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), @@ -2999,7 +3004,7 @@ transformConstraintAttrs(List *constraintList) !IsA(lastprimarynode, FkConstraint)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("misplaced INITIALLY DEFERRED clause"))); + errmsg("misplaced INITIALLY DEFERRED clause"))); if (saw_initially) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), @@ -3023,7 +3028,7 @@ transformConstraintAttrs(List *constraintList) !IsA(lastprimarynode, FkConstraint)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("misplaced INITIALLY IMMEDIATE clause"))); + errmsg("misplaced INITIALLY IMMEDIATE clause"))); if (saw_initially) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), @@ -3135,10 +3140,10 @@ analyzeCreateSchemaStmt(CreateSchemaStmt *stmt) elp->relation->schemaname = cxt.schemaname; else if (strcmp(cxt.schemaname, elp->relation->schemaname) != 0) ereport(ERROR, - (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION), - errmsg("CREATE specifies a schema (%s)" - " different from the one being created (%s)", - elp->relation->schemaname, cxt.schemaname))); + (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION), + errmsg("CREATE specifies a schema (%s)" + " different from the one being created (%s)", + elp->relation->schemaname, cxt.schemaname))); /* * XXX todo: deal with constraints @@ -3156,10 +3161,10 @@ analyzeCreateSchemaStmt(CreateSchemaStmt *stmt) elp->view->schemaname = cxt.schemaname; else if (strcmp(cxt.schemaname, elp->view->schemaname) != 0) ereport(ERROR, - (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION), - errmsg("CREATE specifies a schema (%s)" - " different from the one being created (%s)", - elp->view->schemaname, cxt.schemaname))); + (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION), + errmsg("CREATE specifies a schema (%s)" + " different from the one being created (%s)", + elp->view->schemaname, cxt.schemaname))); /* * XXX todo: deal with references between views @@ -3195,7 +3200,7 @@ analyzeCreateSchemaStmt(CreateSchemaStmt *stmt) */ static bool check_parameter_resolution_walker(Node *node, - check_parameter_resolution_context *context) + check_parameter_resolution_context * context) { if (node == NULL) return false; @@ -3207,17 +3212,17 @@ check_parameter_resolution_walker(Node *node, { int paramno = param->paramid; - if (paramno <= 0 || /* shouldn't happen, but... */ + if (paramno <= 0 || /* shouldn't happen, but... */ paramno > context->numParams) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_PARAMETER), errmsg("there is no parameter $%d", paramno))); - if (param->paramtype != context->paramTypes[paramno-1]) + if (param->paramtype != context->paramTypes[paramno - 1]) ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_PARAMETER), - errmsg("could not determine datatype of parameter $%d", - paramno))); + errmsg("could not determine datatype of parameter $%d", + paramno))); } return false; } diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c index 90eaf18bf5..d9ef4ed74d 100644 --- a/src/backend/parser/parse_agg.c +++ b/src/backend/parser/parse_agg.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_agg.c,v 1.55 2003/07/19 20:20:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_agg.c,v 1.56 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -44,7 +44,7 @@ static bool check_ungrouped_columns_walker(Node *node, * Finish initial transformation of an aggregate call * * parse_func.c has recognized the function as an aggregate, and has set - * up all the fields of the Aggref except agglevelsup. Here we must + * up all the fields of the Aggref except agglevelsup. Here we must * determine which query level the aggregate actually belongs to, set * agglevelsup accordingly, and mark p_hasAggs true in the corresponding * pstate level. @@ -56,22 +56,22 @@ transformAggregateCall(ParseState *pstate, Aggref *agg) /* * The aggregate's level is the same as the level of the lowest-level - * variable or aggregate in its argument; or if it contains no variables - * at all, we presume it to be local. + * variable or aggregate in its argument; or if it contains no + * variables at all, we presume it to be local. */ min_varlevel = find_minimum_var_level((Node *) agg->target); /* * An aggregate can't directly contain another aggregate call of the - * same level (though outer aggs are okay). We can skip this check - * if we didn't find any local vars or aggs. + * same level (though outer aggs are okay). We can skip this check if + * we didn't find any local vars or aggs. */ if (min_varlevel == 0) { if (checkExprHasAggs((Node *) agg->target)) ereport(ERROR, (errcode(ERRCODE_GROUPING_ERROR), - errmsg("aggregate function calls may not be nested"))); + errmsg("aggregate function calls may not be nested"))); } if (min_varlevel < 0) @@ -142,17 +142,17 @@ parseCheckAggregates(ParseState *pstate, Query *qry) if (checkExprHasAggs(expr)) ereport(ERROR, (errcode(ERRCODE_GROUPING_ERROR), - errmsg("aggregates not allowed in GROUP BY clause"))); + errmsg("aggregates not allowed in GROUP BY clause"))); groupClauses = lcons(expr, groupClauses); if (!IsA(expr, Var)) have_non_var_grouping = true; } /* - * If there are join alias vars involved, we have to flatten them - * to the underlying vars, so that aliased and unaliased vars will be - * correctly taken as equal. We can skip the expense of doing this - * if no rangetable entries are RTE_JOIN kind. + * If there are join alias vars involved, we have to flatten them to + * the underlying vars, so that aliased and unaliased vars will be + * correctly taken as equal. We can skip the expense of doing this if + * no rangetable entries are RTE_JOIN kind. */ hasJoinRTEs = false; foreach(lst, pstate->p_rtable) @@ -168,7 +168,7 @@ parseCheckAggregates(ParseState *pstate, Query *qry) if (hasJoinRTEs) groupClauses = (List *) flatten_join_alias_vars(qry, - (Node *) groupClauses); + (Node *) groupClauses); /* * Check the targetlist and HAVING clause for ungrouped variables. @@ -235,22 +235,22 @@ check_ungrouped_columns_walker(Node *node, /* * If we find an aggregate call of the original level, do not recurse - * into its arguments; ungrouped vars in the arguments are not an error. - * We can also skip looking at the arguments of aggregates of higher - * levels, since they could not possibly contain Vars that are of concern - * to us (see transformAggregateCall). We do need to look into the - * arguments of aggregates of lower levels, however. + * into its arguments; ungrouped vars in the arguments are not an + * error. We can also skip looking at the arguments of aggregates of + * higher levels, since they could not possibly contain Vars that are + * of concern to us (see transformAggregateCall). We do need to look + * into the arguments of aggregates of lower levels, however. */ if (IsA(node, Aggref) && (int) ((Aggref *) node)->agglevelsup >= context->sublevels_up) return false; /* - * If we have any GROUP BY items that are not simple Vars, - * check to see if subexpression as a whole matches any GROUP BY item. - * We need to do this at every recursion level so that we recognize - * GROUPed-BY expressions before reaching variables within them. - * But this only works at the outer query level, as noted above. + * If we have any GROUP BY items that are not simple Vars, check to + * see if subexpression as a whole matches any GROUP BY item. We need + * to do this at every recursion level so that we recognize GROUPed-BY + * expressions before reaching variables within them. But this only + * works at the outer query level, as noted above. */ if (context->have_non_var_grouping && context->sublevels_up == 0) { @@ -264,7 +264,7 @@ check_ungrouped_columns_walker(Node *node, /* * If we have an ungrouped Var of the original query level, we have a * failure. Vars below the original query level are not a problem, - * and neither are Vars from above it. (If such Vars are ungrouped as + * and neither are Vars from above it. (If such Vars are ungrouped as * far as their own query level is concerned, that's someone else's * problem...) */ @@ -276,6 +276,7 @@ check_ungrouped_columns_walker(Node *node, if (var->varlevelsup != context->sublevels_up) return false; /* it's not local to my query, ignore */ + /* * Check for a match, if we didn't do it above. */ @@ -283,13 +284,13 @@ check_ungrouped_columns_walker(Node *node, { foreach(gl, context->groupClauses) { - Var *gvar = (Var *) lfirst(gl); + Var *gvar = (Var *) lfirst(gl); if (IsA(gvar, Var) && gvar->varno == var->varno && gvar->varattno == var->varattno && gvar->varlevelsup == 0) - return false; /* acceptable, we're okay */ + return false; /* acceptable, we're okay */ } } @@ -365,10 +366,10 @@ build_aggregate_fnexprs(Oid agg_input_type, (void) get_func_signature(transfn_oid, transfn_arg_types, &transfn_nargs); /* - * Build arg list to use in the transfn FuncExpr node. We really - * only care that transfn can discover the actual argument types - * at runtime using get_fn_expr_argtype(), so it's okay to use - * Param nodes that don't correspond to any real Param. + * Build arg list to use in the transfn FuncExpr node. We really only + * care that transfn can discover the actual argument types at runtime + * using get_fn_expr_argtype(), so it's okay to use Param nodes that + * don't correspond to any real Param. */ arg0 = makeNode(Param); arg0->paramkind = PARAM_EXEC; @@ -385,33 +386,31 @@ build_aggregate_fnexprs(Oid agg_input_type, args = makeList2(arg0, arg1); } else - { args = makeList1(arg0); + + *transfnexpr = (Expr *) makeFuncExpr(transfn_oid, + agg_state_type, + args, + COERCE_DONTCARE); + + /* see if we have a final function */ + if (!OidIsValid(finalfn_oid)) + { + *finalfnexpr = NULL; + return; } - *transfnexpr = (Expr *) makeFuncExpr(transfn_oid, - agg_state_type, - args, - COERCE_DONTCARE); - - /* see if we have a final function */ - if (!OidIsValid(finalfn_oid)) - { - *finalfnexpr = NULL; - return; - } - - /* - * Build expr tree for final function - */ + /* + * Build expr tree for final function + */ arg0 = makeNode(Param); arg0->paramkind = PARAM_EXEC; arg0->paramid = -1; arg0->paramtype = agg_state_type; args = makeList1(arg0); - *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid, - agg_result_type, - args, - COERCE_DONTCARE); + *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid, + agg_result_type, + args, + COERCE_DONTCARE); } diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c index 4b61d59b4a..59cf251699 100644 --- a/src/backend/parser/parse_clause.c +++ b/src/backend/parser/parse_clause.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_clause.c,v 1.118 2003/07/19 20:20:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_clause.c,v 1.119 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -60,8 +60,8 @@ static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype, static TargetEntry *findTargetlistEntry(ParseState *pstate, Node *node, List *tlist, int clause); static List *addTargetToSortList(ParseState *pstate, TargetEntry *tle, - List *sortlist, List *targetlist, - List *opname, bool resolveUnknown); + List *sortlist, List *targetlist, + List *opname, bool resolveUnknown); /* @@ -337,7 +337,7 @@ transformJoinOnClause(ParseState *pstate, JoinExpr *j, ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), errmsg("JOIN/ON clause refers to \"%s\", which is not part of JOIN", - rt_fetch(varno, pstate->p_rtable)->eref->aliasname))); + rt_fetch(varno, pstate->p_rtable)->eref->aliasname))); } } bms_free(clause_varnos); @@ -422,17 +422,19 @@ transformRangeSubselect(ParseState *pstate, RangeSubselect *r) errmsg("sub-select in FROM may not have SELECT INTO"))); /* - * The subquery cannot make use of any variables from FROM items created - * earlier in the current query. Per SQL92, the scope of a FROM item - * does not include other FROM items. Formerly we hacked the namespace - * so that the other variables weren't even visible, but it seems more - * useful to leave them visible and give a specific error message. + * The subquery cannot make use of any variables from FROM items + * created earlier in the current query. Per SQL92, the scope of a + * FROM item does not include other FROM items. Formerly we hacked + * the namespace so that the other variables weren't even visible, but + * it seems more useful to leave them visible and give a specific + * error message. * * XXX this will need further work to support SQL99's LATERAL() feature, * wherein such references would indeed be legal. * * We can skip groveling through the subquery if there's not anything - * visible in the current query. Also note that outer references are OK. + * visible in the current query. Also note that outer references are + * OK. */ if (pstate->p_namespace) { @@ -482,9 +484,9 @@ transformRangeFunction(ParseState *pstate, RangeFunction *r) /* * The function parameters cannot make use of any variables from other - * FROM items. (Compare to transformRangeSubselect(); the coding is - * different though because we didn't parse as a sub-select with its own - * level of namespace.) + * FROM items. (Compare to transformRangeSubselect(); the coding is + * different though because we didn't parse as a sub-select with its + * own level of namespace.) * * XXX this will need further work to support SQL99's LATERAL() feature, * wherein such references would indeed be legal. @@ -1017,7 +1019,7 @@ transformLimitClause(ParseState *pstate, Node *clause, { ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), - /* translator: %s is name of a SQL construct, eg LIMIT */ + /* translator: %s is name of a SQL construct, eg LIMIT */ errmsg("argument of %s must not contain variables", constructName))); } @@ -1025,7 +1027,7 @@ transformLimitClause(ParseState *pstate, Node *clause, { ereport(ERROR, (errcode(ERRCODE_GROUPING_ERROR), - /* translator: %s is name of a SQL construct, eg LIMIT */ + /* translator: %s is name of a SQL construct, eg LIMIT */ errmsg("argument of %s must not contain aggregates", constructName))); } @@ -1033,7 +1035,7 @@ transformLimitClause(ParseState *pstate, Node *clause, { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - /* translator: %s is name of a SQL construct, eg LIMIT */ + /* translator: %s is name of a SQL construct, eg LIMIT */ errmsg("argument of %s must not contain sub-selects", constructName))); } @@ -1135,7 +1137,11 @@ findTargetlistEntry(ParseState *pstate, Node *node, List *tlist, int clause) if (!equal(target_result->expr, tle->expr)) ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_COLUMN), - /* translator: first %s is name of a SQL construct, eg ORDER BY */ + + /* + * translator: first %s is name of a SQL + * construct, eg ORDER BY + */ errmsg("%s \"%s\" is ambiguous", clauseText[clause], name))); } @@ -1157,7 +1163,7 @@ findTargetlistEntry(ParseState *pstate, Node *node, List *tlist, int clause) if (!IsA(val, Integer)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - /* translator: %s is name of a SQL construct, eg ORDER BY */ + /* translator: %s is name of a SQL construct, eg ORDER BY */ errmsg("non-integer constant in %s", clauseText[clause]))); target_pos = intVal(val); @@ -1174,7 +1180,7 @@ findTargetlistEntry(ParseState *pstate, Node *node, List *tlist, int clause) } ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), - /* translator: %s is name of a SQL construct, eg ORDER BY */ + /* translator: %s is name of a SQL construct, eg ORDER BY */ errmsg("%s position %d is not in target list", clauseText[clause], target_pos))); } @@ -1250,10 +1256,10 @@ transformGroupClause(ParseState *pstate, List *grouplist, /* * If the GROUP BY clause matches the ORDER BY clause, we want to * adopt the ordering operators from the latter rather than using - * the default ops. This allows "GROUP BY foo ORDER BY foo DESC" to - * be done with only one sort step. Note we are assuming that any - * user-supplied ordering operator will bring equal values together, - * which is all that GROUP BY needs. + * the default ops. This allows "GROUP BY foo ORDER BY foo DESC" + * to be done with only one sort step. Note we are assuming that + * any user-supplied ordering operator will bring equal values + * together, which is all that GROUP BY needs. */ if (sortClause && ((SortClause *) lfirst(sortClause))->tleSortGroupRef == @@ -1422,7 +1428,7 @@ transformDistinctClause(ParseState *pstate, List *distinctlist, break; } } - if (slitem == NIL) /* should not happen */ + if (slitem == NIL) /* should not happen */ elog(ERROR, "failed to add DISTINCT ON clause to target list"); } } diff --git a/src/backend/parser/parse_coerce.c b/src/backend/parser/parse_coerce.c index 351bc00c70..9995fcc832 100644 --- a/src/backend/parser/parse_coerce.c +++ b/src/backend/parser/parse_coerce.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_coerce.c,v 2.106 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_coerce.c,v 2.107 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,8 +30,8 @@ static Node *coerce_type_typmod(Node *node, - Oid targetTypeId, int32 targetTypMod, - CoercionForm cformat, bool isExplicit); + Oid targetTypeId, int32 targetTypMod, + CoercionForm cformat, bool isExplicit); /* @@ -39,12 +39,12 @@ static Node *coerce_type_typmod(Node *node, * Convert an expression to a target type and typmod. * * This is the general-purpose entry point for arbitrary type coercion - * operations. Direct use of the component operations can_coerce_type, + * operations. Direct use of the component operations can_coerce_type, * coerce_type, and coerce_type_typmod should be restricted to special * cases (eg, when the conversion is expected to succeed). * * Returns the possibly-transformed expression tree, or NULL if the type - * conversion is not possible. (We do this, rather than ereport'ing directly, + * conversion is not possible. (We do this, rather than ereport'ing directly, * so that callers can generate custom error messages indicating context.) * * pstate - parse state (can be NULL, see coerce_type) @@ -66,14 +66,14 @@ coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, else if (ccontext >= COERCION_ASSIGNMENT) { /* - * String hacks to get transparent conversions for char and varchar: - * if a coercion to text is available, use it for forced coercions to - * char(n) or varchar(n) or domains thereof. + * String hacks to get transparent conversions for char and + * varchar: if a coercion to text is available, use it for forced + * coercions to char(n) or varchar(n) or domains thereof. * * This is pretty grotty, but seems easier to maintain than providing * entries in pg_cast that parallel all the ones for text. */ - Oid targetbasetype = getBaseType(targettype); + Oid targetbasetype = getBaseType(targettype); if (targetbasetype == BPCHAROID || targetbasetype == VARCHAROID) { @@ -91,7 +91,10 @@ coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, } else { - /* need a RelabelType if no typmod coercion will be performed */ + /* + * need a RelabelType if no typmod coercion will be + * performed + */ if (targettypmod < 0) expr = (Node *) makeRelabelType((Expr *) expr, targettype, -1, @@ -127,13 +130,13 @@ coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, * The caller should already have determined that the coercion is possible; * see can_coerce_type. * - * No coercion to a typmod (length) is performed here. The caller must + * No coercion to a typmod (length) is performed here. The caller must * call coerce_type_typmod as well, if a typmod constraint is wanted. * (But if the target type is a domain, it may internally contain a * typmod constraint, which will be applied inside coerce_to_domain.) * * pstate is only used in the case that we are able to resolve the type of - * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the + * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the * caller does not want type information updated for Params. */ Node * @@ -191,8 +194,9 @@ coerce_type(ParseState *pstate, Node *node, * Any length constraint will be applied later by our caller. * * Note that we call stringTypeDatum using the domain's pg_type - * row, if it's a domain. This works because the domain row has - * the same typinput and typelem as the base type --- ugly... + * row, if it's a domain. This works because the domain row + * has the same typinput and typelem as the base type --- + * ugly... */ newcon->constvalue = stringTypeDatum(targetType, val, -1); pfree(val); @@ -232,12 +236,12 @@ coerce_type(ParseState *pstate, Node *node, (errcode(ERRCODE_UNDEFINED_PARAMETER), errmsg("there is no parameter $%d", paramno))); - if (toppstate->p_paramtypes[paramno-1] == UNKNOWNOID) + if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID) { /* We've successfully resolved the type */ - toppstate->p_paramtypes[paramno-1] = targetTypeId; + toppstate->p_paramtypes[paramno - 1] = targetTypeId; } - else if (toppstate->p_paramtypes[paramno-1] == targetTypeId) + else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId) { /* We previously resolved the type, and it matches */ } @@ -246,10 +250,10 @@ coerce_type(ParseState *pstate, Node *node, /* Ooops */ ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_PARAMETER), - errmsg("inconsistent types deduced for parameter $%d", - paramno), + errmsg("inconsistent types deduced for parameter $%d", + paramno), errdetail("%s versus %s", - format_type_be(toppstate->p_paramtypes[paramno-1]), + format_type_be(toppstate->p_paramtypes[paramno - 1]), format_type_be(targetTypeId)))); } @@ -298,7 +302,7 @@ coerce_type(ParseState *pstate, Node *node, * higher-level code. * * Also, domains may have value restrictions beyond the base type - * that must be accounted for. If the destination is a domain + * that must be accounted for. If the destination is a domain * then we won't need a RelabelType node. */ result = coerce_to_domain(node, InvalidOid, targetTypeId, @@ -306,10 +310,11 @@ coerce_type(ParseState *pstate, Node *node, if (result == node) { /* - * XXX could we label result with exprTypmod(node) instead of - * default -1 typmod, to save a possible length-coercion - * later? Would work if both types have same interpretation of - * typmod, which is likely but not certain. + * XXX could we label result with exprTypmod(node) instead + * of default -1 typmod, to save a possible + * length-coercion later? Would work if both types have + * same interpretation of typmod, which is likely but not + * certain. */ result = (Node *) makeRelabelType((Expr *) result, targetTypeId, -1, @@ -386,7 +391,7 @@ can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, if (targetTypeId == ANYARRAYOID || targetTypeId == ANYELEMENTOID) { - have_generics = true; /* do more checking later */ + have_generics = true; /* do more checking later */ continue; } @@ -437,7 +442,7 @@ Node * coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId, CoercionForm cformat) { CoerceToDomain *result; - int32 typmod; + int32 typmod; /* Get the base type if it hasn't been supplied */ if (baseTypeId == InvalidOid) @@ -448,17 +453,18 @@ coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId, CoercionForm cformat) return arg; /* - * If the domain applies a typmod to its base type, build the appropriate - * coercion step. Mark it implicit for display purposes, because we don't - * want it shown separately by ruleutils.c; but the isExplicit flag passed - * to the conversion function depends on the manner in which the domain - * coercion is invoked, so that the semantics of implicit and explicit - * coercion differ. (Is that really the behavior we want?) + * If the domain applies a typmod to its base type, build the + * appropriate coercion step. Mark it implicit for display purposes, + * because we don't want it shown separately by ruleutils.c; but the + * isExplicit flag passed to the conversion function depends on the + * manner in which the domain coercion is invoked, so that the + * semantics of implicit and explicit coercion differ. (Is that + * really the behavior we want?) * * NOTE: because we apply this as part of the fixed expression structure, - * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that - * would be safe to do anyway, without lots of knowledge about what the - * base type thinks the typmod means. + * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that + * that would be safe to do anyway, without lots of knowledge about + * what the base type thinks the typmod means. */ typmod = get_typtypmod(typeId); if (typmod >= 0) @@ -467,9 +473,10 @@ coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId, CoercionForm cformat) (cformat != COERCE_IMPLICIT_CAST)); /* - * Now build the domain coercion node. This represents run-time checking - * of any constraints currently attached to the domain. This also - * ensures that the expression is properly labeled as to result type. + * Now build the domain coercion node. This represents run-time + * checking of any constraints currently attached to the domain. This + * also ensures that the expression is properly labeled as to result + * type. */ result = makeNode(CoerceToDomain); result->arg = (Expr *) arg; @@ -568,15 +575,15 @@ coerce_to_boolean(ParseState *pstate, Node *node, if (node == NULL) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - /* translator: first %s is name of a SQL construct, eg WHERE */ - errmsg("argument of %s must be type boolean, not type %s", - constructName, format_type_be(inputTypeId)))); + /* translator: first %s is name of a SQL construct, eg WHERE */ + errmsg("argument of %s must be type boolean, not type %s", + constructName, format_type_be(inputTypeId)))); } if (expression_returns_set(node)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - /* translator: %s is name of a SQL construct, eg WHERE */ + /* translator: %s is name of a SQL construct, eg WHERE */ errmsg("argument of %s must not return a set", constructName))); @@ -607,15 +614,15 @@ coerce_to_integer(ParseState *pstate, Node *node, if (node == NULL) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - /* translator: first %s is name of a SQL construct, eg LIMIT */ - errmsg("argument of %s must be type integer, not type %s", - constructName, format_type_be(inputTypeId)))); + /* translator: first %s is name of a SQL construct, eg LIMIT */ + errmsg("argument of %s must be type integer, not type %s", + constructName, format_type_be(inputTypeId)))); } if (expression_returns_set(node)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - /* translator: %s is name of a SQL construct, eg LIMIT */ + /* translator: %s is name of a SQL construct, eg LIMIT */ errmsg("argument of %s must not return a set", constructName))); @@ -664,19 +671,24 @@ select_common_type(List *typeids, const char *context) */ ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - /* translator: first %s is name of a SQL construct, eg CASE */ + + /* + * translator: first %s is name of a SQL construct, eg + * CASE + */ errmsg("%s types %s and %s cannot be matched", context, format_type_be(ptype), format_type_be(ntype)))); } else if (!IsPreferredType(pcategory, ptype) && - can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) && - !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT)) + can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) && + !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT)) { /* - * take new type if can coerce to it implicitly but not the - * other way; but if we have a preferred type, stay on it. + * take new type if can coerce to it implicitly but not + * the other way; but if we have a preferred type, stay on + * it. */ ptype = ntype; pcategory = TypeCategory(ptype); @@ -725,7 +737,7 @@ coerce_to_common_type(ParseState *pstate, Node *node, else ereport(ERROR, (errcode(ERRCODE_CANNOT_COERCE), - /* translator: first %s is name of a SQL construct, eg CASE */ + /* translator: first %s is name of a SQL construct, eg CASE */ errmsg("%s could not convert type %s to %s", context, format_type_be(inputTypeId), @@ -744,8 +756,8 @@ coerce_to_common_type(ParseState *pstate, Node *node, * and must in fact be varlena arrays. * 2) All arguments declared ANYELEMENT must have matching datatypes. * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure - * the actual ANYELEMENT datatype is in fact the element type for - * the actual ANYARRAY datatype. + * the actual ANYELEMENT datatype is in fact the element type for + * the actual ANYARRAY datatype. * * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT * or ANYARRAY argument, assume it is okay. @@ -763,13 +775,13 @@ check_generic_type_consistency(Oid *actual_arg_types, Oid array_typelem; /* - * Loop through the arguments to see if we have any that are - * ANYARRAY or ANYELEMENT. If so, require the actual types to be + * Loop through the arguments to see if we have any that are ANYARRAY + * or ANYELEMENT. If so, require the actual types to be * self-consistent */ for (j = 0; j < nargs; j++) { - Oid actual_type = actual_arg_types[j]; + Oid actual_type = actual_arg_types[j]; if (declared_arg_types[j] == ANYELEMENTOID) { @@ -798,7 +810,10 @@ check_generic_type_consistency(Oid *actual_arg_types, if (!OidIsValid(elem_typeid)) { - /* if we don't have an element type yet, use the one we just got */ + /* + * if we don't have an element type yet, use the one we just + * got + */ elem_typeid = array_typelem; } else if (array_typelem != elem_typeid) @@ -831,23 +846,23 @@ check_generic_type_consistency(Oid *actual_arg_types, * if it is declared ANYARRAY or ANYELEMENT: * * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the - * argument's actual type as the function's return type. + * argument's actual type as the function's return type. * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument - * is ANYELEMENT, use the actual type of the argument to determine - * the function's return type, i.e. the element type's corresponding - * array type. + * is ANYELEMENT, use the actual type of the argument to determine + * the function's return type, i.e. the element type's corresponding + * array type. * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT, - * generate an ERROR. This condition is prevented by CREATE FUNCTION - * and is therefore not expected here. + * generate an ERROR. This condition is prevented by CREATE FUNCTION + * and is therefore not expected here. * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the - * argument's actual type as the function's return type. + * argument's actual type as the function's return type. * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any - * argument is ANYARRAY, use the actual type of the argument to determine - * the function's return type, i.e. the array type's corresponding - * element type. + * argument is ANYARRAY, use the actual type of the argument to determine + * the function's return type, i.e. the array type's corresponding + * element type. * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT, - * generate an ERROR. This condition is prevented by CREATE FUNCTION - * and is therefore not expected here. + * generate an ERROR. This condition is prevented by CREATE FUNCTION + * and is therefore not expected here. */ Oid enforce_generic_type_consistency(Oid *actual_arg_types, @@ -863,13 +878,13 @@ enforce_generic_type_consistency(Oid *actual_arg_types, Oid array_typelem = InvalidOid; /* - * Loop through the arguments to see if we have any that are - * ANYARRAY or ANYELEMENT. If so, require the actual types to be + * Loop through the arguments to see if we have any that are ANYARRAY + * or ANYELEMENT. If so, require the actual types to be * self-consistent */ for (j = 0; j < nargs; j++) { - Oid actual_type = actual_arg_types[j]; + Oid actual_type = actual_arg_types[j]; if (declared_arg_types[j] == ANYELEMENTOID) { @@ -882,7 +897,7 @@ enforce_generic_type_consistency(Oid *actual_arg_types, if (OidIsValid(elem_typeid) && actual_type != elem_typeid) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("arguments declared ANYELEMENT are not all alike"), + errmsg("arguments declared ANYELEMENT are not all alike"), errdetail("%s versus %s", format_type_be(elem_typeid), format_type_be(actual_type)))); @@ -899,7 +914,7 @@ enforce_generic_type_consistency(Oid *actual_arg_types, if (OidIsValid(array_typeid) && actual_type != array_typeid) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("arguments declared ANYARRAY are not all alike"), + errmsg("arguments declared ANYARRAY are not all alike"), errdetail("%s versus %s", format_type_be(array_typeid), format_type_be(actual_type)))); @@ -921,12 +936,15 @@ enforce_generic_type_consistency(Oid *actual_arg_types, if (!OidIsValid(array_typelem)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("argument declared ANYARRAY is not an array but %s", - format_type_be(array_typeid)))); + errmsg("argument declared ANYARRAY is not an array but %s", + format_type_be(array_typeid)))); if (!OidIsValid(elem_typeid)) { - /* if we don't have an element type yet, use the one we just got */ + /* + * if we don't have an element type yet, use the one we just + * got + */ elem_typeid = array_typelem; } else if (array_typelem != elem_typeid) @@ -955,15 +973,13 @@ enforce_generic_type_consistency(Oid *actual_arg_types, { for (j = 0; j < nargs; j++) { - Oid actual_type = actual_arg_types[j]; + Oid actual_type = actual_arg_types[j]; if (actual_type != UNKNOWNOID) continue; if (declared_arg_types[j] == ANYELEMENTOID) - { declared_arg_types[j] = elem_typeid; - } else if (declared_arg_types[j] == ANYARRAYOID) { if (!OidIsValid(array_typeid)) @@ -989,8 +1005,8 @@ enforce_generic_type_consistency(Oid *actual_arg_types, if (!OidIsValid(array_typeid)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("could not find array type for datatype %s", - format_type_be(elem_typeid)))); + errmsg("could not find array type for datatype %s", + format_type_be(elem_typeid)))); } return array_typeid; } @@ -1026,7 +1042,7 @@ resolve_generic_type(Oid declared_type, if (context_declared_type == ANYARRAYOID) { /* Use actual type, but it must be an array */ - Oid array_typelem = get_element_type(context_actual_type); + Oid array_typelem = get_element_type(context_actual_type); if (!OidIsValid(array_typelem)) ereport(ERROR, @@ -1038,13 +1054,13 @@ resolve_generic_type(Oid declared_type, else if (context_declared_type == ANYELEMENTOID) { /* Use the array type corresponding to actual type */ - Oid array_typeid = get_array_type(context_actual_type); + Oid array_typeid = get_array_type(context_actual_type); if (!OidIsValid(array_typeid)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("could not find array type for datatype %s", - format_type_be(context_actual_type)))); + errmsg("could not find array type for datatype %s", + format_type_be(context_actual_type)))); return array_typeid; } } @@ -1053,7 +1069,7 @@ resolve_generic_type(Oid declared_type, if (context_declared_type == ANYARRAYOID) { /* Use the element type corresponding to actual type */ - Oid array_typelem = get_element_type(context_actual_type); + Oid array_typelem = get_element_type(context_actual_type); if (!OidIsValid(array_typelem)) ereport(ERROR, @@ -1207,8 +1223,8 @@ IsPreferredType(CATEGORY category, Oid type) return false; /* - * This switch should agree with TypeCategory(), above. Note that - * at this point, category certainly matches the type. + * This switch should agree with TypeCategory(), above. Note that at + * this point, category certainly matches the type. */ switch (category) { @@ -1279,8 +1295,8 @@ IsPreferredType(CATEGORY category, Oid type) * Check if srctype is binary-coercible to targettype. * * This notion allows us to cheat and directly exchange values without - * going through the trouble of calling a conversion function. Note that - * in general, this should only be an implementation shortcut. Before 7.4, + * going through the trouble of calling a conversion function. Note that + * in general, this should only be an implementation shortcut. Before 7.4, * this was also used as a heuristic for resolving overloaded functions and * operators, but that's basically a bad idea. * @@ -1293,7 +1309,7 @@ IsPreferredType(CATEGORY category, Oid type) * ANYARRAY type. * * This function replaces IsBinaryCompatible(), which was an inherently - * symmetric test. Since the pg_cast entries aren't necessarily symmetric, + * symmetric test. Since the pg_cast entries aren't necessarily symmetric, * the order of the operands is now significant. */ bool @@ -1415,16 +1431,16 @@ find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, else { /* - * If there's no pg_cast entry, perhaps we are dealing with a - * pair of array types. If so, and if the element types have - * a suitable cast, use array_type_coerce(). + * If there's no pg_cast entry, perhaps we are dealing with a pair + * of array types. If so, and if the element types have a + * suitable cast, use array_type_coerce(). */ Oid targetElemType; Oid sourceElemType; Oid elemfuncid; if ((targetElemType = get_element_type(targetTypeId)) != InvalidOid && - (sourceElemType = get_element_type(sourceTypeId)) != InvalidOid) + (sourceElemType = get_element_type(sourceTypeId)) != InvalidOid) { if (find_coercion_pathway(targetElemType, sourceElemType, ccontext, &elemfuncid)) diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index eb24c1b615..b5aac4f9fd 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_expr.c,v 1.158 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_expr.c,v 1.159 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -41,7 +41,7 @@ static int expr_depth_counter = 0; bool Transform_null_equals = false; static Node *typecast_expression(ParseState *pstate, Node *expr, - TypeName *typename); + TypeName *typename); static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref); static Node *transformIndirection(ParseState *pstate, Node *basenode, List *indirection); @@ -130,10 +130,10 @@ transformExpr(ParseState *pstate, Node *expr) toppstate = toppstate->parentParseState; /* Check parameter number is in range */ - if (paramno <= 0) /* probably can't happen? */ + if (paramno <= 0) /* probably can't happen? */ ereport(ERROR, (errcode(ERRCODE_UNDEFINED_PARAMETER), - errmsg("there is no parameter $%d", paramno))); + errmsg("there is no parameter $%d", paramno))); if (paramno > toppstate->p_numparams) { if (!toppstate->p_variableparams) @@ -152,20 +152,20 @@ transformExpr(ParseState *pstate, Node *expr) /* Zero out the previously-unreferenced slots */ MemSet(toppstate->p_paramtypes + toppstate->p_numparams, 0, - (paramno - toppstate->p_numparams) * sizeof(Oid)); + (paramno - toppstate->p_numparams) * sizeof(Oid)); toppstate->p_numparams = paramno; } if (toppstate->p_variableparams) { /* If not seen before, initialize to UNKNOWN type */ - if (toppstate->p_paramtypes[paramno-1] == InvalidOid) - toppstate->p_paramtypes[paramno-1] = UNKNOWNOID; + if (toppstate->p_paramtypes[paramno - 1] == InvalidOid) + toppstate->p_paramtypes[paramno - 1] = UNKNOWNOID; } param = makeNode(Param); param->paramkind = PARAM_NUM; param->paramid = (AttrNumber) paramno; - param->paramtype = toppstate->p_paramtypes[paramno-1]; + param->paramtype = toppstate->p_paramtypes[paramno - 1]; result = (Node *) param; /* handle qualification, if any */ @@ -254,9 +254,9 @@ transformExpr(ParseState *pstate, Node *expr) else { Node *lexpr = transformExpr(pstate, - a->lexpr); + a->lexpr); Node *rexpr = transformExpr(pstate, - a->rexpr); + a->rexpr); result = (Node *) make_op(pstate, a->name, @@ -276,8 +276,8 @@ transformExpr(ParseState *pstate, Node *expr) rexpr = coerce_to_boolean(pstate, rexpr, "AND"); result = (Node *) makeBoolExpr(AND_EXPR, - makeList2(lexpr, - rexpr)); + makeList2(lexpr, + rexpr)); } break; case AEXPR_OR: @@ -291,8 +291,8 @@ transformExpr(ParseState *pstate, Node *expr) rexpr = coerce_to_boolean(pstate, rexpr, "OR"); result = (Node *) makeBoolExpr(OR_EXPR, - makeList2(lexpr, - rexpr)); + makeList2(lexpr, + rexpr)); } break; case AEXPR_NOT: @@ -303,7 +303,7 @@ transformExpr(ParseState *pstate, Node *expr) rexpr = coerce_to_boolean(pstate, rexpr, "NOT"); result = (Node *) makeBoolExpr(NOT_EXPR, - makeList1(rexpr)); + makeList1(rexpr)); } break; case AEXPR_OP_ANY: @@ -314,7 +314,7 @@ transformExpr(ParseState *pstate, Node *expr) a->rexpr); result = (Node *) make_scalar_array_op(pstate, - a->name, + a->name, true, lexpr, rexpr); @@ -328,7 +328,7 @@ transformExpr(ParseState *pstate, Node *expr) a->rexpr); result = (Node *) make_scalar_array_op(pstate, - a->name, + a->name, false, lexpr, rexpr); @@ -347,10 +347,12 @@ transformExpr(ParseState *pstate, Node *expr) rexpr); if (((OpExpr *) result)->opresulttype != BOOLOID) ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("IS DISTINCT FROM requires = operator to yield boolean"))); + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("IS DISTINCT FROM requires = operator to yield boolean"))); + /* - * We rely on DistinctExpr and OpExpr being same struct + * We rely on DistinctExpr and OpExpr being + * same struct */ NodeSetTag(result, T_DistinctExpr); } @@ -368,10 +370,12 @@ transformExpr(ParseState *pstate, Node *expr) rexpr); if (((OpExpr *) result)->opresulttype != BOOLOID) ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("NULLIF requires = operator to yield boolean"))); + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("NULLIF requires = operator to yield boolean"))); + /* - * We rely on NullIfExpr and OpExpr being same struct + * We rely on NullIfExpr and OpExpr being same + * struct */ NodeSetTag(result, T_NullIfExpr); } @@ -425,8 +429,8 @@ transformExpr(ParseState *pstate, Node *expr) List *args; /* - * Transform the list of arguments. We use a shallow - * list copy and then transform-in-place to avoid O(N^2) + * Transform the list of arguments. We use a shallow list + * copy and then transform-in-place to avoid O(N^2) * behavior from repeated lappend's. */ targs = listCopy(fn->args); @@ -489,7 +493,7 @@ transformExpr(ParseState *pstate, Node *expr) ((TargetEntry *) lfirst(tlist))->resdom->resjunk) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("sub-select must return a column"))); + errmsg("sub-select must return a column"))); while ((tlist = lnext(tlist)) != NIL) { if (!((TargetEntry *) lfirst(tlist))->resdom->resjunk) @@ -499,8 +503,9 @@ transformExpr(ParseState *pstate, Node *expr) } /* - * EXPR and ARRAY need no lefthand or combining operator. - * These fields should be NIL already, but make sure. + * EXPR and ARRAY need no lefthand or combining + * operator. These fields should be NIL already, but + * make sure. */ sublink->lefthand = NIL; sublink->operName = NIL; @@ -523,9 +528,10 @@ transformExpr(ParseState *pstate, Node *expr) lfirst(elist) = transformExpr(pstate, lfirst(elist)); /* - * If the expression is "<> ALL" (with unqualified opname) - * then convert it to "NOT IN". This is a hack to improve - * efficiency of expressions output by pre-7.4 Postgres. + * If the expression is "<> ALL" (with unqualified + * opname) then convert it to "NOT IN". This is a + * hack to improve efficiency of expressions output by + * pre-7.4 Postgres. */ if (sublink->subLinkType == ALL_SUBLINK && length(op) == 1 && strcmp(opname, "<>") == 0) @@ -549,14 +555,14 @@ transformExpr(ParseState *pstate, Node *expr) strcmp(opname, "<>") != 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("row comparison cannot use operator %s", - opname))); + errmsg("row comparison cannot use operator %s", + opname))); /* - * To build the list of combining operator OIDs, we must - * scan subquery's targetlist to find values that will - * be matched against lefthand values. We need to - * ignore resjunk targets, so doing the outer + * To build the list of combining operator OIDs, we + * must scan subquery's targetlist to find values that + * will be matched against lefthand values. We need + * to ignore resjunk targets, so doing the outer * iteration over right_list is easier than doing it * over left_list. */ @@ -576,7 +582,7 @@ transformExpr(ParseState *pstate, Node *expr) if (left_list == NIL) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("sub-select has too many columns"))); + errmsg("sub-select has too many columns"))); lexpr = lfirst(left_list); left_list = lnext(left_list); @@ -596,14 +602,14 @@ transformExpr(ParseState *pstate, Node *expr) (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("operator %s must return boolean, not type %s", opname, - format_type_be(opform->oprresult)), + format_type_be(opform->oprresult)), errhint("The operator of a quantified predicate subquery must return boolean."))); if (get_func_retset(opform->oprcode)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("operator %s must not return a set", - opname), + errmsg("operator %s must not return a set", + opname), errhint("The operator of a quantified predicate subquery must return boolean."))); sublink->operOids = lappendo(sublink->operOids, @@ -614,7 +620,7 @@ transformExpr(ParseState *pstate, Node *expr) if (left_list != NIL) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("sub-select has too few columns"))); + errmsg("sub-select has too few columns"))); if (needNot) { @@ -657,7 +663,7 @@ transformExpr(ParseState *pstate, Node *expr) neww->expr = (Expr *) transformExpr(pstate, warg); neww->expr = (Expr *) coerce_to_boolean(pstate, - (Node *) neww->expr, + (Node *) neww->expr, "CASE/WHEN"); /* @@ -747,8 +753,8 @@ transformExpr(ParseState *pstate, Node *expr) /* Transform the element expressions */ foreach(element, a->elements) { - Node *e = (Node *) lfirst(element); - Node *newe; + Node *e = (Node *) lfirst(element); + Node *newe; newe = transformExpr(pstate, e); newelems = lappend(newelems, newe); @@ -761,8 +767,8 @@ transformExpr(ParseState *pstate, Node *expr) /* Coerce arguments to common type if necessary */ foreach(element, newelems) { - Node *e = (Node *) lfirst(element); - Node *newe; + Node *e = (Node *) lfirst(element); + Node *newe; newe = coerce_to_common_type(pstate, e, element_type, @@ -837,15 +843,15 @@ transformExpr(ParseState *pstate, Node *expr) { CoalesceExpr *c = (CoalesceExpr *) expr; CoalesceExpr *newc = makeNode(CoalesceExpr); - List *newargs = NIL; - List *newcoercedargs = NIL; - List *typeids = NIL; - List *args; + List *newargs = NIL; + List *newcoercedargs = NIL; + List *typeids = NIL; + List *args; foreach(args, c->args) { - Node *e = (Node *) lfirst(args); - Node *newe; + Node *e = (Node *) lfirst(args); + Node *newe; newe = transformExpr(pstate, e); newargs = lappend(newargs, newe); @@ -857,8 +863,8 @@ transformExpr(ParseState *pstate, Node *expr) /* Convert arguments if necessary */ foreach(args, newargs) { - Node *e = (Node *) lfirst(args); - Node *newe; + Node *e = (Node *) lfirst(args); + Node *newe; newe = coerce_to_common_type(pstate, e, newc->coalescetype, @@ -1026,9 +1032,9 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref) * Not known as a column of any range-table entry. * * Consider the possibility that it's VALUE in a domain - * check expression. (We handle VALUE as a name, not a - * keyword, to avoid breaking a lot of applications that - * have used VALUE as a column name in the past.) + * check expression. (We handle VALUE as a name, not + * a keyword, to avoid breaking a lot of applications + * that have used VALUE as a column name in the past.) */ if (pstate->p_value_substitute != NULL && strcmp(name, "value") == 0) @@ -1059,7 +1065,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref) else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" not found", name))); + errmsg("attribute \"%s\" not found", name))); } break; } @@ -1175,8 +1181,8 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref) default: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("improper qualified name (too many dotted names): %s", - NameListToString(cref->fields)))); + errmsg("improper qualified name (too many dotted names): %s", + NameListToString(cref->fields)))); node = NULL; /* keep compiler quiet */ break; } @@ -1246,14 +1252,15 @@ exprType(Node *expr) Assert(!tent->resdom->resjunk); if (sublink->subLinkType == EXPR_SUBLINK) type = tent->resdom->restype; - else /* ARRAY_SUBLINK */ + else +/* ARRAY_SUBLINK */ { type = get_array_type(tent->resdom->restype); if (!OidIsValid(type)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("could not find array type for datatype %s", - format_type_be(tent->resdom->restype)))); + format_type_be(tent->resdom->restype)))); } } else @@ -1266,9 +1273,10 @@ exprType(Node *expr) case T_SubPlan: { /* - * Although the parser does not ever deal with already-planned - * expression trees, we support SubPlan nodes in this routine - * for the convenience of ruleutils.c. + * Although the parser does not ever deal with + * already-planned expression trees, we support SubPlan + * nodes in this routine for the convenience of + * ruleutils.c. */ SubPlan *subplan = (SubPlan *) expr; @@ -1283,14 +1291,15 @@ exprType(Node *expr) Assert(!tent->resdom->resjunk); if (subplan->subLinkType == EXPR_SUBLINK) type = tent->resdom->restype; - else /* ARRAY_SUBLINK */ + else +/* ARRAY_SUBLINK */ { type = get_array_type(tent->resdom->restype); if (!OidIsValid(type)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("could not find array type for datatype %s", - format_type_be(tent->resdom->restype)))); + format_type_be(tent->resdom->restype)))); } } else @@ -1337,9 +1346,10 @@ exprType(Node *expr) type = ((SetToDefault *) expr)->typeId; break; case T_RangeVar: + /* - * If someone uses a bare relation name in an expression, - * we will likely first notice a problem here (see comments in + * If someone uses a bare relation name in an expression, we + * will likely first notice a problem here (see comments in * transformColumnRef()). Issue an appropriate error message. */ ereport(ERROR, @@ -1438,14 +1448,14 @@ exprTypmod(Node *expr) * that typmod, else use -1 */ CoalesceExpr *cexpr = (CoalesceExpr *) expr; - Oid coalescetype = cexpr->coalescetype; - int32 typmod; - List *arg; + Oid coalescetype = cexpr->coalescetype; + int32 typmod; + List *arg; typmod = exprTypmod((Node *) lfirst(cexpr->args)); foreach(arg, cexpr->args) { - Node *e = (Node *) lfirst(arg); + Node *e = (Node *) lfirst(arg); if (exprType(e) != coalescetype) return -1; @@ -1505,9 +1515,9 @@ exprIsLengthCoercion(Node *expr, int32 *coercedTypmod) return false; /* - * If it's not a two-argument or three-argument function with the second - * argument being an int4 constant, it can't have been created from a - * length coercion (it must be a type coercion, instead). + * If it's not a two-argument or three-argument function with the + * second argument being an int4 constant, it can't have been created + * from a length coercion (it must be a type coercion, instead). */ nargs = length(func->args); if (nargs < 2 || nargs > 3) diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c index 4019739450..836f703aae 100644 --- a/src/backend/parser/parse_func.c +++ b/src/backend/parser/parse_func.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_func.c,v 1.157 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_func.c,v 1.158 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -86,8 +86,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, if (nargs > FUNC_MAX_ARGS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_ARGUMENTS), - errmsg("cannot pass more than %d arguments to a function", - FUNC_MAX_ARGS))); + errmsg("cannot pass more than %d arguments to a function", + FUNC_MAX_ARGS))); if (fargs) { @@ -262,9 +262,9 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, if (agg_star) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("%s(*) specified, but %s is not an aggregate function", - NameListToString(funcname), - NameListToString(funcname)))); + errmsg("%s(*) specified, but %s is not an aggregate function", + NameListToString(funcname), + NameListToString(funcname)))); if (agg_distinct) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), @@ -298,8 +298,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" not found in datatype %s", - colname, format_type_be(relTypeId)))); + errmsg("attribute \"%s\" not found in datatype %s", + colname, format_type_be(relTypeId)))); } /* @@ -311,8 +311,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, errmsg("function %s is not unique", func_signature_string(funcname, nargs, actual_arg_types)), - errhint("Could not choose a best candidate function. " - "You may need to add explicit typecasts."))); + errhint("Could not choose a best candidate function. " + "You may need to add explicit typecasts."))); else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), @@ -392,7 +392,7 @@ int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, - FuncCandidateList *candidates) /* return value */ + FuncCandidateList *candidates) /* return value */ { FuncCandidateList current_candidate; FuncCandidateList next_candidate; @@ -495,12 +495,13 @@ func_select_candidate(int nargs, /* * If any input types are domains, reduce them to their base types. * This ensures that we will consider functions on the base type to be - * "exact matches" in the exact-match heuristic; it also makes it possible - * to do something useful with the type-category heuristics. Note that - * this makes it difficult, but not impossible, to use functions declared - * to take a domain as an input datatype. Such a function will be - * selected over the base-type function only if it is an exact match at - * all argument positions, and so was already chosen by our caller. + * "exact matches" in the exact-match heuristic; it also makes it + * possible to do something useful with the type-category heuristics. + * Note that this makes it difficult, but not impossible, to use + * functions declared to take a domain as an input datatype. Such a + * function will be selected over the base-type function only if it is + * an exact match at all argument positions, and so was already chosen + * by our caller. */ for (i = 0; i < nargs; i++) input_base_typeids[i] = getBaseType(input_typeids[i]); @@ -550,13 +551,14 @@ func_select_candidate(int nargs, return candidates; /* - * Still too many candidates? Now look for candidates which have either - * exact matches or preferred types at the args that will require coercion. - * (Restriction added in 7.4: preferred type must be of same category as - * input type; give no preference to cross-category conversions to - * preferred types.) Keep all candidates if none match. + * Still too many candidates? Now look for candidates which have + * either exact matches or preferred types at the args that will + * require coercion. (Restriction added in 7.4: preferred type must be + * of same category as input type; give no preference to + * cross-category conversions to preferred types.) Keep all + * candidates if none match. */ - for (i = 0; i < nargs; i++) /* avoid multiple lookups */ + for (i = 0; i < nargs; i++) /* avoid multiple lookups */ slot_category[i] = TypeCategory(input_base_typeids[i]); ncandidates = 0; nbestMatch = 0; @@ -602,10 +604,11 @@ func_select_candidate(int nargs, * Still too many candidates? Try assigning types for the unknown * columns. * - * NOTE: for a binary operator with one unknown and one non-unknown input, - * we already tried the heuristic of looking for a candidate with the - * known input type on both sides (see binary_oper_exact()). That's - * essentially a special case of the general algorithm we try next. + * NOTE: for a binary operator with one unknown and one non-unknown + * input, we already tried the heuristic of looking for a candidate + * with the known input type on both sides (see binary_oper_exact()). + * That's essentially a special case of the general algorithm we try + * next. * * We do this by examining each unknown argument position to see if we * can determine a "type category" for it. If any candidate has an @@ -815,9 +818,10 @@ func_get_detail(List *funcname, * constant to a specific type. * * The reason we can restrict our check to binary-compatible - * coercions here is that we expect non-binary-compatible coercions - * to have an implementation function named after the target type. - * That function will be found by normal lookup if appropriate. + * coercions here is that we expect non-binary-compatible + * coercions to have an implementation function named after the + * target type. That function will be found by normal lookup if + * appropriate. * * NB: it's important that this code stays in sync with what * coerce_type can do, because the caller will try to apply @@ -895,7 +899,7 @@ func_get_detail(List *funcname, { best_candidate = func_select_candidate(nargs, current_input_typeids, - current_candidates); + current_candidates); /* * If we were able to choose a best candidate, we're @@ -960,7 +964,7 @@ func_get_detail(List *funcname, * finding all superclasses of that type. A vector of new Oid type * arrays is returned to the caller, listing possible alternative * interpretations of the input typeids as members of their superclasses - * rather than the actually given argument types. The vector is + * rather than the actually given argument types. The vector is * terminated by a NULL pointer. * * The order of this vector is as follows: all superclasses of the @@ -1123,14 +1127,14 @@ gen_cross_product(InhPaths *arginh, int nargs) /* * We also need an extra slot for the terminating NULL in the result * array, but that cancels out with the fact that we don't want to - * generate the zero-changes case. So we need exactly nanswers slots. + * generate the zero-changes case. So we need exactly nanswers slots. */ result = (Oid **) palloc(sizeof(Oid *) * nanswers); j = 0; /* * Compute the cross product from right to left. When cur[i] == 0, - * generate the original input type at position i. When cur[i] == k + * generate the original input type at position i. When cur[i] == k * for k > 0, generate its k'th supertype. */ MemSet(cur, 0, sizeof(cur)); @@ -1138,7 +1142,7 @@ gen_cross_product(InhPaths *arginh, int nargs) for (;;) { /* - * Find a column we can increment. All the columns after it get + * Find a column we can increment. All the columns after it get * reset to zero. (Essentially, we're adding one to the multi- * digit number represented by cur[].) */ @@ -1263,8 +1267,8 @@ setup_field_select(Node *input, char *attname, Oid relid) if (attno == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - attname, get_rel_name(relid)))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + attname, get_rel_name(relid)))); fselect->arg = (Expr *) input; fselect->fieldnum = attno; @@ -1448,7 +1452,7 @@ find_aggregate_func(List *aggname, Oid basetype, bool noError) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("function %s(%s) is not an aggregate", - NameListToString(aggname), format_type_be(basetype)))); + NameListToString(aggname), format_type_be(basetype)))); } ReleaseSysCache(ftup); @@ -1485,7 +1489,7 @@ LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("function %s does not exist", - func_signature_string(funcname, nargs, argtypes)))); + func_signature_string(funcname, nargs, argtypes)))); return InvalidOid; } diff --git a/src/backend/parser/parse_node.c b/src/backend/parser/parse_node.c index 5e047400a1..74162a9f80 100644 --- a/src/backend/parser/parse_node.c +++ b/src/backend/parser/parse_node.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_node.c,v 1.79 2003/07/19 20:20:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_node.c,v 1.80 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -121,8 +121,8 @@ transformArraySubscripts(ParseState *pstate, if (elementType == InvalidOid) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("cannot subscript type %s because it is not an array", - format_type_be(arrayType)))); + errmsg("cannot subscript type %s because it is not an array", + format_type_be(arrayType)))); /* * A list containing only single subscripts refers to a single array @@ -173,14 +173,14 @@ transformArraySubscripts(ParseState *pstate, subexpr = transformExpr(pstate, ai->lidx); /* If it's not int4 already, try to coerce */ subexpr = coerce_to_target_type(pstate, - subexpr, exprType(subexpr), + subexpr, exprType(subexpr), INT4OID, -1, COERCION_ASSIGNMENT, COERCE_IMPLICIT_CAST); if (subexpr == NULL) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("array subscript must have type integer"))); + errmsg("array subscript must have type integer"))); } else { diff --git a/src/backend/parser/parse_oper.c b/src/backend/parser/parse_oper.c index 68225aae0a..c3307a7658 100644 --- a/src/backend/parser/parse_oper.c +++ b/src/backend/parser/parse_oper.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_oper.c,v 1.71 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_oper.c,v 1.72 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -31,13 +31,13 @@ static Oid binary_oper_exact(Oid arg1, Oid arg2, FuncCandidateList candidates); static FuncDetailCode oper_select_candidate(int nargs, - Oid *input_typeids, - FuncCandidateList candidates, - Oid *operOid); + Oid *input_typeids, + FuncCandidateList candidates, + Oid *operOid); static const char *op_signature_string(List *op, char oprkind, - Oid arg1, Oid arg2); + Oid arg1, Oid arg2); static void op_error(List *op, char oprkind, Oid arg1, Oid arg2, - FuncDetailCode fdresult); + FuncDetailCode fdresult); /* @@ -140,9 +140,9 @@ equality_oper(Oid argtype, bool noError) /* * If the datatype is an array, then we can use array_eq ... but only - * if there is a suitable equality operator for the element type. - * (We must run this test first, since compatible_oper will find - * array_eq, but would not notice the lack of an element operator.) + * if there is a suitable equality operator for the element type. (We + * must run this test first, since compatible_oper will find array_eq, + * but would not notice the lack of an element operator.) */ elem_type = get_element_type(argtype); if (OidIsValid(elem_type)) @@ -184,8 +184,8 @@ equality_oper(Oid argtype, bool noError) if (!noError) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("could not identify an equality operator for type %s", - format_type_be(argtype)))); + errmsg("could not identify an equality operator for type %s", + format_type_be(argtype)))); return NULL; } @@ -202,10 +202,10 @@ ordering_oper(Oid argtype, bool noError) /* * If the datatype is an array, then we can use array_lt ... but only - * if there is a suitable ordering operator for the element type. - * (We must run this test first, since the code below would find - * array_lt if there's an element = operator, but would not notice the - * lack of an element < operator.) + * if there is a suitable ordering operator for the element type. (We + * must run this test first, since the code below would find array_lt + * if there's an element = operator, but would not notice the lack of + * an element < operator.) */ elem_type = get_element_type(argtype); if (OidIsValid(elem_type)) @@ -222,15 +222,15 @@ ordering_oper(Oid argtype, bool noError) else { /* - * Find the type's equality operator, and use its lsortop (it *must* - * be mergejoinable). We use this definition because for sorting and - * grouping purposes, it's important that the equality and ordering - * operators are consistent. + * Find the type's equality operator, and use its lsortop (it + * *must* be mergejoinable). We use this definition because for + * sorting and grouping purposes, it's important that the equality + * and ordering operators are consistent. */ optup = equality_oper(argtype, noError); if (optup != NULL) { - Oid lsortop; + Oid lsortop; lsortop = ((Form_pg_operator) GETSTRUCT(optup))->oprlsortop; ReleaseSysCache(optup); @@ -247,8 +247,8 @@ ordering_oper(Oid argtype, bool noError) if (!noError) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("could not identify an ordering operator for type %s", - format_type_be(argtype)), + errmsg("could not identify an ordering operator for type %s", + format_type_be(argtype)), errhint("Use an explicit ordering operator or modify the query."))); return NULL; } @@ -361,13 +361,13 @@ static FuncDetailCode oper_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates, - Oid *operOid) /* output argument */ + Oid *operOid) /* output argument */ { int ncandidates; /* - * Delete any candidates that cannot actually accept the given - * input types, whether directly or by coercion. + * Delete any candidates that cannot actually accept the given input + * types, whether directly or by coercion. */ ncandidates = func_match_argtypes(nargs, input_typeids, candidates, &candidates); @@ -385,8 +385,8 @@ oper_select_candidate(int nargs, } /* - * Use the same heuristics as for ambiguous functions to resolve - * the conflict. + * Use the same heuristics as for ambiguous functions to resolve the + * conflict. */ candidates = func_select_candidate(nargs, input_typeids, candidates); @@ -397,7 +397,7 @@ oper_select_candidate(int nargs, } *operOid = InvalidOid; - return FUNCDETAIL_MULTIPLE; /* failed to select a best candidate */ + return FUNCDETAIL_MULTIPLE; /* failed to select a best candidate */ } @@ -772,6 +772,7 @@ make_scalar_array_op(ParseState *pstate, List *opname, ltypeId = exprType(ltree); atypeId = exprType(rtree); + /* * The right-hand input of the operator will be the element type of * the array. However, if we currently have just an untyped literal @@ -785,7 +786,7 @@ make_scalar_array_op(ParseState *pstate, List *opname, if (!OidIsValid(rtypeId)) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("op ANY/ALL (array) requires array on right side"))); + errmsg("op ANY/ALL (array) requires array on right side"))); } /* Now resolve the operator */ @@ -814,15 +815,15 @@ make_scalar_array_op(ParseState *pstate, List *opname, if (rettype != BOOLOID) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), - errmsg("op ANY/ALL (array) requires operator to yield boolean"))); + errmsg("op ANY/ALL (array) requires operator to yield boolean"))); if (get_func_retset(opform->oprcode)) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("op ANY/ALL (array) requires operator not to return a set"))); /* - * Now switch back to the array type on the right, arranging for - * any needed cast to be applied. + * Now switch back to the array type on the right, arranging for any + * needed cast to be applied. */ res_atypeId = get_array_type(declared_arg_types[1]); if (!OidIsValid(res_atypeId)) diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 732699e3ad..ee368a2360 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_relation.c,v 1.85 2003/07/20 21:56:35 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_relation.c,v 1.86 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -33,7 +33,7 @@ #include "utils/syscache.h" /* GUC parameter */ -bool add_missing_from; +bool add_missing_from; static Node *scanNameSpaceForRefname(ParseState *pstate, Node *nsnode, const char *refname); @@ -365,8 +365,8 @@ scanNameSpaceForConflict(ParseState *pstate, Node *nsnode, if (strcmp(j->alias->aliasname, aliasname1) == 0) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_ALIAS), - errmsg("table name \"%s\" specified more than once", - aliasname1))); + errmsg("table name \"%s\" specified more than once", + aliasname1))); /* * Tables within an aliased join are invisible from outside @@ -570,8 +570,8 @@ colnameToVar(ParseState *pstate, char *colname) if (result) ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_COLUMN), - errmsg("column reference \"%s\" is ambiguous", - colname))); + errmsg("column reference \"%s\" is ambiguous", + colname))); result = newresult; } } @@ -666,7 +666,7 @@ addRangeTableEntry(ParseState *pstate, ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), errmsg("table \"%s\" has %d columns available but %d columns specified", - RelationGetRelationName(rel), maxattrs, numaliases))); + RelationGetRelationName(rel), maxattrs, numaliases))); /* fill in any unspecified alias columns using actual column names */ for (varattno = numaliases; varattno < maxattrs; varattno++) @@ -761,7 +761,7 @@ addRangeTableEntryForRelation(ParseState *pstate, ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), errmsg("table \"%s\" has %d columns available but %d columns specified", - RelationGetRelationName(rel), maxattrs, numaliases))); + RelationGetRelationName(rel), maxattrs, numaliases))); /* fill in any unspecified alias columns using actual column names */ for (varattno = numaliases; varattno < maxattrs; varattno++) @@ -957,7 +957,8 @@ addRangeTableEntryForFunction(ParseState *pstate, Relation rel; int maxattrs; - if (!OidIsValid(funcrelid)) /* shouldn't happen if typtype is 'c' */ + if (!OidIsValid(funcrelid)) /* shouldn't happen if typtype is + * 'c' */ elog(ERROR, "invalid typrelid for complex type %u", funcrettype); /* @@ -1003,8 +1004,8 @@ addRangeTableEntryForFunction(ParseState *pstate, if (numaliases > 1) ereport(ERROR, (errcode(ERRCODE_INVALID_COLUMN_REFERENCE), - errmsg("too many column aliases specified for function %s", - funcname))); + errmsg("too many column aliases specified for function %s", + funcname))); if (numaliases == 0) eref->colnames = makeList1(makeString(eref->aliasname)); } @@ -1026,8 +1027,8 @@ addRangeTableEntryForFunction(ParseState *pstate, else ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("function \"%s\" in FROM has unsupported return type", - funcname))); + errmsg("function \"%s\" in FROM has unsupported return type", + funcname))); /*---------- * Flags: @@ -1318,7 +1319,7 @@ expandRTE(ParseState *pstate, RangeTblEntry *rte, int maxattrs; int numaliases; - if (!OidIsValid(funcrelid)) /* shouldn't happen */ + if (!OidIsValid(funcrelid)) /* shouldn't happen */ elog(ERROR, "invalid typrelid for complex type %u", funcrettype); @@ -1575,7 +1576,7 @@ get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum, ObjectIdGetDatum(rte->relid), Int16GetDatum(attnum), 0, 0); - if (!HeapTupleIsValid(tp)) /* shouldn't happen */ + if (!HeapTupleIsValid(tp)) /* shouldn't happen */ elog(ERROR, "cache lookup failed for attribute %d of relation %u", attnum, rte->relid); att_tup = (Form_pg_attribute) GETSTRUCT(tp); @@ -1632,7 +1633,7 @@ get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum, HeapTuple tp; Form_pg_attribute att_tup; - if (!OidIsValid(funcrelid)) /* shouldn't happen */ + if (!OidIsValid(funcrelid)) /* shouldn't happen */ elog(ERROR, "invalid typrelid for complex type %u", funcrettype); @@ -1640,7 +1641,7 @@ get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum, ObjectIdGetDatum(funcrelid), Int16GetDatum(attnum), 0, 0); - if (!HeapTupleIsValid(tp)) /* shouldn't happen */ + if (!HeapTupleIsValid(tp)) /* shouldn't happen */ elog(ERROR, "cache lookup failed for attribute %d of relation %u", attnum, funcrelid); att_tup = (Form_pg_attribute) GETSTRUCT(tp); @@ -1720,7 +1721,7 @@ get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum) ObjectIdGetDatum(rte->relid), Int16GetDatum(attnum), 0, 0); - if (!HeapTupleIsValid(tp)) /* shouldn't happen */ + if (!HeapTupleIsValid(tp)) /* shouldn't happen */ elog(ERROR, "cache lookup failed for attribute %d of relation %u", attnum, rte->relid); att_tup = (Form_pg_attribute) GETSTRUCT(tp); @@ -1752,7 +1753,7 @@ get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum) ObjectIdGetDatum(funcrelid), Int16GetDatum(attnum), 0, 0); - if (!HeapTupleIsValid(tp)) /* shouldn't happen */ + if (!HeapTupleIsValid(tp)) /* shouldn't happen */ elog(ERROR, "cache lookup failed for attribute %d of relation %u", attnum, funcrelid); att_tup = (Form_pg_attribute) GETSTRUCT(tp); @@ -1927,7 +1928,7 @@ warnAutoRange(ParseState *pstate, RangeVar *relation) else ereport(NOTICE, (errcode(ERRCODE_UNDEFINED_TABLE), - errmsg("adding missing FROM-clause entry for table \"%s\"", - relation->relname))); + errmsg("adding missing FROM-clause entry for table \"%s\"", + relation->relname))); } } diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c index daeb56b110..6e10d52723 100644 --- a/src/backend/parser/parse_target.c +++ b/src/backend/parser/parse_target.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_target.c,v 1.108 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_target.c,v 1.109 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -66,7 +66,7 @@ transformTargetEntry(ParseState *pstate, errmsg("relation reference \"%s\" cannot be used as a targetlist entry", ((RangeVar *) expr)->relname), errhint("Write \"%s\".* to denote all the columns of the relation.", - ((RangeVar *) expr)->relname))); + ((RangeVar *) expr)->relname))); type_id = exprType(expr); type_mod = exprTypmod(expr); @@ -152,8 +152,8 @@ transformTargetList(ParseState *pstate, List *targetlist) */ if (strcmp(name1, get_database_name(MyDatabaseId)) != 0) ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cross-database references are not implemented"))); + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cross-database references are not implemented"))); schemaname = strVal(lsecond(fields)); relname = strVal(lthird(fields)); break; @@ -286,7 +286,7 @@ markTargetListOrigin(ParseState *pstate, Resdom *res, Var *var) case RTE_JOIN: { /* Join RTE --- recursively inspect the alias variable */ - Var *aliasvar; + Var *aliasvar; Assert(attnum > 0 && attnum <= length(rte->joinaliasvars)); aliasvar = (Var *) nth(attnum - 1, rte->joinaliasvars); @@ -322,7 +322,7 @@ updateTargetListEntry(ParseState *pstate, int attrno, List *indirection) { - Oid type_id; /* type of value provided */ + Oid type_id; /* type of value provided */ Oid attrtype; /* type of target column */ int32 attrtypmod; Resdom *resnode = tle->resdom; @@ -341,13 +341,13 @@ updateTargetListEntry(ParseState *pstate, * If the expression is a DEFAULT placeholder, insert the attribute's * type/typmod into it so that exprType will report the right things. * (We expect that the eventually substituted default expression will - * in fact have this type and typmod.) Also, reject trying to update + * in fact have this type and typmod.) Also, reject trying to update * an array element with DEFAULT, since there can't be any default for * individual elements of a column. */ if (tle->expr && IsA(tle->expr, SetToDefault)) { - SetToDefault *def = (SetToDefault *) tle->expr; + SetToDefault *def = (SetToDefault *) tle->expr; def->typeId = attrtype; def->typeMod = attrtypmod; @@ -496,8 +496,8 @@ checkInsertTargets(ParseState *pstate, List *cols, List **attrnos) if (intMember(attrno, *attrnos)) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), - errmsg("attribute \"%s\" specified more than once", - name))); + errmsg("attribute \"%s\" specified more than once", + name))); *attrnos = lappendi(*attrnos, attrno); } } @@ -551,7 +551,7 @@ ExpandAllTables(ParseState *pstate) if (!found_table) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("SELECT * with no tables specified is not valid"))); + errmsg("SELECT * with no tables specified is not valid"))); return target; } diff --git a/src/backend/parser/parse_type.c b/src/backend/parser/parse_type.c index 5d68ef14a5..d744823b3b 100644 --- a/src/backend/parser/parse_type.c +++ b/src/backend/parser/parse_type.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parse_type.c,v 1.59 2003/07/20 21:56:35 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_type.c,v 1.60 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -91,8 +91,8 @@ LookupTypeName(const TypeName *typename) if (attnum == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), - errmsg("attribute \"%s\" of relation \"%s\" does not exist", - field, rel->relname))); + errmsg("attribute \"%s\" of relation \"%s\" does not exist", + field, rel->relname))); restype = get_atttype(relid, attnum); /* this construct should never have an array indicator */ @@ -229,7 +229,7 @@ typenameType(const TypeName *typename) tup = SearchSysCache(TYPEOID, ObjectIdGetDatum(typoid), 0, 0, 0); - if (!HeapTupleIsValid(tup)) /* should not happen */ + if (!HeapTupleIsValid(tup)) /* should not happen */ elog(ERROR, "cache lookup failed for type %u", typoid); if (!((Form_pg_type) GETSTRUCT(tup))->typisdefined) ereport(ERROR, diff --git a/src/backend/port/beos/sem.c b/src/backend/port/beos/sem.c index 06518e7db7..5de018b22b 100644 --- a/src/backend/port/beos/sem.c +++ b/src/backend/port/beos/sem.c @@ -291,8 +291,8 @@ semop(int semId, struct sembuf * sops, int nsops) if (sops[i].sem_op < 0) { /* - * Try acquiring the semaphore till we are not interrupted by a - * signal + * Try acquiring the semaphore till we are not interrupted by + * a signal */ if (sops[i].sem_flg == IPC_NOWAIT) { diff --git a/src/backend/port/dynloader/darwin.c b/src/backend/port/dynloader/darwin.c index 8810308a14..b297405b85 100644 --- a/src/backend/port/dynloader/darwin.c +++ b/src/backend/port/dynloader/darwin.c @@ -3,7 +3,7 @@ * available with a PostgreSQL-compatible license. Kudos Wilfredo * Sánchez . * - * $Header: /cvsroot/pgsql/src/backend/port/dynloader/darwin.c,v 1.7 2003/04/13 01:19:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/dynloader/darwin.c,v 1.8 2003/08/04 00:43:21 momjian Exp $ */ #include "postgres.h" @@ -58,7 +58,7 @@ char * pg_dlerror(void) { NSLinkEditErrors c; - int errorNumber; + int errorNumber; const char *fileName; const char *errorString = NULL; diff --git a/src/backend/port/dynloader/linux.c b/src/backend/port/dynloader/linux.c index f82cfadf6a..faf06d9bc4 100644 --- a/src/backend/port/dynloader/linux.c +++ b/src/backend/port/dynloader/linux.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/dynloader/linux.c,v 1.24 2003/07/22 23:30:39 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/dynloader/linux.c,v 1.25 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -131,4 +131,4 @@ pg_dlerror(void) #endif } -#endif /* !HAVE_DLOPEN */ +#endif /* !HAVE_DLOPEN */ diff --git a/src/backend/port/dynloader/linux.h b/src/backend/port/dynloader/linux.h index 0adbdf8edf..fdc65a069f 100644 --- a/src/backend/port/dynloader/linux.h +++ b/src/backend/port/dynloader/linux.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: linux.h,v 1.19 2002/10/15 16:04:17 tgl Exp $ + * $Id: linux.h,v 1.20 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -39,7 +39,6 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* HAVE_DLOPEN */ #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/win32.c b/src/backend/port/dynloader/win32.c index e124ee4120..83194aa775 100644 --- a/src/backend/port/dynloader/win32.c +++ b/src/backend/port/dynloader/win32.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/backend/port/dynloader/win32.c,v 1.1 2003/05/15 16:35:29 momjian Exp $ */ +/* $Header: /cvsroot/pgsql/src/backend/port/dynloader/win32.c,v 1.2 2003/08/04 00:43:21 momjian Exp $ */ #include @@ -11,17 +11,17 @@ dlerror(void) int dlclose(void *handle) { - return FreeLibrary((HMODULE)handle) ? 0 : 1; + return FreeLibrary((HMODULE) handle) ? 0 : 1; } void * dlsym(void *handle, const char *symbol) { - return (void *)GetProcAddress((HMODULE)handle, symbol); + return (void *) GetProcAddress((HMODULE) handle, symbol); } void * dlopen(const char *path, int mode) { - return (void *)LoadLibrary(path); + return (void *) LoadLibrary(path); } diff --git a/src/backend/port/ipc_test.c b/src/backend/port/ipc_test.c index 6d10d3bb8f..4ae64d788e 100644 --- a/src/backend/port/ipc_test.c +++ b/src/backend/port/ipc_test.c @@ -21,7 +21,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/ipc_test.c,v 1.7 2003/07/27 21:49:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/ipc_test.c,v 1.8 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -140,13 +140,13 @@ errstart(int elevel, const char *filename, int lineno, } void -errfinish(int dummy, ...) +errfinish(int dummy,...) { proc_exit(1); } void -elog_finish(int elevel, const char *fmt, ...) +elog_finish(int elevel, const char *fmt,...) { fprintf(stderr, "ERROR: %s\n", fmt); proc_exit(1); @@ -159,28 +159,28 @@ errcode(int sqlerrcode) } int -errmsg(const char *fmt, ...) +errmsg(const char *fmt,...) { fprintf(stderr, "ERROR: %s\n", fmt); return 0; /* return value does not matter */ } int -errmsg_internal(const char *fmt, ...) +errmsg_internal(const char *fmt,...) { fprintf(stderr, "ERROR: %s\n", fmt); return 0; /* return value does not matter */ } int -errdetail(const char *fmt, ...) +errdetail(const char *fmt,...) { fprintf(stderr, "DETAIL: %s\n", fmt); return 0; /* return value does not matter */ } int -errhint(const char *fmt, ...) +errhint(const char *fmt,...) { fprintf(stderr, "HINT: %s\n", fmt); return 0; /* return value does not matter */ diff --git a/src/backend/port/posix_sema.c b/src/backend/port/posix_sema.c index ae73eff024..3434618d93 100644 --- a/src/backend/port/posix_sema.c +++ b/src/backend/port/posix_sema.c @@ -11,7 +11,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/posix_sema.c,v 1.8 2003/07/27 21:49:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/posix_sema.c,v 1.9 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -114,7 +114,6 @@ PosixSemaphoreCreate(sem_t * sem) if (sem_init(sem, 1, 1) < 0) elog(FATAL, "sem_init failed: %m"); } - #endif /* USE_NAMED_POSIX_SEMAPHORES */ diff --git a/src/backend/port/sysv_sema.c b/src/backend/port/sysv_sema.c index 23131f8a67..2ec342df85 100644 --- a/src/backend/port/sysv_sema.c +++ b/src/backend/port/sysv_sema.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/sysv_sema.c,v 1.7 2003/07/27 21:49:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/sysv_sema.c,v 1.8 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -121,12 +121,12 @@ InternalIpcSemaphoreCreate(IpcSemaphoreKey semKey, int numSems) (errno == ENOSPC) ? errhint("This error does *not* mean that you have run out of disk space.\n" "It occurs when either the system limit for the maximum number of " - "semaphore sets (SEMMNI), or the system wide maximum number of " - "semaphores (SEMMNS), would be exceeded. You need to raise the " + "semaphore sets (SEMMNI), or the system wide maximum number of " + "semaphores (SEMMNS), would be exceeded. You need to raise the " "respective kernel parameter. Alternatively, reduce PostgreSQL's " "consumption of semaphores by reducing its max_connections parameter " "(currently %d).\n" - "The PostgreSQL documentation contains more information about " + "The PostgreSQL documentation contains more information about " "configuring your system for PostgreSQL.", MaxBackends) : 0)); } @@ -149,7 +149,7 @@ IpcSemaphoreInitialize(IpcSemaphoreId semId, int semNum, int value) semId, semNum, value), (errno == ERANGE) ? errhint("You possibly need to raise your kernel's SEMVMX value to be at least " - "%d. Look into the PostgreSQL documentation for details.", + "%d. Look into the PostgreSQL documentation for details.", value) : 0)); } diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c index 3f31f21d8e..b7829d7c8c 100644 --- a/src/backend/port/sysv_shmem.c +++ b/src/backend/port/sysv_shmem.c @@ -10,7 +10,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/sysv_shmem.c,v 1.13 2003/07/27 21:49:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/sysv_shmem.c,v 1.14 2003/08/04 00:43:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -40,13 +40,13 @@ typedef int IpcMemoryId; /* shared memory ID returned by shmget(2) */ IpcMemoryKey UsedShmemSegID = 0; -void *UsedShmemSegAddr = NULL; +void *UsedShmemSegAddr = NULL; static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, uint32 size); static void IpcMemoryDetach(int status, Datum shmaddr); static void IpcMemoryDelete(int status, Datum shmId); static PGShmemHeader *PGSharedMemoryAttach(IpcMemoryKey key, - IpcMemoryId *shmid); + IpcMemoryId *shmid); /* @@ -90,15 +90,15 @@ InternalIpcMemoryCreate(IpcMemoryKey memKey, uint32 size) */ ereport(FATAL, (errmsg("could not create shared memory segment: %m"), - errdetail("Failed syscall was shmget(key=%d, size=%u, 0%o).", - (int) memKey, size, - IPC_CREAT | IPC_EXCL | IPCProtection), + errdetail("Failed syscall was shmget(key=%d, size=%u, 0%o).", + (int) memKey, size, + IPC_CREAT | IPC_EXCL | IPCProtection), (errno == EINVAL) ? errhint("This error usually means that PostgreSQL's request for a shared memory " "segment exceeded your kernel's SHMMAX parameter. You can either " "reduce the request size or reconfigure the kernel with larger SHMMAX. " - "To reduce the request size (currently %u bytes), reduce " - "PostgreSQL's shared_buffers parameter (currently %d) and/or " + "To reduce the request size (currently %u bytes), reduce " + "PostgreSQL's shared_buffers parameter (currently %d) and/or " "its max_connections parameter (currently %d).\n" "If the request size is already small, it's possible that it is less than " "your kernel's SHMMIN parameter, in which case raising the request size or " @@ -108,9 +108,9 @@ InternalIpcMemoryCreate(IpcMemoryKey memKey, uint32 size) size, NBuffers, MaxBackends) : 0, (errno == ENOMEM) ? errhint("This error usually means that PostgreSQL's request for a shared " - "memory segment exceeded available memory or swap space. " - "To reduce the request size (currently %u bytes), reduce " - "PostgreSQL's shared_buffers parameter (currently %d) and/or " + "memory segment exceeded available memory or swap space. " + "To reduce the request size (currently %u bytes), reduce " + "PostgreSQL's shared_buffers parameter (currently %d) and/or " "its max_connections parameter (currently %d).\n" "The PostgreSQL documentation contains more information about shared " "memory configuration.", @@ -120,9 +120,9 @@ InternalIpcMemoryCreate(IpcMemoryKey memKey, uint32 size) "It occurs either if all available shared memory IDs have been taken, " "in which case you need to raise the SHMMNI parameter in your kernel, " "or because the system's overall limit for shared memory has been " - "reached. If you cannot increase the shared memory limit, " - "reduce PostgreSQL's shared memory request (currently %u bytes), " - "by reducing its shared_buffers parameter (currently %d) and/or " + "reached. If you cannot increase the shared memory limit, " + "reduce PostgreSQL's shared memory request (currently %u bytes), " + "by reducing its shared_buffers parameter (currently %d) and/or " "its max_connections parameter (currently %d).\n" "The PostgreSQL documentation contains more information about shared " "memory configuration.", @@ -326,13 +326,13 @@ PGSharedMemoryCreate(uint32 size, bool makePrivate, int port) hdr->totalsize = size; hdr->freeoffset = MAXALIGN(sizeof(PGShmemHeader)); - + if (ExecBackend && UsedShmemSegAddr == NULL && !makePrivate) { UsedShmemSegAddr = memAddress; UsedShmemSegID = NextShmemSegID; } - + return hdr; } @@ -353,7 +353,7 @@ PGSharedMemoryAttach(IpcMemoryKey key, IpcMemoryId *shmid) hdr = (PGShmemHeader *) shmat(*shmid, UsedShmemSegAddr, #if defined(solaris) && defined(__sparc__) - /* use intimate shared memory on Solaris */ + /* use intimate shared memory on Solaris */ SHM_SHARE_MMU #else 0 diff --git a/src/backend/port/win32/sema.c b/src/backend/port/win32/sema.c index 267b461920..7bdd2e0977 100644 --- a/src/backend/port/win32/sema.c +++ b/src/backend/port/win32/sema.c @@ -17,9 +17,9 @@ typedef struct { int m_numSems; off_t m_semaphoreHandles; - //offset from beginning of header + /* offset from beginning of header */ off_t m_semaphoreCounts; - //offset from beginning of header + /* offset from beginning of header */ } win32_sem_set_hdr; /* Control of a semaphore pool. The pool is an area in which we stored all @@ -131,7 +131,7 @@ semget(int semKey, int semNum, int flags) HANDLE *sem_handles = NULL; int *sem_counts = NULL; int i; - + sec_attrs.nLength = sizeof(sec_attrs); sec_attrs.lpSecurityDescriptor = NULL; sec_attrs.bInheritHandle = TRUE; @@ -152,8 +152,8 @@ semget(int semKey, int semNum, int flags) new_set->m_numSems = semNum; new_set->m_semaphoreHandles = sizeof(win32_sem_set_hdr); - //array starts after header - new_set->m_semaphoreCounts = new_set->m_semaphoreHandles + (sizeof(HANDLE) * semNum); + /* array starts after header */ + new_set->m_semaphoreCounts = new_set->m_semaphoreHandles + (sizeof(HANDLE) * semNum); sem_handles = (HANDLE *) ((off_t) new_set + new_set->m_semaphoreHandles); sem_counts = (int *) ((off_t) new_set + new_set->m_semaphoreCounts); @@ -186,7 +186,8 @@ semget(int semKey, int semNum, int flags) return MAKE_OFFSET(new_set); else { - int i; + int i; + /* Blow away what we've got right now... */ for (i = 0; i < semNum; ++i) { diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c index 4c8dbe5e16..5e603a00b1 100644 --- a/src/backend/postmaster/pgstat.c +++ b/src/backend/postmaster/pgstat.c @@ -13,7 +13,7 @@ * * Copyright (c) 2001-2003, PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/backend/postmaster/pgstat.c,v 1.41 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/postmaster/pgstat.c,v 1.42 2003/08/04 00:43:21 momjian Exp $ * ---------- */ #include "postgres.h" @@ -85,6 +85,7 @@ static bool pgStatRunningInCollector = FALSE; static int pgStatTabstatAlloc = 0; static int pgStatTabstatUsed = 0; static PgStat_MsgTabstat **pgStatTabstatMessages = NULL; + #define TABSTAT_QUANTUM 4 /* we alloc this many at a time */ static int pgStatXactCommit = 0; @@ -146,8 +147,10 @@ static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len); void pgstat_init(void) { - ACCEPT_TYPE_ARG3 alen; - struct addrinfo *addrs = NULL, *addr, hints; + ACCEPT_TYPE_ARG3 alen; + struct addrinfo *addrs = NULL, + *addr, + hints; int ret; /* @@ -197,7 +200,7 @@ pgstat_init(void) gai_strerror(ret)))); goto startup_failed; } - + for (addr = addrs; addr; addr = addr->ai_next) { #ifdef HAVE_UNIX_SOCKETS @@ -233,11 +236,11 @@ pgstat_init(void) addrs = NULL; alen = sizeof(pgStatAddr); - if (getsockname(pgStatSock, (struct sockaddr *)&pgStatAddr, &alen) < 0) + if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0) { ereport(LOG, (errcode_for_socket_access(), - errmsg("could not get address of socket for statistics: %m"))); + errmsg("could not get address of socket for statistics: %m"))); goto startup_failed; } @@ -265,7 +268,7 @@ pgstat_init(void) { ereport(LOG, (errcode_for_socket_access(), - errmsg("could not set statistics socket to nonblock mode: %m"))); + errmsg("could not set statistics socket to nonblock mode: %m"))); goto startup_failed; } @@ -276,7 +279,7 @@ pgstat_init(void) { ereport(LOG, (errcode_for_socket_access(), - errmsg("could not create pipe for statistics collector: %m"))); + errmsg("could not create pipe for statistics collector: %m"))); goto startup_failed; } @@ -320,10 +323,10 @@ pgstat_start(void) /* * Do nothing if too soon since last collector start. This is a - * safety valve to protect against continuous respawn attempts if - * the collector is dying immediately at launch. Note that since - * we will be re-called from the postmaster main loop, we will get - * another chance later. + * safety valve to protect against continuous respawn attempts if the + * collector is dying immediately at launch. Note that since we will + * be re-called from the postmaster main loop, we will get another + * chance later. */ curtime = time(NULL); if ((unsigned int) (curtime - last_pgstat_start_time) < @@ -338,6 +341,7 @@ pgstat_start(void) { ereport(LOG, (errmsg("statistics collector startup skipped"))); + /* * We can only get here if someone tries to manually turn * pgstat_collect_startcollector on after it had been off. @@ -347,7 +351,8 @@ pgstat_start(void) } /* - * Okay, fork off the collector. Remember its PID for pgstat_ispgstat. + * Okay, fork off the collector. Remember its PID for + * pgstat_ispgstat. */ fflush(stdout); @@ -772,7 +777,7 @@ pgstat_reset_counters(void) if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to reset statistics counters"))); + errmsg("must be superuser to reset statistics counters"))); pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER); pgstat_send(&msg, sizeof(msg)); @@ -897,7 +902,7 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) */ if (pgStatTabstatUsed >= pgStatTabstatAlloc) { - int newAlloc = pgStatTabstatAlloc + TABSTAT_QUANTUM; + int newAlloc = pgStatTabstatAlloc + TABSTAT_QUANTUM; PgStat_MsgTabstat *newMessages; PgStat_MsgTabstat **msgArray; @@ -1251,7 +1256,7 @@ pgstat_main(void) { ereport(LOG, (errcode_for_socket_access(), - errmsg("could not create pipe for statistics buffer: %m"))); + errmsg("could not create pipe for statistics buffer: %m"))); exit(1); } @@ -1316,7 +1321,7 @@ pgstat_main(void) /* assume the problem is out-of-memory */ ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory in statistics collector --- abort"))); + errmsg("out of memory in statistics collector --- abort"))); exit(1); } @@ -1394,7 +1399,7 @@ pgstat_main(void) continue; ereport(LOG, (errcode_for_socket_access(), - errmsg("select failed in statistics collector: %m"))); + errmsg("select failed in statistics collector: %m"))); exit(1); } @@ -1436,7 +1441,7 @@ pgstat_main(void) continue; ereport(LOG, (errcode_for_socket_access(), - errmsg("could not read from statistics pipe: %m"))); + errmsg("could not read from statistics pipe: %m"))); exit(1); } if (len == 0) /* EOF on the pipe! */ @@ -1455,7 +1460,7 @@ pgstat_main(void) * that we can restart both processes. */ ereport(LOG, - (errmsg("invalid statistics message length"))); + (errmsg("invalid statistics message length"))); exit(1); } } @@ -1579,7 +1584,7 @@ pgstat_recvbuffer(void) int msg_send = 0; /* next send index in buffer */ int msg_recv = 0; /* next receive index */ int msg_have = 0; /* number of bytes stored */ - struct sockaddr_storage fromaddr; + struct sockaddr_storage fromaddr; int fromlen; bool overflow = false; @@ -1607,7 +1612,7 @@ pgstat_recvbuffer(void) { ereport(LOG, (errcode_for_socket_access(), - errmsg("could not set statistics pipe to nonblock mode: %m"))); + errmsg("could not set statistics pipe to nonblock mode: %m"))); exit(1); } @@ -1619,7 +1624,7 @@ pgstat_recvbuffer(void) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory in statistics collector --- abort"))); + errmsg("out of memory in statistics collector --- abort"))); exit(1); } @@ -1692,13 +1697,13 @@ pgstat_recvbuffer(void) { fromlen = sizeof(fromaddr); len = recvfrom(pgStatSock, (char *) &input_buffer, - sizeof(PgStat_Msg), 0, - (struct sockaddr *) &fromaddr, &fromlen); + sizeof(PgStat_Msg), 0, + (struct sockaddr *) &fromaddr, &fromlen); if (len < 0) { ereport(LOG, (errcode_for_socket_access(), - errmsg("failed to read statistics message: %m"))); + errmsg("failed to read statistics message: %m"))); exit(1); } @@ -1887,7 +1892,7 @@ pgstat_add_backend(PgStat_MsgHdr *msg) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory in statistics collector --- abort"))); + errmsg("out of memory in statistics collector --- abort"))); exit(1); } @@ -1919,7 +1924,7 @@ pgstat_add_backend(PgStat_MsgHdr *msg) /* assume the problem is out-of-memory */ ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory in statistics collector --- abort"))); + errmsg("out of memory in statistics collector --- abort"))); exit(1); } } @@ -2234,7 +2239,7 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory in statistics collector --- abort"))); + errmsg("out of memory in statistics collector --- abort"))); exit(1); } /* in backend, can do normal error */ @@ -2621,7 +2626,7 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory in statistics collector --- abort"))); + errmsg("out of memory in statistics collector --- abort"))); exit(1); } @@ -2803,7 +2808,7 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len) /* assume the problem is out-of-memory */ ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory in statistics collector --- abort"))); + errmsg("out of memory in statistics collector --- abort"))); exit(1); } } diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 3adea9ab40..9692c8898d 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -37,7 +37,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/postmaster/postmaster.c,v 1.338 2003/08/01 23:25:00 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/postmaster/postmaster.c,v 1.339 2003/08/04 00:43:21 momjian Exp $ * * NOTES * @@ -169,14 +169,15 @@ int ReservedBackends; static char *progname = (char *) NULL; /* The socket(s) we're listening to. */ -#define MAXLISTEN 10 +#define MAXLISTEN 10 static int ListenSocket[MAXLISTEN]; /* Used to reduce macros tests */ #ifdef EXEC_BACKEND -const bool ExecBackend = true; +const bool ExecBackend = true; + #else -const bool ExecBackend = false; +const bool ExecBackend = false; #endif /* @@ -210,15 +211,15 @@ bool LogSourcePort; bool Log_connections = false; bool Db_user_namespace = false; -char *rendezvous_name; +char *rendezvous_name; /* For FNCTL_NONBLOCK */ #if defined(WIN32) || defined(__BEOS__) -long ioctlsocket_ret; +long ioctlsocket_ret; #endif /* list of library:init-function to be preloaded */ -char *preload_libraries_string = NULL; +char *preload_libraries_string = NULL; /* Startup/shutdown state */ static pid_t StartupPID = 0, @@ -290,7 +291,8 @@ static void SignalChildren(int signal); static int CountChildren(void); static bool CreateOptsFile(int argc, char *argv[]); static pid_t SSDataBase(int xlop); -static void postmaster_error(const char *fmt,...) +static void +postmaster_error(const char *fmt,...) /* This lets gcc check the format string for consistency. */ __attribute__((format(printf, 1, 2))); @@ -327,8 +329,8 @@ checkDataDir(const char *checkdir) else ereport(FATAL, (errcode_for_file_access(), - errmsg("could not read permissions of directory \"%s\": %m", - checkdir))); + errmsg("could not read permissions of directory \"%s\": %m", + checkdir))); } /* @@ -357,7 +359,7 @@ checkDataDir(const char *checkdir) { fprintf(stderr, gettext("%s could not find the database system.\n" - "Expected to find it in the PGDATA directory \"%s\",\n" + "Expected to find it in the PGDATA directory \"%s\",\n" "but failed to open file \"%s\": %s\n"), progname, checkdir, path, strerror(errno)); ExitPostmaster(2); @@ -374,17 +376,16 @@ reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context) { } - #endif int PostmasterMain(int argc, char *argv[]) { - int opt; - int status; + int opt; + int status; char original_extraoptions[MAXPGPATH]; - char *potential_DataDir = NULL; - int i; + char *potential_DataDir = NULL; + int i; *original_extraoptions = '\0'; @@ -581,7 +582,7 @@ PostmasterMain(int argc, char *argv[]) default: fprintf(stderr, - gettext("Try '%s --help' for more information.\n"), + gettext("Try '%s --help' for more information.\n"), progname); ExitPostmaster(1); } @@ -682,8 +683,8 @@ PostmasterMain(int argc, char *argv[]) #endif /* - * process any libraries that should be preloaded and - * optionally pre-initialized + * process any libraries that should be preloaded and optionally + * pre-initialized */ if (preload_libraries_string) process_preload_libraries(preload_libraries_string); @@ -725,13 +726,14 @@ PostmasterMain(int argc, char *argv[]) { if (VirtualHost && VirtualHost[0]) { - char *curhost, *endptr; - char c = 0; + char *curhost, + *endptr; + char c = 0; curhost = VirtualHost; for (;;) { - while (*curhost == ' ') /* skip any extra spaces */ + while (*curhost == ' ') /* skip any extra spaces */ curhost++; if (*curhost == '\0') break; @@ -747,8 +749,8 @@ PostmasterMain(int argc, char *argv[]) ListenSocket, MAXLISTEN); if (status != STATUS_OK) ereport(LOG, - (errmsg("could not create listen socket for \"%s\"", - curhost))); + (errmsg("could not create listen socket for \"%s\"", + curhost))); if (endptr) { *endptr = c; @@ -766,10 +768,10 @@ PostmasterMain(int argc, char *argv[]) ListenSocket, MAXLISTEN); if (status != STATUS_OK) ereport(LOG, - (errmsg("could not create TCP/IP listen socket"))); + (errmsg("could not create TCP/IP listen socket"))); } -#ifdef USE_RENDEZVOUS +#ifdef USE_RENDEZVOUS if (rendezvous_name != NULL) { DNSServiceRegistrationCreate(rendezvous_name, @@ -777,7 +779,7 @@ PostmasterMain(int argc, char *argv[]) "", htonl(PostPortNumber), "", - (DNSServiceRegistrationReply)reg_reply, + (DNSServiceRegistrationReply) reg_reply, NULL); } #endif @@ -842,8 +844,8 @@ PostmasterMain(int argc, char *argv[]) /* * Reset whereToSendOutput from Debug (its starting state) to None. - * This prevents ereport from sending log messages to stderr unless the - * syslog/stderr switch permits. We don't do this until the + * This prevents ereport from sending log messages to stderr unless + * the syslog/stderr switch permits. We don't do this until the * postmaster is fully launched, since startup failures may as well be * reported to stderr. */ @@ -989,10 +991,11 @@ usage(const char *progname) static int ServerLoop(void) { - fd_set readmask; + fd_set readmask; int nSockets; - struct timeval now, later; - struct timezone tz; + struct timeval now, + later; + struct timezone tz; int i; gettimeofday(&now, &tz); @@ -1090,8 +1093,8 @@ ServerLoop(void) } /* - * New connection pending on any of our sockets? If so, - * fork a child process to deal with it. + * New connection pending on any of our sockets? If so, fork a + * child process to deal with it. */ for (i = 0; i < MAXLISTEN; i++) { @@ -1105,8 +1108,8 @@ ServerLoop(void) BackendStartup(port); /* - * We no longer need the open socket - * or port structure in this process + * We no longer need the open socket or port structure + * in this process */ StreamClose(port->sock); ConnFree(port); @@ -1136,7 +1139,7 @@ initMasks(fd_set *rmask) for (i = 0; i < MAXLISTEN; i++) { - int fd = ListenSocket[i]; + int fd = ListenSocket[i]; if (fd == -1) break; @@ -1173,7 +1176,7 @@ ProcessStartupPacket(Port *port, bool SSLdone) { /* * EOF after SSLdone probably means the client didn't like our - * response to NEGOTIATE_SSL_CODE. That's not an error condition, + * response to NEGOTIATE_SSL_CODE. That's not an error condition, * so don't clutter the log with a complaint. */ if (!SSLdone) @@ -1197,9 +1200,9 @@ ProcessStartupPacket(Port *port, bool SSLdone) /* * Allocate at least the size of an old-style startup packet, plus one - * extra byte, and make sure all are zeroes. This ensures we will have - * null termination of all strings, in both fixed- and variable-length - * packet layouts. + * extra byte, and make sure all are zeroes. This ensures we will + * have null termination of all strings, in both fixed- and + * variable-length packet layouts. */ if (len <= (int32) sizeof(StartupPacket)) buf = palloc0(sizeof(StartupPacket) + 1); @@ -1243,7 +1246,7 @@ ProcessStartupPacket(Port *port, bool SSLdone) { ereport(COMMERROR, (errcode_for_socket_access(), - errmsg("failed to send SSL negotiation response: %m"))); + errmsg("failed to send SSL negotiation response: %m"))); return STATUS_ERROR; /* close the connection */ } @@ -1259,41 +1262,41 @@ ProcessStartupPacket(Port *port, bool SSLdone) /* Could add additional special packet types here */ /* - * Set FrontendProtocol now so that ereport() knows what format to send - * if we fail during startup. + * Set FrontendProtocol now so that ereport() knows what format to + * send if we fail during startup. */ FrontendProtocol = proto; /* Check we can handle the protocol the frontend is using. */ if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) || - PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) || - (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) && - PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))) + PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) || + (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) && + PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))) ereport(FATAL, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u", - PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto), + PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto), PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST), PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST), PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))); /* * Now fetch parameters out of startup packet and save them into the - * Port structure. All data structures attached to the Port struct + * Port structure. All data structures attached to the Port struct * must be allocated in TopMemoryContext so that they won't disappear - * when we pass them to PostgresMain (see BackendFork). We need not worry - * about leaking this storage on failure, since we aren't in the postmaster - * process anymore. + * when we pass them to PostgresMain (see BackendFork). We need not + * worry about leaking this storage on failure, since we aren't in the + * postmaster process anymore. */ oldcontext = MemoryContextSwitchTo(TopMemoryContext); if (PG_PROTOCOL_MAJOR(proto) >= 3) { - int32 offset = sizeof(ProtocolVersion); + int32 offset = sizeof(ProtocolVersion); /* - * Scan packet body for name/option pairs. We can assume any + * Scan packet body for name/option pairs. We can assume any * string beginning within the packet body is null-terminated, * thanks to zeroing extra byte above. */ @@ -1301,9 +1304,9 @@ ProcessStartupPacket(Port *port, bool SSLdone) while (offset < len) { - char *nameptr = ((char *) buf) + offset; - int32 valoffset; - char *valptr; + char *nameptr = ((char *) buf) + offset; + int32 valoffset; + char *valptr; if (*nameptr == '\0') break; /* found packet terminator */ @@ -1328,11 +1331,12 @@ ProcessStartupPacket(Port *port, bool SSLdone) } offset = valoffset + strlen(valptr) + 1; } + /* * If we didn't find a packet terminator exactly at the end of the * given packet length, complain. */ - if (offset != len-1) + if (offset != len - 1) ereport(FATAL, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("invalid startup packet layout: expected terminator as last byte"))); @@ -1340,10 +1344,11 @@ ProcessStartupPacket(Port *port, bool SSLdone) else { /* - * Get the parameters from the old-style, fixed-width-fields startup - * packet as C strings. The packet destination was cleared first so a - * short packet has zeros silently added. We have to be prepared to - * truncate the pstrdup result for oversize fields, though. + * Get the parameters from the old-style, fixed-width-fields + * startup packet as C strings. The packet destination was + * cleared first so a short packet has zeros silently added. We + * have to be prepared to truncate the pstrdup result for oversize + * fields, though. */ StartupPacket *packet = (StartupPacket *) buf; @@ -1363,7 +1368,7 @@ ProcessStartupPacket(Port *port, bool SSLdone) if (port->user_name == NULL || port->user_name[0] == '\0') ereport(FATAL, (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), - errmsg("no PostgreSQL user name specified in startup packet"))); + errmsg("no PostgreSQL user name specified in startup packet"))); /* The database defaults to the user name. */ if (port->database_name == NULL || port->database_name[0] == '\0') @@ -1468,10 +1473,8 @@ processCancelRequest(Port *port, void *pkt) return; } else if (ExecBackend) - { AttachSharedMemoryAndSemaphores(); - } - + /* See if we have a matching backend */ for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr)) @@ -1590,7 +1593,7 @@ ConnFree(Port *conn) void ClosePostmasterPorts(bool pgstat_too) { - int i; + int i; /* Close the listen sockets */ for (i = 0; i < MAXLISTEN; i++) @@ -1639,7 +1642,7 @@ SIGHUP_handler(SIGNAL_ARGS) if (Shutdown <= SmartShutdown) { ereport(LOG, - (errmsg("received SIGHUP, reloading configuration files"))); + (errmsg("received SIGHUP, reloading configuration files"))); ProcessConfigFile(PGC_SIGHUP); #ifdef EXEC_BACKEND write_nondefault_variables(PGC_SIGHUP); @@ -1806,9 +1809,9 @@ reaper(SIGNAL_ARGS) #endif /* - * Check if this child was the statistics collector. If so, - * try to start a new one. (If fail, we'll try again in - * future cycles of the main loop.) + * Check if this child was the statistics collector. If so, try to + * start a new one. (If fail, we'll try again in future cycles of + * the main loop.) */ if (pgstat_ispgstat(pid)) { @@ -1883,7 +1886,7 @@ reaper(SIGNAL_ARGS) */ CleanupProc(pid, exitstatus); - } /* loop over pending child-death reports */ + } /* loop over pending child-death reports */ #endif if (FatalError) @@ -1895,7 +1898,7 @@ reaper(SIGNAL_ARGS) if (DLGetHead(BackendList) || StartupPID > 0 || ShutdownPID > 0) goto reaper_done; ereport(LOG, - (errmsg("all server processes terminated; reinitializing"))); + (errmsg("all server processes terminated; reinitializing"))); shmem_exit(0); reset_shared(PostPortNumber); @@ -1979,11 +1982,11 @@ CleanupProc(int pid, if (!FatalError) { LogChildExit(LOG, - (pid == CheckPointPID) ? gettext("checkpoint process") : + (pid == CheckPointPID) ? gettext("checkpoint process") : gettext("server process"), pid, exitstatus); ereport(LOG, - (errmsg("terminating any other active server processes"))); + (errmsg("terminating any other active server processes"))); } curr = DLGetHead(BackendList); @@ -2045,26 +2048,29 @@ LogChildExit(int lev, const char *procname, int pid, int exitstatus) { if (WIFEXITED(exitstatus)) ereport(lev, - /* - * translator: %s is a noun phrase describing a child process, - * such as "server process" - */ + + /* + * translator: %s is a noun phrase describing a child process, + * such as "server process" + */ (errmsg("%s (pid %d) exited with exit code %d", procname, pid, WEXITSTATUS(exitstatus)))); else if (WIFSIGNALED(exitstatus)) ereport(lev, - /* - * translator: %s is a noun phrase describing a child process, - * such as "server process" - */ + + /* + * translator: %s is a noun phrase describing a child process, + * such as "server process" + */ (errmsg("%s (pid %d) was terminated by signal %d", procname, pid, WTERMSIG(exitstatus)))); else ereport(lev, - /* - * translator: %s is a noun phrase describing a child process, - * such as "server process" - */ + + /* + * translator: %s is a noun phrase describing a child process, + * such as "server process" + */ (errmsg("%s (pid %d) exited with unexpected status %d", procname, pid, exitstatus))); } @@ -2195,7 +2201,7 @@ BackendStartup(Port *port) free(bn); errno = save_errno; ereport(LOG, - (errmsg("could not fork new process for connection: %m"))); + (errmsg("could not fork new process for connection: %m"))); report_fork_failure_to_client(port, save_errno); return STATUS_ERROR; } @@ -2284,18 +2290,19 @@ split_opts(char **argv, int *argcp, char *s) static int BackendFork(Port *port) { - char **av; - int maxac; - int ac; + char **av; + int maxac; + int ac; char debugbuf[32]; char protobuf[32]; + #ifdef EXEC_BACKEND char pbuf[NAMEDATALEN + 256]; #endif - int i; - int status; - struct timeval now; - struct timezone tz; + int i; + int status; + struct timeval now; + struct timezone tz; char remote_host[NI_MAXHOST]; char remote_port[NI_MAXSERV]; @@ -2324,8 +2331,8 @@ BackendFork(Port *port) MyProcPid = getpid(); /* - * Initialize libpq and enable reporting of ereport errors to the client. - * Must do this now because authentication uses libpq to send + * Initialize libpq and enable reporting of ereport errors to the + * client. Must do this now because authentication uses libpq to send * messages. */ pq_init(); /* initialize libpq to talk to client */ @@ -2350,7 +2357,7 @@ BackendFork(Port *port) if (getnameinfo_all(&port->raddr.addr, port->raddr.salen, remote_host, sizeof(remote_host), remote_port, sizeof(remote_port), - (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) + (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) { getnameinfo_all(&port->raddr.addr, port->raddr.salen, remote_host, sizeof(remote_host), @@ -2366,7 +2373,7 @@ BackendFork(Port *port) if (LogSourcePort) { /* modify remote_host for use in ps status */ - char tmphost[NI_MAXHOST]; + char tmphost[NI_MAXHOST]; snprintf(tmphost, sizeof(tmphost), "%s:%s", remote_host, remote_port); StrNCpy(remote_host, tmphost, sizeof(remote_host)); @@ -2484,14 +2491,15 @@ BackendFork(Port *port) */ av[ac++] = "-p"; #ifdef EXEC_BACKEND - Assert(UsedShmemSegID != 0 && UsedShmemSegAddr != NULL); + Assert(UsedShmemSegID != 0 && UsedShmemSegAddr != NULL); /* database name at the end because it might contain commas */ snprintf(pbuf, NAMEDATALEN + 256, "%d,%d,%d,%p,%s", port->sock, canAcceptConnections(), - UsedShmemSegID, UsedShmemSegAddr, port->database_name); + UsedShmemSegID, UsedShmemSegAddr, port->database_name); av[ac++] = pbuf; #else av[ac++] = port->database_name; #endif + /* * Pass the (insecure) option switches from the connection request. * (It's OK to mangle port->cmdline_options now.) @@ -2507,7 +2515,7 @@ BackendFork(Port *port) * Release postmaster's working memory context so that backend can * recycle the space. Note this does not trash *MyProcPort, because * ConnCreate() allocated that space with malloc() ... else we'd need - * to copy the Port data here. Also, subsidiary data such as the + * to copy the Port data here. Also, subsidiary data such as the * username isn't lost either; see ProcessStartupPacket(). */ MemoryContextSwitchTo(TopMemoryContext); @@ -2565,21 +2573,21 @@ sigusr1_handler(SIGNAL_ARGS) if (CheckPointWarning != 0) { /* - * This only times checkpoints forced by running out of - * segment files. Other checkpoints could reduce - * the frequency of forced checkpoints. + * This only times checkpoints forced by running out of + * segment files. Other checkpoints could reduce the + * frequency of forced checkpoints. */ - time_t now = time(NULL); + time_t now = time(NULL); if (LastSignalledCheckpoint != 0) { - int elapsed_secs = now - LastSignalledCheckpoint; + int elapsed_secs = now - LastSignalledCheckpoint; if (elapsed_secs < CheckPointWarning) ereport(LOG, (errmsg("checkpoints are occurring too frequently (%d seconds apart)", elapsed_secs), - errhint("Consider increasing CHECKPOINT_SEGMENTS."))); + errhint("Consider increasing CHECKPOINT_SEGMENTS."))); } LastSignalledCheckpoint = now; } @@ -2763,6 +2771,7 @@ SSDataBase(int xlop) int ac = 0; char nbbuf[32]; char xlbuf[32]; + #ifdef EXEC_BACKEND char pbuf[NAMEDATALEN + 256]; #endif @@ -2817,10 +2826,10 @@ SSDataBase(int xlop) av[ac++] = "-p"; #ifdef EXEC_BACKEND - Assert(UsedShmemSegID != 0 && UsedShmemSegAddr != NULL); + Assert(UsedShmemSegID != 0 && UsedShmemSegAddr != NULL); /* database name at the end because it might contain commas */ snprintf(pbuf, NAMEDATALEN + 256, "%d,%p,%s", UsedShmemSegID, - UsedShmemSegAddr, "template1"); + UsedShmemSegAddr, "template1"); av[ac++] = pbuf; #else av[ac++] = "template1"; @@ -2850,7 +2859,7 @@ SSDataBase(int xlop) break; case BS_XLOG_CHECKPOINT: ereport(LOG, - (errmsg("could not fork checkpoint process: %m"))); + (errmsg("could not fork checkpoint process: %m"))); break; case BS_XLOG_SHUTDOWN: ereport(LOG, diff --git a/src/backend/regex/regc_color.c b/src/backend/regex/regc_color.c index eb25055682..da2b79b5f0 100644 --- a/src/backend/regex/regc_color.c +++ b/src/backend/regex/regc_color.c @@ -2,21 +2,21 @@ * colorings of characters * This file is #included by regcomp.c. * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -28,7 +28,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regc_color.c,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regc_color.c,v 1.2 2003/08/04 00:43:21 momjian Exp $ * * * Note that there are some incestuous relationships between this code and @@ -37,8 +37,8 @@ -#define CISERR() VISERR(cm->v) -#define CERR(e) VERR(cm->v, (e)) +#define CISERR() VISERR(cm->v) +#define CERR(e) VERR(cm->v, (e)) @@ -46,11 +46,11 @@ * initcm - set up new colormap */ static void -initcm(struct vars *v, - struct colormap *cm) +initcm(struct vars * v, + struct colormap * cm) { - int i; - int j; + int i; + int j; union tree *t; union tree *nextt; struct colordesc *cd; @@ -63,21 +63,22 @@ initcm(struct vars *v, cm->max = 0; cm->free = 0; - cd = cm->cd; /* cm->cd[WHITE] */ + cd = cm->cd; /* cm->cd[WHITE] */ cd->sub = NOSUB; cd->arcs = NULL; cd->flags = 0; cd->nchrs = CHR_MAX - CHR_MIN + 1; /* upper levels of tree */ - for (t = &cm->tree[0], j = NBYTS-1; j > 0; t = nextt, j--) { + for (t = &cm->tree[0], j = NBYTS - 1; j > 0; t = nextt, j--) + { nextt = t + 1; - for (i = BYTTAB-1; i >= 0; i--) + for (i = BYTTAB - 1; i >= 0; i--) t->tptr[i] = nextt; } /* bottom level is solid white */ - t = &cm->tree[NBYTS-1]; - for (i = BYTTAB-1; i >= 0; i--) + t = &cm->tree[NBYTS - 1]; + for (i = BYTTAB - 1; i >= 0; i--) t->tcolor[i] = WHITE; cd->block = t; } @@ -86,16 +87,17 @@ initcm(struct vars *v, * freecm - free dynamically-allocated things in a colormap */ static void -freecm(struct colormap *cm) +freecm(struct colormap * cm) { - size_t i; + size_t i; union tree *cb; cm->magic = 0; if (NBYTS > 1) cmtreefree(cm, cm->tree, 0); for (i = 1; i <= cm->max; i++) /* skip WHITE */ - if (!UNUSEDCOLOR(&cm->cd[i])) { + if (!UNUSEDCOLOR(&cm->cd[i])) + { cb = cm->cd[i].block; if (cb != NULL) FREE(cb); @@ -108,24 +110,29 @@ freecm(struct colormap *cm) * cmtreefree - free a non-terminal part of a colormap tree */ static void -cmtreefree(struct colormap *cm, - union tree *tree, +cmtreefree(struct colormap * cm, + union tree * tree, int level) /* level number (top == 0) of this block */ { - int i; + int i; union tree *t; - union tree *fillt = &cm->tree[level+1]; + union tree *fillt = &cm->tree[level + 1]; union tree *cb; - assert(level < NBYTS-1); /* this level has pointers */ - for (i = BYTTAB-1; i >= 0; i--) { + assert(level < NBYTS - 1); /* this level has pointers */ + for (i = BYTTAB - 1; i >= 0; i--) + { t = tree->tptr[i]; assert(t != NULL); - if (t != fillt) { - if (level < NBYTS-2) { /* more pointer blocks below */ - cmtreefree(cm, t, level+1); + if (t != fillt) + { + if (level < NBYTS - 2) + { /* more pointer blocks below */ + cmtreefree(cm, t, level + 1); FREE(t); - } else { /* color block below */ + } + else + { /* color block below */ cb = cm->cd[t->tcolor[0]].block; if (t != cb) /* not a solid block */ FREE(t); @@ -137,22 +144,22 @@ cmtreefree(struct colormap *cm, /* * setcolor - set the color of a character in a colormap */ -static color /* previous color */ -setcolor(struct colormap *cm, +static color /* previous color */ +setcolor(struct colormap * cm, chr c, pcolor co) { - uchr uc = c; - int shift; - int level; - int b; - int bottom; + uchr uc = c; + int shift; + int level; + int b; + int bottom; union tree *t; union tree *newt; union tree *fillt; union tree *lastt; union tree *cb; - color prev; + color prev; assert(cm->magic == CMMAGIC); if (CISERR() || co == COLORLESS) @@ -160,27 +167,30 @@ setcolor(struct colormap *cm, t = cm->tree; for (level = 0, shift = BYTBITS * (NBYTS - 1); shift > 0; - level++, shift -= BYTBITS) { + level++, shift -= BYTBITS) + { b = (uc >> shift) & BYTMASK; lastt = t; t = lastt->tptr[b]; assert(t != NULL); - fillt = &cm->tree[level+1]; + fillt = &cm->tree[level + 1]; bottom = (shift <= BYTBITS) ? 1 : 0; cb = (bottom) ? cm->cd[t->tcolor[0]].block : fillt; - if (t == fillt || t == cb) { /* must allocate a new block */ - newt = (union tree *)MALLOC((bottom) ? - sizeof(struct colors) : sizeof(struct ptrs)); - if (newt == NULL) { + if (t == fillt || t == cb) + { /* must allocate a new block */ + newt = (union tree *) MALLOC((bottom) ? + sizeof(struct colors) : sizeof(struct ptrs)); + if (newt == NULL) + { CERR(REG_ESPACE); return COLORLESS; } if (bottom) memcpy(VS(newt->tcolor), VS(t->tcolor), - BYTTAB*sizeof(color)); + BYTTAB * sizeof(color)); else memcpy(VS(newt->tptr), VS(t->tptr), - BYTTAB*sizeof(union tree *)); + BYTTAB * sizeof(union tree *)); t = newt; lastt->tptr[b] = t; } @@ -188,7 +198,7 @@ setcolor(struct colormap *cm, b = uc & BYTMASK; prev = t->tcolor[b]; - t->tcolor[b] = (color)co; + t->tcolor[b] = (color) co; return prev; } @@ -196,51 +206,59 @@ setcolor(struct colormap *cm, * maxcolor - report largest color number in use */ static color -maxcolor(struct colormap *cm) +maxcolor(struct colormap * cm) { if (CISERR()) return COLORLESS; - return (color)cm->max; + return (color) cm->max; } /* * newcolor - find a new color (must be subject of setcolor at once) - * Beware: may relocate the colordescs. + * Beware: may relocate the colordescs. */ -static color /* COLORLESS for error */ -newcolor(struct colormap *cm) +static color /* COLORLESS for error */ +newcolor(struct colormap * cm) { struct colordesc *cd; struct colordesc *new; - size_t n; + size_t n; if (CISERR()) return COLORLESS; - if (cm->free != 0) { + if (cm->free != 0) + { assert(cm->free > 0); - assert((size_t)cm->free < cm->ncds); + assert((size_t) cm->free < cm->ncds); cd = &cm->cd[cm->free]; assert(UNUSEDCOLOR(cd)); assert(cd->arcs == NULL); cm->free = cd->sub; - } else if (cm->max < cm->ncds - 1) { + } + else if (cm->max < cm->ncds - 1) + { cm->max++; cd = &cm->cd[cm->max]; - } else { + } + else + { /* oops, must allocate more */ n = cm->ncds * 2; - if (cm->cd == cm->cdspace) { - new = (struct colordesc *)MALLOC(n * - sizeof(struct colordesc)); + if (cm->cd == cm->cdspace) + { + new = (struct colordesc *) MALLOC(n * + sizeof(struct colordesc)); if (new != NULL) memcpy(VS(new), VS(cm->cdspace), cm->ncds * - sizeof(struct colordesc)); - } else - new = (struct colordesc *)REALLOC(cm->cd, - n * sizeof(struct colordesc)); - if (new == NULL) { + sizeof(struct colordesc)); + } + else + new = (struct colordesc *) REALLOC(cm->cd, + n * sizeof(struct colordesc)); + if (new == NULL) + { CERR(REG_ESPACE); return COLORLESS; } @@ -257,18 +275,19 @@ newcolor(struct colormap *cm) cd->flags = 0; cd->block = NULL; - return (color)(cd - cm->cd); + return (color) (cd - cm->cd); } /* * freecolor - free a color (must have no arcs or subcolor) */ static void -freecolor(struct colormap *cm, +freecolor(struct colormap * cm, pcolor co) { struct colordesc *cd = &cm->cd[co]; - color pco, nco; /* for freelist scan */ + color pco, + nco; /* for freelist scan */ assert(co >= 0); if (co == WHITE) @@ -278,35 +297,43 @@ freecolor(struct colormap *cm, assert(cd->sub == NOSUB); assert(cd->nchrs == 0); cd->flags = FREECOL; - if (cd->block != NULL) { + if (cd->block != NULL) + { FREE(cd->block); - cd->block = NULL; /* just paranoia */ + cd->block = NULL; /* just paranoia */ } - if ((size_t)co == cm->max) { + if ((size_t) co == cm->max) + { while (cm->max > WHITE && UNUSEDCOLOR(&cm->cd[cm->max])) cm->max--; assert(cm->free >= 0); - while ((size_t)cm->free > cm->max) + while ((size_t) cm->free > cm->max) cm->free = cm->cd[cm->free].sub; - if (cm->free > 0) { + if (cm->free > 0) + { assert(cm->free < cm->max); pco = cm->free; nco = cm->cd[pco].sub; while (nco > 0) - if ((size_t)nco > cm->max) { + if ((size_t) nco > cm->max) + { /* take this one out of freelist */ nco = cm->cd[nco].sub; cm->cd[pco].sub = nco; - } else { + } + else + { assert(nco < cm->max); pco = nco; nco = cm->cd[pco].sub; } } - } else { + } + else + { cd->sub = cm->free; - cm->free = (color)(cd - cm->cd); + cm->free = (color) (cd - cm->cd); } } @@ -314,9 +341,9 @@ freecolor(struct colormap *cm, * pseudocolor - allocate a false color, to be managed by other means */ static color -pseudocolor(struct colormap *cm) +pseudocolor(struct colormap * cm) { - color co; + color co; co = newcolor(cm); if (CISERR()) @@ -330,10 +357,10 @@ pseudocolor(struct colormap *cm) * subcolor - allocate a new subcolor (if necessary) to this chr */ static color -subcolor(struct colormap *cm, chr c) +subcolor(struct colormap * cm, chr c) { - color co; /* current color of c */ - color sco; /* new subcolor */ + color co; /* current color of c */ + color sco; /* new subcolor */ co = GETCOLOR(cm, c); sco = newsub(cm, co); @@ -341,8 +368,8 @@ subcolor(struct colormap *cm, chr c) return COLORLESS; assert(sco != COLORLESS); - if (co == sco) /* already in an open subcolor */ - return co; /* rest is redundant */ + if (co == sco) /* already in an open subcolor */ + return co; /* rest is redundant */ cm->cd[co].nchrs--; cm->cd[sco].nchrs++; setcolor(cm, c, sco); @@ -353,17 +380,19 @@ subcolor(struct colormap *cm, chr c) * newsub - allocate a new subcolor (if necessary) for a color */ static color -newsub(struct colormap *cm, +newsub(struct colormap * cm, pcolor co) { - color sco; /* new subcolor */ + color sco; /* new subcolor */ sco = cm->cd[co].sub; - if (sco == NOSUB) { /* color has no open subcolor */ - if (cm->cd[co].nchrs == 1) /* optimization */ + if (sco == NOSUB) + { /* color has no open subcolor */ + if (cm->cd[co].nchrs == 1) /* optimization */ return co; - sco = newcolor(cm); /* must create subcolor */ - if (sco == COLORLESS) { + sco = newcolor(cm); /* must create subcolor */ + if (sco == COLORLESS) + { assert(CISERR()); return COLORLESS; } @@ -379,23 +408,23 @@ newsub(struct colormap *cm, * subrange - allocate new subcolors to this range of chrs, fill in arcs */ static void -subrange(struct vars *v, +subrange(struct vars * v, chr from, chr to, - struct state *lp, - struct state *rp) + struct state * lp, + struct state * rp) { - uchr uf; - int i; + uchr uf; + int i; assert(from <= to); /* first, align "from" on a tree-block boundary */ - uf = (uchr)from; - i = (int)( ((uf + BYTTAB-1) & (uchr)~BYTMASK) - uf ); + uf = (uchr) from; + i = (int) (((uf + BYTTAB - 1) & (uchr) ~ BYTMASK) - uf); for (; from <= to && i > 0; i--, from++) newarc(v->nfa, PLAIN, subcolor(v->cm, from), lp, rp); - if (from > to) /* didn't reach a boundary */ + if (from > to) /* didn't reach a boundary */ return; /* deal with whole blocks */ @@ -411,25 +440,25 @@ subrange(struct vars *v, * subblock - allocate new subcolors for one tree block of chrs, fill in arcs */ static void -subblock(struct vars *v, +subblock(struct vars * v, chr start, /* first of BYTTAB chrs */ - struct state *lp, - struct state *rp) + struct state * lp, + struct state * rp) { - uchr uc = start; + uchr uc = start; struct colormap *cm = v->cm; - int shift; - int level; - int i; - int b; + int shift; + int level; + int i; + int b; union tree *t; union tree *cb; union tree *fillt; union tree *lastt; - int previ; - int ndone; - color co; - color sco; + int previ; + int ndone; + color co; + color sco; assert((uc % BYTTAB) == 0); @@ -437,20 +466,23 @@ subblock(struct vars *v, t = cm->tree; fillt = NULL; for (level = 0, shift = BYTBITS * (NBYTS - 1); shift > 0; - level++, shift -= BYTBITS) { + level++, shift -= BYTBITS) + { b = (uc >> shift) & BYTMASK; lastt = t; t = lastt->tptr[b]; assert(t != NULL); - fillt = &cm->tree[level+1]; - if (t == fillt && shift > BYTBITS) { /* need new ptr block */ - t = (union tree *)MALLOC(sizeof(struct ptrs)); - if (t == NULL) { + fillt = &cm->tree[level + 1]; + if (t == fillt && shift > BYTBITS) + { /* need new ptr block */ + t = (union tree *) MALLOC(sizeof(struct ptrs)); + if (t == NULL) + { CERR(REG_ESPACE); return; } memcpy(VS(t->tptr), VS(fillt->tptr), - BYTTAB*sizeof(union tree *)); + BYTTAB * sizeof(union tree *)); lastt->tptr[b] = t; } } @@ -458,13 +490,16 @@ subblock(struct vars *v, /* special cases: fill block or solid block */ co = t->tcolor[0]; cb = cm->cd[co].block; - if (t == fillt || t == cb) { + if (t == fillt || t == cb) + { /* either way, we want a subcolor solid block */ sco = newsub(cm, co); t = cm->cd[sco].block; - if (t == NULL) { /* must set it up */ - t = (union tree *)MALLOC(sizeof(struct colors)); - if (t == NULL) { + if (t == NULL) + { /* must set it up */ + t = (union tree *) MALLOC(sizeof(struct colors)); + if (t == NULL) + { CERR(REG_ESPACE); return; } @@ -482,12 +517,14 @@ subblock(struct vars *v, /* general case, a mixed block to be altered */ i = 0; - while (i < BYTTAB) { + while (i < BYTTAB) + { co = t->tcolor[i]; sco = newsub(cm, co); newarc(v->nfa, PLAIN, sco, lp, rp); previ = i; - do { + do + { t->tcolor[i++] = sco; } while (i < BYTTAB && t->tcolor[i] == co); ndone = i - previ; @@ -500,30 +537,37 @@ subblock(struct vars *v, * okcolors - promote subcolors to full colors */ static void -okcolors(struct nfa *nfa, - struct colormap *cm) +okcolors(struct nfa * nfa, + struct colormap * cm) { struct colordesc *cd; struct colordesc *end = CDEND(cm); struct colordesc *scd; struct arc *a; - color co; - color sco; + color co; + color sco; - for (cd = cm->cd, co = 0; cd < end; cd++, co++) { + for (cd = cm->cd, co = 0; cd < end; cd++, co++) + { sco = cd->sub; - if (UNUSEDCOLOR(cd) || sco == NOSUB) { + if (UNUSEDCOLOR(cd) || sco == NOSUB) + { /* has no subcolor, no further action */ - } else if (sco == co) { + } + else if (sco == co) + { /* is subcolor, let parent deal with it */ - } else if (cd->nchrs == 0) { + } + else if (cd->nchrs == 0) + { /* parent empty, its arcs change color to subcolor */ cd->sub = NOSUB; scd = &cm->cd[sco]; assert(scd->nchrs > 0); assert(scd->sub == sco); scd->sub = NOSUB; - while ((a = cd->arcs) != NULL) { + while ((a = cd->arcs) != NULL) + { assert(a->co == co); /* uncolorchain(cm, a); */ cd->arcs = a->colorchain; @@ -533,14 +577,17 @@ okcolors(struct nfa *nfa, scd->arcs = a; } freecolor(cm, co); - } else { + } + else + { /* parent's arcs must gain parallel subcolor arcs */ cd->sub = NOSUB; scd = &cm->cd[sco]; assert(scd->nchrs > 0); assert(scd->sub == sco); scd->sub = NOSUB; - for (a = cd->arcs; a != NULL; a = a->colorchain) { + for (a = cd->arcs; a != NULL; a = a->colorchain) + { assert(a->co == co); newarc(nfa, a->type, sco, a->from, a->to); } @@ -552,8 +599,8 @@ okcolors(struct nfa *nfa, * colorchain - add this arc to the color chain of its color */ static void -colorchain(struct colormap *cm, - struct arc *a) +colorchain(struct colormap * cm, + struct arc * a) { struct colordesc *cd = &cm->cd[a->co]; @@ -565,32 +612,33 @@ colorchain(struct colormap *cm, * uncolorchain - delete this arc from the color chain of its color */ static void -uncolorchain(struct colormap *cm, - struct arc *a) +uncolorchain(struct colormap * cm, + struct arc * a) { struct colordesc *cd = &cm->cd[a->co]; struct arc *aa; aa = cd->arcs; - if (aa == a) /* easy case */ + if (aa == a) /* easy case */ cd->arcs = a->colorchain; - else { + else + { for (; aa != NULL && aa->colorchain != a; aa = aa->colorchain) continue; assert(aa != NULL); aa->colorchain = a->colorchain; } - a->colorchain = NULL; /* paranoia */ + a->colorchain = NULL; /* paranoia */ } /* * singleton - is this character in its own color? */ -static int /* predicate */ -singleton(struct colormap *cm, +static int /* predicate */ +singleton(struct colormap * cm, chr c) { - color co; /* color of c */ + color co; /* color of c */ co = GETCOLOR(cm, c); if (cm->cd[co].nchrs == 1 && cm->cd[co].sub == NOSUB) @@ -602,20 +650,20 @@ singleton(struct colormap *cm, * rainbow - add arcs of all full colors (but one) between specified states */ static void -rainbow(struct nfa *nfa, - struct colormap *cm, +rainbow(struct nfa * nfa, + struct colormap * cm, int type, pcolor but, /* COLORLESS if no exceptions */ - struct state *from, - struct state *to) + struct state * from, + struct state * to) { struct colordesc *cd; struct colordesc *end = CDEND(cm); - color co; + color co; for (cd = cm->cd, co = 0; cd < end && !CISERR(); cd++, co++) if (!UNUSEDCOLOR(cd) && cd->sub != co && co != but && - !(cd->flags&PSEUDO)) + !(cd->flags & PSEUDO)) newarc(nfa, type, co, from, to); } @@ -625,20 +673,21 @@ rainbow(struct nfa *nfa, * The calling sequence ought to be reconciled with cloneouts(). */ static void -colorcomplement(struct nfa *nfa, - struct colormap *cm, +colorcomplement(struct nfa * nfa, + struct colormap * cm, int type, - struct state *of, /* complements of this guy's PLAIN outarcs */ - struct state *from, - struct state *to) + struct state * of, /* complements of this guy's PLAIN + * outarcs */ + struct state * from, + struct state * to) { struct colordesc *cd; struct colordesc *end = CDEND(cm); - color co; + color co; assert(of != from); for (cd = cm->cd, co = 0; cd < end && !CISERR(); cd++, co++) - if (!UNUSEDCOLOR(cd) && !(cd->flags&PSEUDO)) + if (!UNUSEDCOLOR(cd) && !(cd->flags & PSEUDO)) if (findarc(of, PLAIN, co) == NULL) newarc(nfa, type, co, from, to); } @@ -650,28 +699,29 @@ colorcomplement(struct nfa *nfa, * dumpcolors - debugging output */ static void -dumpcolors(struct colormap *cm, +dumpcolors(struct colormap * cm, FILE *f) { struct colordesc *cd; struct colordesc *end; - color co; - chr c; - char *has; + color co; + chr c; + char *has; - fprintf(f, "max %ld\n", (long)cm->max); + fprintf(f, "max %ld\n", (long) cm->max); if (NBYTS > 1) fillcheck(cm, cm->tree, 0, f); end = CDEND(cm); - for (cd = cm->cd + 1, co = 1; cd < end; cd++, co++) /* skip 0 */ - if (!UNUSEDCOLOR(cd)) { + for (cd = cm->cd + 1, co = 1; cd < end; cd++, co++) /* skip 0 */ + if (!UNUSEDCOLOR(cd)) + { assert(cd->nchrs > 0); has = (cd->block != NULL) ? "#" : ""; - if (cd->flags&PSEUDO) - fprintf(f, "#%2ld%s(ps): ", (long)co, has); + if (cd->flags & PSEUDO) + fprintf(f, "#%2ld%s(ps): ", (long) co, has); else - fprintf(f, "#%2ld%s(%2d): ", (long)co, - has, cd->nchrs); + fprintf(f, "#%2ld%s(%2d): ", (long) co, + has, cd->nchrs); /* it's hard to do this more efficiently */ for (c = CHR_MIN; c < CHR_MAX; c++) if (GETCOLOR(cm, c) == co) @@ -687,24 +737,26 @@ dumpcolors(struct colormap *cm, * fillcheck - check proper filling of a tree */ static void -fillcheck(struct colormap *cm, - union tree *tree, +fillcheck(struct colormap * cm, + union tree * tree, int level, /* level number (top == 0) of this block */ FILE *f) { - int i; + int i; union tree *t; - union tree *fillt = &cm->tree[level+1]; + union tree *fillt = &cm->tree[level + 1]; - assert(level < NBYTS-1); /* this level has pointers */ - for (i = BYTTAB-1; i >= 0; i--) { + assert(level < NBYTS - 1); /* this level has pointers */ + for (i = BYTTAB - 1; i >= 0; i--) + { t = tree->tptr[i]; if (t == NULL) fprintf(f, "NULL found in filled tree!\n"); else if (t == fillt) - {} - else if (level < NBYTS-2) /* more pointer blocks below */ - fillcheck(cm, t, level+1, f); + { + } + else if (level < NBYTS - 2) /* more pointer blocks below */ + fillcheck(cm, t, level + 1, f); } } @@ -720,9 +772,9 @@ dumpchr(chr c, if (c == '\\') fprintf(f, "\\\\"); else if (c > ' ' && c <= '~') - putc((char)c, f); + putc((char) c, f); else - fprintf(f, "\\u%04lx", (long)c); + fprintf(f, "\\u%04lx", (long) c); } -#endif /* REG_DEBUG */ +#endif /* REG_DEBUG */ diff --git a/src/backend/regex/regc_cvec.c b/src/backend/regex/regc_cvec.c index 3b4e6ddb61..502bbeeca7 100644 --- a/src/backend/regex/regc_cvec.c +++ b/src/backend/regex/regc_cvec.c @@ -2,21 +2,21 @@ * Utility functions for handling cvecs * This file is #included by regcomp.c. * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -28,7 +28,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regc_cvec.c,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regc_cvec.c,v 1.2 2003/08/04 00:43:21 momjian Exp $ * */ @@ -40,23 +40,24 @@ newcvec(int nchrs, /* to hold this many chrs... */ int nranges, /* ... and this many ranges... */ int nmcces) /* ... and this many MCCEs */ { - size_t n; - size_t nc; - struct cvec *cv; + size_t n; + size_t nc; + struct cvec *cv; - nc = (size_t)nchrs + (size_t)nmcces*(MAXMCCE+1) + (size_t)nranges*2; - n = sizeof(struct cvec) + (size_t)(nmcces-1)*sizeof(chr *) - + nc*sizeof(chr); - cv = (struct cvec *)MALLOC(n); - if (cv == NULL) { - return NULL; - } - cv->chrspace = nchrs; - cv->chrs = (chr *)&cv->mcces[nmcces]; /* chrs just after MCCE ptrs */ - cv->mccespace = nmcces; - cv->ranges = cv->chrs + nchrs + nmcces*(MAXMCCE+1); - cv->rangespace = nranges; - return clearcvec(cv); + nc = (size_t) nchrs + (size_t) nmcces *(MAXMCCE + 1) + (size_t) nranges *2; + + n = sizeof(struct cvec) + (size_t) (nmcces - 1) * sizeof(chr *) + + nc * sizeof(chr); + cv = (struct cvec *) MALLOC(n); + if (cv == NULL) + return NULL; + cv->chrspace = nchrs; + cv->chrs = (chr *) & cv->mcces[nmcces]; /* chrs just after MCCE + * ptrs */ + cv->mccespace = nmcces; + cv->ranges = cv->chrs + nchrs + nmcces * (MAXMCCE + 1); + cv->rangespace = nranges; + return clearcvec(cv); } /* @@ -64,131 +65,125 @@ newcvec(int nchrs, /* to hold this many chrs... */ * Returns pointer as convenience. */ static struct cvec * -clearcvec(struct cvec *cv) +clearcvec(struct cvec * cv) { - int i; + int i; - assert(cv != NULL); - cv->nchrs = 0; - assert(cv->chrs == (chr *)&cv->mcces[cv->mccespace]); - cv->nmcces = 0; - cv->nmccechrs = 0; - cv->nranges = 0; - for (i = 0; i < cv->mccespace; i++) { - cv->mcces[i] = NULL; - } + assert(cv != NULL); + cv->nchrs = 0; + assert(cv->chrs == (chr *) & cv->mcces[cv->mccespace]); + cv->nmcces = 0; + cv->nmccechrs = 0; + cv->nranges = 0; + for (i = 0; i < cv->mccespace; i++) + cv->mcces[i] = NULL; - return cv; + return cv; } /* * addchr - add a chr to a cvec */ static void -addchr(struct cvec *cv, /* character vector */ - chr c) /* character to add */ +addchr(struct cvec * cv, /* character vector */ + chr c) /* character to add */ { - assert(cv->nchrs < cv->chrspace - cv->nmccechrs); - cv->chrs[cv->nchrs++] = (chr)c; + assert(cv->nchrs < cv->chrspace - cv->nmccechrs); + cv->chrs[cv->nchrs++] = (chr) c; } /* * addrange - add a range to a cvec */ static void -addrange(struct cvec *cv, /* character vector */ +addrange(struct cvec * cv, /* character vector */ chr from, /* first character of range */ chr to) /* last character of range */ { - assert(cv->nranges < cv->rangespace); - cv->ranges[cv->nranges*2] = (chr)from; - cv->ranges[cv->nranges*2 + 1] = (chr)to; - cv->nranges++; + assert(cv->nranges < cv->rangespace); + cv->ranges[cv->nranges * 2] = (chr) from; + cv->ranges[cv->nranges * 2 + 1] = (chr) to; + cv->nranges++; } /* * addmcce - add an MCCE to a cvec */ static void -addmcce(struct cvec *cv, /* character vector */ - chr *startp, /* beginning of text */ - chr *endp) /* just past end of text */ +addmcce(struct cvec * cv, /* character vector */ + chr * startp, /* beginning of text */ + chr * endp) /* just past end of text */ { - int len; - int i; - chr *s; - chr *d; + int len; + int i; + chr *s; + chr *d; - if (startp == NULL && endp == NULL) { - return; - } - len = endp - startp; - assert(len > 0); - assert(cv->nchrs + len < cv->chrspace - cv->nmccechrs); - assert(cv->nmcces < cv->mccespace); - d = &cv->chrs[cv->chrspace - cv->nmccechrs - len - 1]; - cv->mcces[cv->nmcces++] = d; - for (s = startp, i = len; i > 0; s++, i--) { - *d++ = *s; - } - *d++ = 0; /* endmarker */ - assert(d == &cv->chrs[cv->chrspace - cv->nmccechrs]); - cv->nmccechrs += len + 1; + if (startp == NULL && endp == NULL) + return; + len = endp - startp; + assert(len > 0); + assert(cv->nchrs + len < cv->chrspace - cv->nmccechrs); + assert(cv->nmcces < cv->mccespace); + d = &cv->chrs[cv->chrspace - cv->nmccechrs - len - 1]; + cv->mcces[cv->nmcces++] = d; + for (s = startp, i = len; i > 0; s++, i--) + *d++ = *s; + *d++ = 0; /* endmarker */ + assert(d == &cv->chrs[cv->chrspace - cv->nmccechrs]); + cv->nmccechrs += len + 1; } /* * haschr - does a cvec contain this chr? */ -static int /* predicate */ -haschr(struct cvec *cv, /* character vector */ - chr c) /* character to test for */ +static int /* predicate */ +haschr(struct cvec * cv, /* character vector */ + chr c) /* character to test for */ { - int i; - chr *p; + int i; + chr *p; - for (p = cv->chrs, i = cv->nchrs; i > 0; p++, i--) { - if (*p == c) { - return 1; + for (p = cv->chrs, i = cv->nchrs; i > 0; p++, i--) + { + if (*p == c) + return 1; } - } - for (p = cv->ranges, i = cv->nranges; i > 0; p += 2, i--) { - if ((*p <= c) && (c <= *(p+1))) { - return 1; + for (p = cv->ranges, i = cv->nranges; i > 0; p += 2, i--) + { + if ((*p <= c) && (c <= *(p + 1))) + return 1; } - } - return 0; + return 0; } /* * getcvec - get a cvec, remembering it as v->cv */ static struct cvec * -getcvec(struct vars *v, /* context */ +getcvec(struct vars * v, /* context */ int nchrs, /* to hold this many chrs... */ int nranges, /* ... and this many ranges... */ int nmcces) /* ... and this many MCCEs */ { - if (v->cv != NULL && nchrs <= v->cv->chrspace && - nranges <= v->cv->rangespace && nmcces <= v->cv->mccespace) { - return clearcvec(v->cv); - } + if (v->cv != NULL && nchrs <= v->cv->chrspace && + nranges <= v->cv->rangespace && nmcces <= v->cv->mccespace) + return clearcvec(v->cv); - if (v->cv != NULL) { - freecvec(v->cv); - } - v->cv = newcvec(nchrs, nranges, nmcces); - if (v->cv == NULL) { - ERR(REG_ESPACE); - } + if (v->cv != NULL) + freecvec(v->cv); + v->cv = newcvec(nchrs, nranges, nmcces); + if (v->cv == NULL) + ERR(REG_ESPACE); - return v->cv; + return v->cv; } /* * freecvec - free a cvec */ static void -freecvec(struct cvec *cv) +freecvec(struct cvec * cv) { - FREE(cv); + FREE(cv); } diff --git a/src/backend/regex/regc_lex.c b/src/backend/regex/regc_lex.c index 2f1a5840ff..2407e06ef4 100644 --- a/src/backend/regex/regc_lex.c +++ b/src/backend/regex/regc_lex.c @@ -2,21 +2,21 @@ * lexical analyzer * This file is #included by regcomp.c. * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -28,159 +28,168 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regc_lex.c,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regc_lex.c,v 1.2 2003/08/04 00:43:21 momjian Exp $ * */ /* scanning macros (know about v) */ -#define ATEOS() (v->now >= v->stop) -#define HAVE(n) (v->stop - v->now >= (n)) -#define NEXT1(c) (!ATEOS() && *v->now == CHR(c)) -#define NEXT2(a,b) (HAVE(2) && *v->now == CHR(a) && *(v->now+1) == CHR(b)) -#define NEXT3(a,b,c) (HAVE(3) && *v->now == CHR(a) && \ +#define ATEOS() (v->now >= v->stop) +#define HAVE(n) (v->stop - v->now >= (n)) +#define NEXT1(c) (!ATEOS() && *v->now == CHR(c)) +#define NEXT2(a,b) (HAVE(2) && *v->now == CHR(a) && *(v->now+1) == CHR(b)) +#define NEXT3(a,b,c) (HAVE(3) && *v->now == CHR(a) && \ *(v->now+1) == CHR(b) && \ *(v->now+2) == CHR(c)) -#define SET(c) (v->nexttype = (c)) -#define SETV(c, n) (v->nexttype = (c), v->nextvalue = (n)) -#define RET(c) return (SET(c), 1) -#define RETV(c, n) return (SETV(c, n), 1) -#define FAILW(e) return (ERR(e), 0) /* ERR does SET(EOS) */ -#define LASTTYPE(t) (v->lasttype == (t)) +#define SET(c) (v->nexttype = (c)) +#define SETV(c, n) (v->nexttype = (c), v->nextvalue = (n)) +#define RET(c) return (SET(c), 1) +#define RETV(c, n) return (SETV(c, n), 1) +#define FAILW(e) return (ERR(e), 0) /* ERR does SET(EOS) */ +#define LASTTYPE(t) (v->lasttype == (t)) /* lexical contexts */ -#define L_ERE 1 /* mainline ERE/ARE */ -#define L_BRE 2 /* mainline BRE */ -#define L_Q 3 /* REG_QUOTE */ -#define L_EBND 4 /* ERE/ARE bound */ -#define L_BBND 5 /* BRE bound */ -#define L_BRACK 6 /* brackets */ -#define L_CEL 7 /* collating element */ -#define L_ECL 8 /* equivalence class */ -#define L_CCL 9 /* character class */ -#define INTOCON(c) (v->lexcon = (c)) -#define INCON(con) (v->lexcon == (con)) +#define L_ERE 1 /* mainline ERE/ARE */ +#define L_BRE 2 /* mainline BRE */ +#define L_Q 3 /* REG_QUOTE */ +#define L_EBND 4 /* ERE/ARE bound */ +#define L_BBND 5 /* BRE bound */ +#define L_BRACK 6 /* brackets */ +#define L_CEL 7 /* collating element */ +#define L_ECL 8 /* equivalence class */ +#define L_CCL 9 /* character class */ +#define INTOCON(c) (v->lexcon = (c)) +#define INCON(con) (v->lexcon == (con)) /* construct pointer past end of chr array */ -#define ENDOF(array) ((array) + sizeof(array)/sizeof(chr)) +#define ENDOF(array) ((array) + sizeof(array)/sizeof(chr)) /* * lexstart - set up lexical stuff, scan leading options */ static void -lexstart(struct vars *v) +lexstart(struct vars * v) { - prefixes(v); /* may turn on new type bits etc. */ + prefixes(v); /* may turn on new type bits etc. */ NOERR(); - if (v->cflags®_QUOTE) { - assert(!(v->cflags&(REG_ADVANCED|REG_EXPANDED|REG_NEWLINE))); + if (v->cflags & REG_QUOTE) + { + assert(!(v->cflags & (REG_ADVANCED | REG_EXPANDED | REG_NEWLINE))); INTOCON(L_Q); - } else if (v->cflags®_EXTENDED) { - assert(!(v->cflags®_QUOTE)); + } + else if (v->cflags & REG_EXTENDED) + { + assert(!(v->cflags & REG_QUOTE)); INTOCON(L_ERE); - } else { - assert(!(v->cflags&(REG_QUOTE|REG_ADVF))); + } + else + { + assert(!(v->cflags & (REG_QUOTE | REG_ADVF))); INTOCON(L_BRE); } v->nexttype = EMPTY; /* remember we were at the start */ - next(v); /* set up the first token */ + next(v); /* set up the first token */ } /* * prefixes - implement various special prefixes */ static void -prefixes(struct vars *v) +prefixes(struct vars * v) { /* literal string doesn't get any of this stuff */ - if (v->cflags®_QUOTE) + if (v->cflags & REG_QUOTE) return; - /* initial "***" gets special things */ + /* initial "***" gets special things */ if (HAVE(4) && NEXT3('*', '*', '*')) - switch (*(v->now + 3)) { - case CHR('?'): /* "***?" error, msg shows version */ - ERR(REG_BADPAT); - return; /* proceed no further */ - break; - case CHR('='): /* "***=" shifts to literal string */ - NOTE(REG_UNONPOSIX); - v->cflags |= REG_QUOTE; - v->cflags &= ~(REG_ADVANCED|REG_EXPANDED|REG_NEWLINE); - v->now += 4; - return; /* and there can be no more prefixes */ - break; - case CHR(':'): /* "***:" shifts to AREs */ - NOTE(REG_UNONPOSIX); - v->cflags |= REG_ADVANCED; - v->now += 4; - break; - default: /* otherwise *** is just an error */ - ERR(REG_BADRPT); - return; - break; + switch (*(v->now + 3)) + { + case CHR('?'): /* "***?" error, msg shows version */ + ERR(REG_BADPAT); + return; /* proceed no further */ + break; + case CHR('='): /* "***=" shifts to literal string */ + NOTE(REG_UNONPOSIX); + v->cflags |= REG_QUOTE; + v->cflags &= ~(REG_ADVANCED | REG_EXPANDED | REG_NEWLINE); + v->now += 4; + return; /* and there can be no more prefixes */ + break; + case CHR(':'): /* "***:" shifts to AREs */ + NOTE(REG_UNONPOSIX); + v->cflags |= REG_ADVANCED; + v->now += 4; + break; + default: /* otherwise *** is just an error */ + ERR(REG_BADRPT); + return; + break; } /* BREs and EREs don't get embedded options */ - if ((v->cflags®_ADVANCED) != REG_ADVANCED) + if ((v->cflags & REG_ADVANCED) != REG_ADVANCED) return; /* embedded options (AREs only) */ - if (HAVE(3) && NEXT2('(', '?') && iscalpha(*(v->now + 2))) { + if (HAVE(3) && NEXT2('(', '?') && iscalpha(*(v->now + 2))) + { NOTE(REG_UNONPOSIX); v->now += 2; for (; !ATEOS() && iscalpha(*v->now); v->now++) - switch (*v->now) { - case CHR('b'): /* BREs (but why???) */ - v->cflags &= ~(REG_ADVANCED|REG_QUOTE); - break; - case CHR('c'): /* case sensitive */ - v->cflags &= ~REG_ICASE; - break; - case CHR('e'): /* plain EREs */ - v->cflags |= REG_EXTENDED; - v->cflags &= ~(REG_ADVF|REG_QUOTE); - break; - case CHR('i'): /* case insensitive */ - v->cflags |= REG_ICASE; - break; - case CHR('m'): /* Perloid synonym for n */ - case CHR('n'): /* \n affects ^ $ . [^ */ - v->cflags |= REG_NEWLINE; - break; - case CHR('p'): /* ~Perl, \n affects . [^ */ - v->cflags |= REG_NLSTOP; - v->cflags &= ~REG_NLANCH; - break; - case CHR('q'): /* literal string */ - v->cflags |= REG_QUOTE; - v->cflags &= ~REG_ADVANCED; - break; - case CHR('s'): /* single line, \n ordinary */ - v->cflags &= ~REG_NEWLINE; - break; - case CHR('t'): /* tight syntax */ - v->cflags &= ~REG_EXPANDED; - break; - case CHR('w'): /* weird, \n affects ^ $ only */ - v->cflags &= ~REG_NLSTOP; - v->cflags |= REG_NLANCH; - break; - case CHR('x'): /* expanded syntax */ - v->cflags |= REG_EXPANDED; - break; - default: - ERR(REG_BADOPT); - return; + switch (*v->now) + { + case CHR('b'): /* BREs (but why???) */ + v->cflags &= ~(REG_ADVANCED | REG_QUOTE); + break; + case CHR('c'): /* case sensitive */ + v->cflags &= ~REG_ICASE; + break; + case CHR('e'): /* plain EREs */ + v->cflags |= REG_EXTENDED; + v->cflags &= ~(REG_ADVF | REG_QUOTE); + break; + case CHR('i'): /* case insensitive */ + v->cflags |= REG_ICASE; + break; + case CHR('m'): /* Perloid synonym for n */ + case CHR('n'): /* \n affects ^ $ . [^ */ + v->cflags |= REG_NEWLINE; + break; + case CHR('p'): /* ~Perl, \n affects . [^ */ + v->cflags |= REG_NLSTOP; + v->cflags &= ~REG_NLANCH; + break; + case CHR('q'): /* literal string */ + v->cflags |= REG_QUOTE; + v->cflags &= ~REG_ADVANCED; + break; + case CHR('s'): /* single line, \n ordinary */ + v->cflags &= ~REG_NEWLINE; + break; + case CHR('t'): /* tight syntax */ + v->cflags &= ~REG_EXPANDED; + break; + case CHR('w'): /* weird, \n affects ^ $ only */ + v->cflags &= ~REG_NLSTOP; + v->cflags |= REG_NLANCH; + break; + case CHR('x'): /* expanded syntax */ + v->cflags |= REG_EXPANDED; + break; + default: + ERR(REG_BADOPT); + return; } - if (!NEXT1(')')) { + if (!NEXT1(')')) + { ERR(REG_BADOPT); return; } v->now++; - if (v->cflags®_QUOTE) - v->cflags &= ~(REG_EXPANDED|REG_NEWLINE); + if (v->cflags & REG_QUOTE) + v->cflags &= ~(REG_EXPANDED | REG_NEWLINE); } } @@ -191,11 +200,11 @@ prefixes(struct vars *v) * implicit assumptions about what sorts of strings can be subroutines. */ static void -lexnest(struct vars *v, - chr *beginp, /* start of interpolation */ - chr *endp) /* one past end of interpolation */ +lexnest(struct vars * v, + chr * beginp, /* start of interpolation */ + chr * endp) /* one past end of interpolation */ { - assert(v->savenow == NULL); /* only one level of nesting */ + assert(v->savenow == NULL); /* only one level of nesting */ v->savenow = v->now; v->savestop = v->stop; v->now = beginp; @@ -205,47 +214,47 @@ lexnest(struct vars *v, /* * string constants to interpolate as expansions of things like \d */ -static chr backd[] = { /* \d */ +static chr backd[] = { /* \d */ CHR('['), CHR('['), CHR(':'), CHR('d'), CHR('i'), CHR('g'), CHR('i'), CHR('t'), CHR(':'), CHR(']'), CHR(']') }; -static chr backD[] = { /* \D */ +static chr backD[] = { /* \D */ CHR('['), CHR('^'), CHR('['), CHR(':'), CHR('d'), CHR('i'), CHR('g'), CHR('i'), CHR('t'), CHR(':'), CHR(']'), CHR(']') }; -static chr brbackd[] = { /* \d within brackets */ +static chr brbackd[] = { /* \d within brackets */ CHR('['), CHR(':'), CHR('d'), CHR('i'), CHR('g'), CHR('i'), CHR('t'), CHR(':'), CHR(']') }; -static chr backs[] = { /* \s */ +static chr backs[] = { /* \s */ CHR('['), CHR('['), CHR(':'), CHR('s'), CHR('p'), CHR('a'), CHR('c'), CHR('e'), CHR(':'), CHR(']'), CHR(']') }; -static chr backS[] = { /* \S */ +static chr backS[] = { /* \S */ CHR('['), CHR('^'), CHR('['), CHR(':'), CHR('s'), CHR('p'), CHR('a'), CHR('c'), CHR('e'), CHR(':'), CHR(']'), CHR(']') }; -static chr brbacks[] = { /* \s within brackets */ +static chr brbacks[] = { /* \s within brackets */ CHR('['), CHR(':'), CHR('s'), CHR('p'), CHR('a'), CHR('c'), CHR('e'), CHR(':'), CHR(']') }; -static chr backw[] = { /* \w */ +static chr backw[] = { /* \w */ CHR('['), CHR('['), CHR(':'), CHR('a'), CHR('l'), CHR('n'), CHR('u'), CHR('m'), CHR(':'), CHR(']'), CHR('_'), CHR(']') }; -static chr backW[] = { /* \W */ +static chr backW[] = { /* \W */ CHR('['), CHR('^'), CHR('['), CHR(':'), CHR('a'), CHR('l'), CHR('n'), CHR('u'), CHR('m'), CHR(':'), CHR(']'), CHR('_'), CHR(']') }; -static chr brbackw[] = { /* \w within brackets */ +static chr brbackw[] = { /* \w within brackets */ CHR('['), CHR(':'), CHR('a'), CHR('l'), CHR('n'), CHR('u'), CHR('m'), CHR(':'), CHR(']'), CHR('_') @@ -256,7 +265,7 @@ static chr brbackw[] = { /* \w within brackets */ * Possibly ought to inquire whether there is a "word" character class. */ static void -lexword(struct vars *v) +lexword(struct vars * v) { lexnest(v, backw, ENDOF(backw)); } @@ -264,60 +273,65 @@ lexword(struct vars *v) /* * next - get next token */ -static int /* 1 normal, 0 failure */ -next(struct vars *v) +static int /* 1 normal, 0 failure */ +next(struct vars * v) { - chr c; + chr c; /* errors yield an infinite sequence of failures */ if (ISERR()) - return 0; /* the error has set nexttype to EOS */ + return 0; /* the error has set nexttype to EOS */ /* remember flavor of last token */ v->lasttype = v->nexttype; /* REG_BOSONLY */ - if (v->nexttype == EMPTY && (v->cflags®_BOSONLY)) { + if (v->nexttype == EMPTY && (v->cflags & REG_BOSONLY)) + { /* at start of a REG_BOSONLY RE */ RETV(SBEGIN, 0); /* same as \A */ } /* if we're nested and we've hit end, return to outer level */ - if (v->savenow != NULL && ATEOS()) { + if (v->savenow != NULL && ATEOS()) + { v->now = v->savenow; v->stop = v->savestop; v->savenow = v->savestop = NULL; } /* skip white space etc. if appropriate (not in literal or []) */ - if (v->cflags®_EXPANDED) - switch (v->lexcon) { - case L_ERE: - case L_BRE: - case L_EBND: - case L_BBND: - skip(v); - break; + if (v->cflags & REG_EXPANDED) + switch (v->lexcon) + { + case L_ERE: + case L_BRE: + case L_EBND: + case L_BBND: + skip(v); + break; } /* handle EOS, depending on context */ - if (ATEOS()) { - switch (v->lexcon) { - case L_ERE: - case L_BRE: - case L_Q: - RET(EOS); - break; - case L_EBND: - case L_BBND: - FAILW(REG_EBRACE); - break; - case L_BRACK: - case L_CEL: - case L_ECL: - case L_CCL: - FAILW(REG_EBRACK); - break; + if (ATEOS()) + { + switch (v->lexcon) + { + case L_ERE: + case L_BRE: + case L_Q: + RET(EOS); + break; + case L_EBND: + case L_BBND: + FAILW(REG_EBRACE); + break; + case L_BRACK: + case L_CEL: + case L_ECL: + case L_CCL: + FAILW(REG_EBRACK); + break; } assert(NOTREACHED); } @@ -326,314 +340,365 @@ next(struct vars *v) c = *v->now++; /* deal with the easy contexts, punt EREs to code below */ - switch (v->lexcon) { - case L_BRE: /* punt BREs to separate function */ - return brenext(v, c); - break; - case L_ERE: /* see below */ - break; - case L_Q: /* literal strings are easy */ - RETV(PLAIN, c); - break; - case L_BBND: /* bounds are fairly simple */ - case L_EBND: - switch (c) { - case CHR('0'): case CHR('1'): case CHR('2'): case CHR('3'): - case CHR('4'): case CHR('5'): case CHR('6'): case CHR('7'): - case CHR('8'): case CHR('9'): - RETV(DIGIT, (chr)DIGITVAL(c)); + switch (v->lexcon) + { + case L_BRE: /* punt BREs to separate function */ + return brenext(v, c); break; - case CHR(','): - RET(','); + case L_ERE: /* see below */ break; - case CHR('}'): /* ERE bound ends with } */ - if (INCON(L_EBND)) { - INTOCON(L_ERE); - if ((v->cflags®_ADVF) && NEXT1('?')) { - v->now++; - NOTE(REG_UNONPOSIX); - RETV('}', 0); - } - RETV('}', 1); - } else - FAILW(REG_BADBR); + case L_Q: /* literal strings are easy */ + RETV(PLAIN, c); break; - case CHR('\\'): /* BRE bound ends with \} */ - if (INCON(L_BBND) && NEXT1('}')) { - v->now++; - INTOCON(L_BRE); - RET('}'); - } else - FAILW(REG_BADBR); - break; - default: - FAILW(REG_BADBR); - break; - } - assert(NOTREACHED); - break; - case L_BRACK: /* brackets are not too hard */ - switch (c) { - case CHR(']'): - if (LASTTYPE('[')) - RETV(PLAIN, c); - else { - INTOCON((v->cflags®_EXTENDED) ? - L_ERE : L_BRE); - RET(']'); - } - break; - case CHR('\\'): - NOTE(REG_UBBS); - if (!(v->cflags®_ADVF)) - RETV(PLAIN, c); - NOTE(REG_UNONPOSIX); - if (ATEOS()) - FAILW(REG_EESCAPE); - (DISCARD)lexescape(v); - switch (v->nexttype) { /* not all escapes okay here */ - case PLAIN: - return 1; - break; - case CCLASS: - switch (v->nextvalue) { - case 'd': - lexnest(v, brbackd, ENDOF(brbackd)); + case L_BBND: /* bounds are fairly simple */ + case L_EBND: + switch (c) + { + case CHR('0'): + case CHR('1'): + case CHR('2'): + case CHR('3'): + case CHR('4'): + case CHR('5'): + case CHR('6'): + case CHR('7'): + case CHR('8'): + case CHR('9'): + RETV(DIGIT, (chr) DIGITVAL(c)); break; - case 's': - lexnest(v, brbacks, ENDOF(brbacks)); + case CHR(','): + RET(','); break; - case 'w': - lexnest(v, brbackw, ENDOF(brbackw)); + case CHR('}'): /* ERE bound ends with } */ + if (INCON(L_EBND)) + { + INTOCON(L_ERE); + if ((v->cflags & REG_ADVF) && NEXT1('?')) + { + v->now++; + NOTE(REG_UNONPOSIX); + RETV('}', 0); + } + RETV('}', 1); + } + else + FAILW(REG_BADBR); + break; + case CHR('\\'): /* BRE bound ends with \} */ + if (INCON(L_BBND) && NEXT1('}')) + { + v->now++; + INTOCON(L_BRE); + RET('}'); + } + else + FAILW(REG_BADBR); break; default: - FAILW(REG_EESCAPE); + FAILW(REG_BADBR); break; - } - /* lexnest done, back up and try again */ - v->nexttype = v->lasttype; - return next(v); - break; - } - /* not one of the acceptable escapes */ - FAILW(REG_EESCAPE); - break; - case CHR('-'): - if (LASTTYPE('[') || NEXT1(']')) - RETV(PLAIN, c); - else - RETV(RANGE, c); - break; - case CHR('['): - if (ATEOS()) - FAILW(REG_EBRACK); - switch (*v->now++) { - case CHR('.'): - INTOCON(L_CEL); - /* might or might not be locale-specific */ - RET(COLLEL); - break; - case CHR('='): - INTOCON(L_ECL); - NOTE(REG_ULOCALE); - RET(ECLASS); - break; - case CHR(':'): - INTOCON(L_CCL); - NOTE(REG_ULOCALE); - RET(CCLASS); - break; - default: /* oops */ - v->now--; - RETV(PLAIN, c); - break; } assert(NOTREACHED); break; - default: - RETV(PLAIN, c); + case L_BRACK: /* brackets are not too hard */ + switch (c) + { + case CHR(']'): + if (LASTTYPE('[')) + RETV(PLAIN, c); + else + { + INTOCON((v->cflags & REG_EXTENDED) ? + L_ERE : L_BRE); + RET(']'); + } + break; + case CHR('\\'): + NOTE(REG_UBBS); + if (!(v->cflags & REG_ADVF)) + RETV(PLAIN, c); + NOTE(REG_UNONPOSIX); + if (ATEOS()) + FAILW(REG_EESCAPE); + (DISCARD) lexescape(v); + switch (v->nexttype) + { /* not all escapes okay here */ + case PLAIN: + return 1; + break; + case CCLASS: + switch (v->nextvalue) + { + case 'd': + lexnest(v, brbackd, ENDOF(brbackd)); + break; + case 's': + lexnest(v, brbacks, ENDOF(brbacks)); + break; + case 'w': + lexnest(v, brbackw, ENDOF(brbackw)); + break; + default: + FAILW(REG_EESCAPE); + break; + } + /* lexnest done, back up and try again */ + v->nexttype = v->lasttype; + return next(v); + break; + } + /* not one of the acceptable escapes */ + FAILW(REG_EESCAPE); + break; + case CHR('-'): + if (LASTTYPE('[') || NEXT1(']')) + RETV(PLAIN, c); + else + RETV(RANGE, c); + break; + case CHR('['): + if (ATEOS()) + FAILW(REG_EBRACK); + switch (*v->now++) + { + case CHR('.'): + INTOCON(L_CEL); + /* might or might not be locale-specific */ + RET(COLLEL); + break; + case CHR('='): + INTOCON(L_ECL); + NOTE(REG_ULOCALE); + RET(ECLASS); + break; + case CHR(':'): + INTOCON(L_CCL); + NOTE(REG_ULOCALE); + RET(CCLASS); + break; + default: /* oops */ + v->now--; + RETV(PLAIN, c); + break; + } + assert(NOTREACHED); + break; + default: + RETV(PLAIN, c); + break; + } + assert(NOTREACHED); + break; + case L_CEL: /* collating elements are easy */ + if (c == CHR('.') && NEXT1(']')) + { + v->now++; + INTOCON(L_BRACK); + RETV(END, '.'); + } + else + RETV(PLAIN, c); + break; + case L_ECL: /* ditto equivalence classes */ + if (c == CHR('=') && NEXT1(']')) + { + v->now++; + INTOCON(L_BRACK); + RETV(END, '='); + } + else + RETV(PLAIN, c); + break; + case L_CCL: /* ditto character classes */ + if (c == CHR(':') && NEXT1(']')) + { + v->now++; + INTOCON(L_BRACK); + RETV(END, ':'); + } + else + RETV(PLAIN, c); + break; + default: + assert(NOTREACHED); break; - } - assert(NOTREACHED); - break; - case L_CEL: /* collating elements are easy */ - if (c == CHR('.') && NEXT1(']')) { - v->now++; - INTOCON(L_BRACK); - RETV(END, '.'); - } else - RETV(PLAIN, c); - break; - case L_ECL: /* ditto equivalence classes */ - if (c == CHR('=') && NEXT1(']')) { - v->now++; - INTOCON(L_BRACK); - RETV(END, '='); - } else - RETV(PLAIN, c); - break; - case L_CCL: /* ditto character classes */ - if (c == CHR(':') && NEXT1(']')) { - v->now++; - INTOCON(L_BRACK); - RETV(END, ':'); - } else - RETV(PLAIN, c); - break; - default: - assert(NOTREACHED); - break; } /* that got rid of everything except EREs and AREs */ assert(INCON(L_ERE)); /* deal with EREs and AREs, except for backslashes */ - switch (c) { - case CHR('|'): - RET('|'); - break; - case CHR('*'): - if ((v->cflags®_ADVF) && NEXT1('?')) { - v->now++; - NOTE(REG_UNONPOSIX); - RETV('*', 0); - } - RETV('*', 1); - break; - case CHR('+'): - if ((v->cflags®_ADVF) && NEXT1('?')) { - v->now++; - NOTE(REG_UNONPOSIX); - RETV('+', 0); - } - RETV('+', 1); - break; - case CHR('?'): - if ((v->cflags®_ADVF) && NEXT1('?')) { - v->now++; - NOTE(REG_UNONPOSIX); - RETV('?', 0); - } - RETV('?', 1); - break; - case CHR('{'): /* bounds start or plain character */ - if (v->cflags®_EXPANDED) - skip(v); - if (ATEOS() || !iscdigit(*v->now)) { - NOTE(REG_UBRACES); - NOTE(REG_UUNSPEC); - RETV(PLAIN, c); - } else { - NOTE(REG_UBOUNDS); - INTOCON(L_EBND); - RET('{'); - } - assert(NOTREACHED); - break; - case CHR('('): /* parenthesis, or advanced extension */ - if ((v->cflags®_ADVF) && NEXT1('?')) { - NOTE(REG_UNONPOSIX); - v->now++; - switch (*v->now++) { - case CHR(':'): /* non-capturing paren */ - RETV('(', 0); - break; - case CHR('#'): /* comment */ - while (!ATEOS() && *v->now != CHR(')')) - v->now++; - if (!ATEOS()) - v->now++; - assert(v->nexttype == v->lasttype); - return next(v); - break; - case CHR('='): /* positive lookahead */ - NOTE(REG_ULOOKAHEAD); - RETV(LACON, 1); - break; - case CHR('!'): /* negative lookahead */ - NOTE(REG_ULOOKAHEAD); - RETV(LACON, 0); - break; - default: - FAILW(REG_BADRPT); - break; + switch (c) + { + case CHR('|'): + RET('|'); + break; + case CHR('*'): + if ((v->cflags & REG_ADVF) && NEXT1('?')) + { + v->now++; + NOTE(REG_UNONPOSIX); + RETV('*', 0); + } + RETV('*', 1); + break; + case CHR('+'): + if ((v->cflags & REG_ADVF) && NEXT1('?')) + { + v->now++; + NOTE(REG_UNONPOSIX); + RETV('+', 0); + } + RETV('+', 1); + break; + case CHR('?'): + if ((v->cflags & REG_ADVF) && NEXT1('?')) + { + v->now++; + NOTE(REG_UNONPOSIX); + RETV('?', 0); + } + RETV('?', 1); + break; + case CHR('{'): /* bounds start or plain character */ + if (v->cflags & REG_EXPANDED) + skip(v); + if (ATEOS() || !iscdigit(*v->now)) + { + NOTE(REG_UBRACES); + NOTE(REG_UUNSPEC); + RETV(PLAIN, c); + } + else + { + NOTE(REG_UBOUNDS); + INTOCON(L_EBND); + RET('{'); } assert(NOTREACHED); - } - if (v->cflags®_NOSUB) - RETV('(', 0); /* all parens non-capturing */ - else - RETV('(', 1); - break; - case CHR(')'): - if (LASTTYPE('(')) { - NOTE(REG_UUNSPEC); - } - RETV(')', c); - break; - case CHR('['): /* easy except for [[:<:]] and [[:>:]] */ - if (HAVE(6) && *(v->now+0) == CHR('[') && - *(v->now+1) == CHR(':') && - (*(v->now+2) == CHR('<') || - *(v->now+2) == CHR('>')) && - *(v->now+3) == CHR(':') && - *(v->now+4) == CHR(']') && - *(v->now+5) == CHR(']')) { - c = *(v->now+2); - v->now += 6; - NOTE(REG_UNONPOSIX); - RET((c == CHR('<')) ? '<' : '>'); - } - INTOCON(L_BRACK); - if (NEXT1('^')) { - v->now++; - RETV('[', 0); - } - RETV('[', 1); - break; - case CHR('.'): - RET('.'); - break; - case CHR('^'): - RET('^'); - break; - case CHR('$'): - RET('$'); - break; - case CHR('\\'): /* mostly punt backslashes to code below */ - if (ATEOS()) - FAILW(REG_EESCAPE); - break; - default: /* ordinary character */ - RETV(PLAIN, c); - break; + break; + case CHR('('): /* parenthesis, or advanced extension */ + if ((v->cflags & REG_ADVF) && NEXT1('?')) + { + NOTE(REG_UNONPOSIX); + v->now++; + switch (*v->now++) + { + case CHR(':'): /* non-capturing paren */ + RETV('(', 0); + break; + case CHR('#'): /* comment */ + while (!ATEOS() && *v->now != CHR(')')) + v->now++; + if (!ATEOS()) + v->now++; + assert(v->nexttype == v->lasttype); + return next(v); + break; + case CHR('='): /* positive lookahead */ + NOTE(REG_ULOOKAHEAD); + RETV(LACON, 1); + break; + case CHR('!'): /* negative lookahead */ + NOTE(REG_ULOOKAHEAD); + RETV(LACON, 0); + break; + default: + FAILW(REG_BADRPT); + break; + } + assert(NOTREACHED); + } + if (v->cflags & REG_NOSUB) + RETV('(', 0); /* all parens non-capturing */ + else + RETV('(', 1); + break; + case CHR(')'): + if (LASTTYPE('(')) + NOTE(REG_UUNSPEC); + RETV(')', c); + break; + case CHR('['): /* easy except for [[:<:]] and [[:>:]] */ + if (HAVE(6) && *(v->now + 0) == CHR('[') && + *(v->now + 1) == CHR(':') && + (*(v->now + 2) == CHR('<') || + *(v->now + 2) == CHR('>')) && + *(v->now + 3) == CHR(':') && + *(v->now + 4) == CHR(']') && + *(v->now + 5) == CHR(']')) + { + c = *(v->now + 2); + v->now += 6; + NOTE(REG_UNONPOSIX); + RET((c == CHR('<')) ? '<' : '>'); + } + INTOCON(L_BRACK); + if (NEXT1('^')) + { + v->now++; + RETV('[', 0); + } + RETV('[', 1); + break; + case CHR('.'): + RET('.'); + break; + case CHR('^'): + RET('^'); + break; + case CHR('$'): + RET('$'); + break; + case CHR('\\'): /* mostly punt backslashes to code below */ + if (ATEOS()) + FAILW(REG_EESCAPE); + break; + default: /* ordinary character */ + RETV(PLAIN, c); + break; } /* ERE/ARE backslash handling; backslash already eaten */ assert(!ATEOS()); - if (!(v->cflags®_ADVF)) { /* only AREs have non-trivial escapes */ - if (iscalnum(*v->now)) { + if (!(v->cflags & REG_ADVF)) + { /* only AREs have non-trivial escapes */ + if (iscalnum(*v->now)) + { NOTE(REG_UBSALNUM); NOTE(REG_UUNSPEC); } RETV(PLAIN, *v->now++); } - (DISCARD)lexescape(v); + (DISCARD) lexescape(v); if (ISERR()) FAILW(REG_EESCAPE); - if (v->nexttype == CCLASS) { /* fudge at lexical level */ - switch (v->nextvalue) { - case 'd': lexnest(v, backd, ENDOF(backd)); break; - case 'D': lexnest(v, backD, ENDOF(backD)); break; - case 's': lexnest(v, backs, ENDOF(backs)); break; - case 'S': lexnest(v, backS, ENDOF(backS)); break; - case 'w': lexnest(v, backw, ENDOF(backw)); break; - case 'W': lexnest(v, backW, ENDOF(backW)); break; - default: - assert(NOTREACHED); - FAILW(REG_ASSERT); - break; + if (v->nexttype == CCLASS) + { /* fudge at lexical level */ + switch (v->nextvalue) + { + case 'd': + lexnest(v, backd, ENDOF(backd)); + break; + case 'D': + lexnest(v, backD, ENDOF(backD)); + break; + case 's': + lexnest(v, backs, ENDOF(backs)); + break; + case 'S': + lexnest(v, backS, ENDOF(backS)); + break; + case 'w': + lexnest(v, backw, ENDOF(backw)); + break; + case 'W': + lexnest(v, backW, ENDOF(backW)); + break; + default: + assert(NOTREACHED); + FAILW(REG_ASSERT); + break; } /* lexnest done, back up and try again */ v->nexttype = v->lasttype; @@ -647,19 +712,20 @@ next(struct vars *v) * lexescape - parse an ARE backslash escape (backslash already eaten) * Note slightly nonstandard use of the CCLASS type code. */ -static int /* not actually used, but convenient for RETV */ -lexescape(struct vars *v) +static int /* not actually used, but convenient for + * RETV */ +lexescape(struct vars * v) { - chr c; - static chr alert[] = { + chr c; + static chr alert[] = { CHR('a'), CHR('l'), CHR('e'), CHR('r'), CHR('t') }; - static chr esc[] = { + static chr esc[] = { CHR('E'), CHR('S'), CHR('C') }; - chr *save; + chr *save; - assert(v->cflags®_ADVF); + assert(v->cflags & REG_ADVF); assert(!ATEOS()); c = *v->now++; @@ -667,132 +733,142 @@ lexescape(struct vars *v) RETV(PLAIN, c); NOTE(REG_UNONPOSIX); - switch (c) { - case CHR('a'): - RETV(PLAIN, chrnamed(v, alert, ENDOF(alert), CHR('\007'))); - break; - case CHR('A'): - RETV(SBEGIN, 0); - break; - case CHR('b'): - RETV(PLAIN, CHR('\b')); - break; - case CHR('B'): - RETV(PLAIN, CHR('\\')); - break; - case CHR('c'): - NOTE(REG_UUNPORT); - if (ATEOS()) - FAILW(REG_EESCAPE); - RETV(PLAIN, (chr)(*v->now++ & 037)); - break; - case CHR('d'): - NOTE(REG_ULOCALE); - RETV(CCLASS, 'd'); - break; - case CHR('D'): - NOTE(REG_ULOCALE); - RETV(CCLASS, 'D'); - break; - case CHR('e'): - NOTE(REG_UUNPORT); - RETV(PLAIN, chrnamed(v, esc, ENDOF(esc), CHR('\033'))); - break; - case CHR('f'): - RETV(PLAIN, CHR('\f')); - break; - case CHR('m'): - RET('<'); - break; - case CHR('M'): - RET('>'); - break; - case CHR('n'): - RETV(PLAIN, CHR('\n')); - break; - case CHR('r'): - RETV(PLAIN, CHR('\r')); - break; - case CHR('s'): - NOTE(REG_ULOCALE); - RETV(CCLASS, 's'); - break; - case CHR('S'): - NOTE(REG_ULOCALE); - RETV(CCLASS, 'S'); - break; - case CHR('t'): - RETV(PLAIN, CHR('\t')); - break; - case CHR('u'): - c = lexdigits(v, 16, 4, 4); - if (ISERR()) - FAILW(REG_EESCAPE); - RETV(PLAIN, c); - break; - case CHR('U'): - c = lexdigits(v, 16, 8, 8); - if (ISERR()) - FAILW(REG_EESCAPE); - RETV(PLAIN, c); - break; - case CHR('v'): - RETV(PLAIN, CHR('\v')); - break; - case CHR('w'): - NOTE(REG_ULOCALE); - RETV(CCLASS, 'w'); - break; - case CHR('W'): - NOTE(REG_ULOCALE); - RETV(CCLASS, 'W'); - break; - case CHR('x'): - NOTE(REG_UUNPORT); - c = lexdigits(v, 16, 1, 255); /* REs >255 long outside spec */ - if (ISERR()) - FAILW(REG_EESCAPE); - RETV(PLAIN, c); - break; - case CHR('y'): - NOTE(REG_ULOCALE); - RETV(WBDRY, 0); - break; - case CHR('Y'): - NOTE(REG_ULOCALE); - RETV(NWBDRY, 0); - break; - case CHR('Z'): - RETV(SEND, 0); - break; - case CHR('1'): case CHR('2'): case CHR('3'): case CHR('4'): - case CHR('5'): case CHR('6'): case CHR('7'): case CHR('8'): - case CHR('9'): - save = v->now; - v->now--; /* put first digit back */ - c = lexdigits(v, 10, 1, 255); /* REs >255 long outside spec */ - if (ISERR()) - FAILW(REG_EESCAPE); - /* ugly heuristic (first test is "exactly 1 digit?") */ - if (v->now - save == 0 || (int)c <= v->nsubexp) { - NOTE(REG_UBACKREF); - RETV(BACKREF, (chr)c); - } - /* oops, doesn't look like it's a backref after all... */ - v->now = save; - /* and fall through into octal number */ - case CHR('0'): - NOTE(REG_UUNPORT); - v->now--; /* put first digit back */ - c = lexdigits(v, 8, 1, 3); - if (ISERR()) - FAILW(REG_EESCAPE); - RETV(PLAIN, c); - break; - default: - assert(iscalpha(c)); - FAILW(REG_EESCAPE); /* unknown alphabetic escape */ - break; + switch (c) + { + case CHR('a'): + RETV(PLAIN, chrnamed(v, alert, ENDOF(alert), CHR('\007'))); + break; + case CHR('A'): + RETV(SBEGIN, 0); + break; + case CHR('b'): + RETV(PLAIN, CHR('\b')); + break; + case CHR('B'): + RETV(PLAIN, CHR('\\')); + break; + case CHR('c'): + NOTE(REG_UUNPORT); + if (ATEOS()) + FAILW(REG_EESCAPE); + RETV(PLAIN, (chr) (*v->now++ & 037)); + break; + case CHR('d'): + NOTE(REG_ULOCALE); + RETV(CCLASS, 'd'); + break; + case CHR('D'): + NOTE(REG_ULOCALE); + RETV(CCLASS, 'D'); + break; + case CHR('e'): + NOTE(REG_UUNPORT); + RETV(PLAIN, chrnamed(v, esc, ENDOF(esc), CHR('\033'))); + break; + case CHR('f'): + RETV(PLAIN, CHR('\f')); + break; + case CHR('m'): + RET('<'); + break; + case CHR('M'): + RET('>'); + break; + case CHR('n'): + RETV(PLAIN, CHR('\n')); + break; + case CHR('r'): + RETV(PLAIN, CHR('\r')); + break; + case CHR('s'): + NOTE(REG_ULOCALE); + RETV(CCLASS, 's'); + break; + case CHR('S'): + NOTE(REG_ULOCALE); + RETV(CCLASS, 'S'); + break; + case CHR('t'): + RETV(PLAIN, CHR('\t')); + break; + case CHR('u'): + c = lexdigits(v, 16, 4, 4); + if (ISERR()) + FAILW(REG_EESCAPE); + RETV(PLAIN, c); + break; + case CHR('U'): + c = lexdigits(v, 16, 8, 8); + if (ISERR()) + FAILW(REG_EESCAPE); + RETV(PLAIN, c); + break; + case CHR('v'): + RETV(PLAIN, CHR('\v')); + break; + case CHR('w'): + NOTE(REG_ULOCALE); + RETV(CCLASS, 'w'); + break; + case CHR('W'): + NOTE(REG_ULOCALE); + RETV(CCLASS, 'W'); + break; + case CHR('x'): + NOTE(REG_UUNPORT); + c = lexdigits(v, 16, 1, 255); /* REs >255 long outside + * spec */ + if (ISERR()) + FAILW(REG_EESCAPE); + RETV(PLAIN, c); + break; + case CHR('y'): + NOTE(REG_ULOCALE); + RETV(WBDRY, 0); + break; + case CHR('Y'): + NOTE(REG_ULOCALE); + RETV(NWBDRY, 0); + break; + case CHR('Z'): + RETV(SEND, 0); + break; + case CHR('1'): + case CHR('2'): + case CHR('3'): + case CHR('4'): + case CHR('5'): + case CHR('6'): + case CHR('7'): + case CHR('8'): + case CHR('9'): + save = v->now; + v->now--; /* put first digit back */ + c = lexdigits(v, 10, 1, 255); /* REs >255 long outside + * spec */ + if (ISERR()) + FAILW(REG_EESCAPE); + /* ugly heuristic (first test is "exactly 1 digit?") */ + if (v->now - save == 0 || (int) c <= v->nsubexp) + { + NOTE(REG_UBACKREF); + RETV(BACKREF, (chr) c); + } + /* oops, doesn't look like it's a backref after all... */ + v->now = save; + /* and fall through into octal number */ + case CHR('0'): + NOTE(REG_UUNPORT); + v->now--; /* put first digit back */ + c = lexdigits(v, 8, 1, 3); + if (ISERR()) + FAILW(REG_EESCAPE); + RETV(PLAIN, c); + break; + default: + assert(iscalpha(c)); + FAILW(REG_EESCAPE); /* unknown alphabetic escape */ + break; } assert(NOTREACHED); } @@ -800,51 +876,79 @@ lexescape(struct vars *v) /* * lexdigits - slurp up digits and return chr value */ -static chr /* chr value; errors signalled via ERR */ -lexdigits(struct vars *v, +static chr /* chr value; errors signalled via ERR */ +lexdigits(struct vars * v, int base, int minlen, int maxlen) { - uchr n; /* unsigned to avoid overflow misbehavior */ - int len; - chr c; - int d; - const uchr ub = (uchr) base; + uchr n; /* unsigned to avoid overflow misbehavior */ + int len; + chr c; + int d; + const uchr ub = (uchr) base; n = 0; - for (len = 0; len < maxlen && !ATEOS(); len++) { + for (len = 0; len < maxlen && !ATEOS(); len++) + { c = *v->now++; - switch (c) { - case CHR('0'): case CHR('1'): case CHR('2'): case CHR('3'): - case CHR('4'): case CHR('5'): case CHR('6'): case CHR('7'): - case CHR('8'): case CHR('9'): - d = DIGITVAL(c); - break; - case CHR('a'): case CHR('A'): d = 10; break; - case CHR('b'): case CHR('B'): d = 11; break; - case CHR('c'): case CHR('C'): d = 12; break; - case CHR('d'): case CHR('D'): d = 13; break; - case CHR('e'): case CHR('E'): d = 14; break; - case CHR('f'): case CHR('F'): d = 15; break; - default: - v->now--; /* oops, not a digit at all */ - d = -1; - break; + switch (c) + { + case CHR('0'): + case CHR('1'): + case CHR('2'): + case CHR('3'): + case CHR('4'): + case CHR('5'): + case CHR('6'): + case CHR('7'): + case CHR('8'): + case CHR('9'): + d = DIGITVAL(c); + break; + case CHR('a'): + case CHR('A'): + d = 10; + break; + case CHR('b'): + case CHR('B'): + d = 11; + break; + case CHR('c'): + case CHR('C'): + d = 12; + break; + case CHR('d'): + case CHR('D'): + d = 13; + break; + case CHR('e'): + case CHR('E'): + d = 14; + break; + case CHR('f'): + case CHR('F'): + d = 15; + break; + default: + v->now--; /* oops, not a digit at all */ + d = -1; + break; } - if (d >= base) { /* not a plausible digit */ + if (d >= base) + { /* not a plausible digit */ v->now--; d = -1; } if (d < 0) - break; /* NOTE BREAK OUT */ - n = n*ub + (uchr)d; + break; /* NOTE BREAK OUT */ + n = n * ub + (uchr) d; } if (len < minlen) ERR(REG_EESCAPE); - return (chr)n; + return (chr) n; } /* @@ -853,66 +957,71 @@ lexdigits(struct vars *v, * This is much like EREs except for all the stupid backslashes and the * context-dependency of some things. */ -static int /* 1 normal, 0 failure */ -brenext(struct vars *v, +static int /* 1 normal, 0 failure */ +brenext(struct vars * v, chr pc) { - chr c = (chr)pc; + chr c = (chr) pc; - switch (c) { - case CHR('*'): - if (LASTTYPE(EMPTY) || LASTTYPE('(') || LASTTYPE('^')) + switch (c) + { + case CHR('*'): + if (LASTTYPE(EMPTY) || LASTTYPE('(') || LASTTYPE('^')) + RETV(PLAIN, c); + RET('*'); + break; + case CHR('['): + if (HAVE(6) && *(v->now + 0) == CHR('[') && + *(v->now + 1) == CHR(':') && + (*(v->now + 2) == CHR('<') || + *(v->now + 2) == CHR('>')) && + *(v->now + 3) == CHR(':') && + *(v->now + 4) == CHR(']') && + *(v->now + 5) == CHR(']')) + { + c = *(v->now + 2); + v->now += 6; + NOTE(REG_UNONPOSIX); + RET((c == CHR('<')) ? '<' : '>'); + } + INTOCON(L_BRACK); + if (NEXT1('^')) + { + v->now++; + RETV('[', 0); + } + RETV('[', 1); + break; + case CHR('.'): + RET('.'); + break; + case CHR('^'): + if (LASTTYPE(EMPTY)) + RET('^'); + if (LASTTYPE('(')) + { + NOTE(REG_UUNSPEC); + RET('^'); + } RETV(PLAIN, c); - RET('*'); - break; - case CHR('['): - if (HAVE(6) && *(v->now+0) == CHR('[') && - *(v->now+1) == CHR(':') && - (*(v->now+2) == CHR('<') || - *(v->now+2) == CHR('>')) && - *(v->now+3) == CHR(':') && - *(v->now+4) == CHR(']') && - *(v->now+5) == CHR(']')) { - c = *(v->now+2); - v->now += 6; - NOTE(REG_UNONPOSIX); - RET((c == CHR('<')) ? '<' : '>'); - } - INTOCON(L_BRACK); - if (NEXT1('^')) { - v->now++; - RETV('[', 0); - } - RETV('[', 1); - break; - case CHR('.'): - RET('.'); - break; - case CHR('^'): - if (LASTTYPE(EMPTY)) - RET('^'); - if (LASTTYPE('(')) { - NOTE(REG_UUNSPEC); - RET('^'); - } - RETV(PLAIN, c); - break; - case CHR('$'): - if (v->cflags®_EXPANDED) - skip(v); - if (ATEOS()) - RET('$'); - if (NEXT2('\\', ')')) { - NOTE(REG_UUNSPEC); - RET('$'); - } - RETV(PLAIN, c); - break; - case CHR('\\'): - break; /* see below */ - default: - RETV(PLAIN, c); - break; + break; + case CHR('$'): + if (v->cflags & REG_EXPANDED) + skip(v); + if (ATEOS()) + RET('$'); + if (NEXT2('\\', ')')) + { + NOTE(REG_UUNSPEC); + RET('$'); + } + RETV(PLAIN, c); + break; + case CHR('\\'): + break; /* see below */ + default: + RETV(PLAIN, c); + break; } assert(c == CHR('\\')); @@ -921,39 +1030,47 @@ brenext(struct vars *v, FAILW(REG_EESCAPE); c = *v->now++; - switch (c) { - case CHR('{'): - INTOCON(L_BBND); - NOTE(REG_UBOUNDS); - RET('{'); - break; - case CHR('('): - RETV('(', 1); - break; - case CHR(')'): - RETV(')', c); - break; - case CHR('<'): - NOTE(REG_UNONPOSIX); - RET('<'); - break; - case CHR('>'): - NOTE(REG_UNONPOSIX); - RET('>'); - break; - case CHR('1'): case CHR('2'): case CHR('3'): case CHR('4'): - case CHR('5'): case CHR('6'): case CHR('7'): case CHR('8'): - case CHR('9'): - NOTE(REG_UBACKREF); - RETV(BACKREF, (chr)DIGITVAL(c)); - break; - default: - if (iscalnum(c)) { - NOTE(REG_UBSALNUM); - NOTE(REG_UUNSPEC); - } - RETV(PLAIN, c); - break; + switch (c) + { + case CHR('{'): + INTOCON(L_BBND); + NOTE(REG_UBOUNDS); + RET('{'); + break; + case CHR('('): + RETV('(', 1); + break; + case CHR(')'): + RETV(')', c); + break; + case CHR('<'): + NOTE(REG_UNONPOSIX); + RET('<'); + break; + case CHR('>'): + NOTE(REG_UNONPOSIX); + RET('>'); + break; + case CHR('1'): + case CHR('2'): + case CHR('3'): + case CHR('4'): + case CHR('5'): + case CHR('6'): + case CHR('7'): + case CHR('8'): + case CHR('9'): + NOTE(REG_UBACKREF); + RETV(BACKREF, (chr) DIGITVAL(c)); + break; + default: + if (iscalnum(c)) + { + NOTE(REG_UBSALNUM); + NOTE(REG_UUNSPEC); + } + RETV(PLAIN, c); + break; } assert(NOTREACHED); @@ -963,13 +1080,14 @@ brenext(struct vars *v, * skip - skip white space and comments in expanded form */ static void -skip(struct vars *v) +skip(struct vars * v) { - chr *start = v->now; + chr *start = v->now; - assert(v->cflags®_EXPANDED); + assert(v->cflags & REG_EXPANDED); - for (;;) { + for (;;) + { while (!ATEOS() && iscspace(*v->now)) v->now++; if (ATEOS() || *v->now != CHR('#')) @@ -1002,14 +1120,14 @@ newline(void) * use that it hardly matters. */ static chr -chrnamed(struct vars *v, - chr *startp, /* start of name */ - chr *endp, /* just past end of name */ +chrnamed(struct vars * v, + chr * startp, /* start of name */ + chr * endp, /* just past end of name */ chr lastresort) /* what to return if name lookup fails */ { - celt c; - int errsave; - int e; + celt c; + int errsave; + int e; struct cvec *cv; errsave = v->err; @@ -1019,10 +1137,10 @@ chrnamed(struct vars *v, v->err = errsave; if (e != 0) - return (chr)lastresort; + return (chr) lastresort; cv = range(v, c, c, 0); if (cv->nchrs == 0) - return (chr)lastresort; + return (chr) lastresort; return cv->chrs[0]; } diff --git a/src/backend/regex/regc_locale.c b/src/backend/regex/regc_locale.c index 41ea9fe1f2..69c7fd7214 100644 --- a/src/backend/regex/regc_locale.c +++ b/src/backend/regex/regc_locale.c @@ -1,4 +1,4 @@ -/* +/* * regc_locale.c -- * * This file contains locale-specific regexp routines. @@ -11,7 +11,7 @@ * Corporation and other parties. The following terms apply to all files * associated with the software unless explicitly disclaimed in * individual files. - * + * * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this @@ -21,137 +21,332 @@ * and need not follow the licensing terms described here, provided that * the new terms are clearly indicated on the first page of each file where * they apply. - * + * * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY * DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. - * + * * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE + * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR * MODIFICATIONS. - * + * * GOVERNMENT USE: If you are acquiring this software on behalf of the * U.S. government, the Government shall have only "Restricted Rights" - * in the software and related documentation as defined in the Federal - * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you + * in the software and related documentation as defined in the Federal + * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you * are acquiring the software on behalf of the Department of Defense, the * software shall be classified as "Commercial Computer Software" and the * Government shall have only "Restricted Rights" as defined in Clause * 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the * authors grant the U.S. Government and others acting in its behalf * permission to use and distribute the software in accordance with the - * terms specified in this license. + * terms specified in this license. * - * $Header: /cvsroot/pgsql/src/backend/regex/regc_locale.c,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regc_locale.c,v 1.2 2003/08/04 00:43:21 momjian Exp $ */ /* ASCII character-name table */ -static struct cname { - char *name; - char code; -} cnames[] = { - {"NUL", '\0'}, - {"SOH", '\001'}, - {"STX", '\002'}, - {"ETX", '\003'}, - {"EOT", '\004'}, - {"ENQ", '\005'}, - {"ACK", '\006'}, - {"BEL", '\007'}, - {"alert", '\007'}, - {"BS", '\010'}, - {"backspace", '\b'}, - {"HT", '\011'}, - {"tab", '\t'}, - {"LF", '\012'}, - {"newline", '\n'}, - {"VT", '\013'}, - {"vertical-tab", '\v'}, - {"FF", '\014'}, - {"form-feed", '\f'}, - {"CR", '\015'}, - {"carriage-return", '\r'}, - {"SO", '\016'}, - {"SI", '\017'}, - {"DLE", '\020'}, - {"DC1", '\021'}, - {"DC2", '\022'}, - {"DC3", '\023'}, - {"DC4", '\024'}, - {"NAK", '\025'}, - {"SYN", '\026'}, - {"ETB", '\027'}, - {"CAN", '\030'}, - {"EM", '\031'}, - {"SUB", '\032'}, - {"ESC", '\033'}, - {"IS4", '\034'}, - {"FS", '\034'}, - {"IS3", '\035'}, - {"GS", '\035'}, - {"IS2", '\036'}, - {"RS", '\036'}, - {"IS1", '\037'}, - {"US", '\037'}, - {"space", ' '}, - {"exclamation-mark",'!'}, - {"quotation-mark", '"'}, - {"number-sign", '#'}, - {"dollar-sign", '$'}, - {"percent-sign", '%'}, - {"ampersand", '&'}, - {"apostrophe", '\''}, - {"left-parenthesis",'('}, - {"right-parenthesis", ')'}, - {"asterisk", '*'}, - {"plus-sign", '+'}, - {"comma", ','}, - {"hyphen", '-'}, - {"hyphen-minus", '-'}, - {"period", '.'}, - {"full-stop", '.'}, - {"slash", '/'}, - {"solidus", '/'}, - {"zero", '0'}, - {"one", '1'}, - {"two", '2'}, - {"three", '3'}, - {"four", '4'}, - {"five", '5'}, - {"six", '6'}, - {"seven", '7'}, - {"eight", '8'}, - {"nine", '9'}, - {"colon", ':'}, - {"semicolon", ';'}, - {"less-than-sign", '<'}, - {"equals-sign", '='}, - {"greater-than-sign", '>'}, - {"question-mark", '?'}, - {"commercial-at", '@'}, - {"left-square-bracket", '['}, - {"backslash", '\\'}, - {"reverse-solidus", '\\'}, - {"right-square-bracket", ']'}, - {"circumflex", '^'}, - {"circumflex-accent", '^'}, - {"underscore", '_'}, - {"low-line", '_'}, - {"grave-accent", '`'}, - {"left-brace", '{'}, - {"left-curly-bracket", '{'}, - {"vertical-line", '|'}, - {"right-brace", '}'}, - {"right-curly-bracket", '}'}, - {"tilde", '~'}, - {"DEL", '\177'}, - {NULL, 0} +static struct cname +{ + char *name; + char code; +} cnames[] = + +{ + { + "NUL", '\0' + }, + { + "SOH", '\001' + }, + { + "STX", '\002' + }, + { + "ETX", '\003' + }, + { + "EOT", '\004' + }, + { + "ENQ", '\005' + }, + { + "ACK", '\006' + }, + { + "BEL", '\007' + }, + { + "alert", '\007' + }, + { + "BS", '\010' + }, + { + "backspace", '\b' + }, + { + "HT", '\011' + }, + { + "tab", '\t' + }, + { + "LF", '\012' + }, + { + "newline", '\n' + }, + { + "VT", '\013' + }, + { + "vertical-tab", '\v' + }, + { + "FF", '\014' + }, + { + "form-feed", '\f' + }, + { + "CR", '\015' + }, + { + "carriage-return", '\r' + }, + { + "SO", '\016' + }, + { + "SI", '\017' + }, + { + "DLE", '\020' + }, + { + "DC1", '\021' + }, + { + "DC2", '\022' + }, + { + "DC3", '\023' + }, + { + "DC4", '\024' + }, + { + "NAK", '\025' + }, + { + "SYN", '\026' + }, + { + "ETB", '\027' + }, + { + "CAN", '\030' + }, + { + "EM", '\031' + }, + { + "SUB", '\032' + }, + { + "ESC", '\033' + }, + { + "IS4", '\034' + }, + { + "FS", '\034' + }, + { + "IS3", '\035' + }, + { + "GS", '\035' + }, + { + "IS2", '\036' + }, + { + "RS", '\036' + }, + { + "IS1", '\037' + }, + { + "US", '\037' + }, + { + "space", ' ' + }, + { + "exclamation-mark", '!' + }, + { + "quotation-mark", '"' + }, + { + "number-sign", '#' + }, + { + "dollar-sign", '$' + }, + { + "percent-sign", '%' + }, + { + "ampersand", '&' + }, + { + "apostrophe", '\'' + }, + { + "left-parenthesis", '(' + }, + { + "right-parenthesis", ')' + }, + { + "asterisk", '*' + }, + { + "plus-sign", '+' + }, + { + "comma", ',' + }, + { + "hyphen", '-' + }, + { + "hyphen-minus", '-' + }, + { + "period", '.' + }, + { + "full-stop", '.' + }, + { + "slash", '/' + }, + { + "solidus", '/' + }, + { + "zero", '0' + }, + { + "one", '1' + }, + { + "two", '2' + }, + { + "three", '3' + }, + { + "four", '4' + }, + { + "five", '5' + }, + { + "six", '6' + }, + { + "seven", '7' + }, + { + "eight", '8' + }, + { + "nine", '9' + }, + { + "colon", ':' + }, + { + "semicolon", ';' + }, + { + "less-than-sign", '<' + }, + { + "equals-sign", '=' + }, + { + "greater-than-sign", '>' + }, + { + "question-mark", '?' + }, + { + "commercial-at", '@' + }, + { + "left-square-bracket", '[' + }, + { + "backslash", '\\' + }, + { + "reverse-solidus", '\\' + }, + { + "right-square-bracket", ']' + }, + { + "circumflex", '^' + }, + { + "circumflex-accent", '^' + }, + { + "underscore", '_' + }, + { + "low-line", '_' + }, + { + "grave-accent", '`' + }, + { + "left-brace", '{' + }, + { + "left-curly-bracket", '{' + }, + { + "vertical-line", '|' + }, + { + "right-brace", '}' + }, + { + "right-curly-bracket", '}' + }, + { + "tilde", '~' + }, + { + "DEL", '\177' + }, + { + NULL, 0 + } }; /* @@ -226,132 +421,134 @@ pg_tolower(pg_wchar c) * nmcces - how many distinct MCCEs are there? */ static int -nmcces(struct vars *v) +nmcces(struct vars * v) { - /* - * No multi-character collating elements defined at the moment. - */ - return 0; + /* + * No multi-character collating elements defined at the moment. + */ + return 0; } /* * nleaders - how many chrs can be first chrs of MCCEs? */ static int -nleaders(struct vars *v) +nleaders(struct vars * v) { - return 0; + return 0; } /* * allmcces - return a cvec with all the MCCEs of the locale */ static struct cvec * -allmcces(struct vars *v, /* context */ - struct cvec *cv) /* this is supposed to have enough room */ +allmcces(struct vars * v, /* context */ + struct cvec * cv) /* this is supposed to have enough room */ { - return clearcvec(cv); + return clearcvec(cv); } /* * element - map collating-element name to celt */ static celt -element(struct vars *v, /* context */ - chr *startp, /* points to start of name */ - chr *endp) /* points just past end of name */ +element(struct vars * v, /* context */ + chr * startp, /* points to start of name */ + chr * endp) /* points just past end of name */ { - struct cname *cn; - size_t len; + struct cname *cn; + size_t len; - /* generic: one-chr names stand for themselves */ - assert(startp < endp); - len = endp - startp; - if (len == 1) { - return *startp; - } + /* generic: one-chr names stand for themselves */ + assert(startp < endp); + len = endp - startp; + if (len == 1) + return *startp; - NOTE(REG_ULOCALE); + NOTE(REG_ULOCALE); - /* search table */ - for (cn=cnames; cn->name!=NULL; cn++) { - if (strlen(cn->name)==len && - pg_char_and_wchar_strncmp(cn->name, startp, len)==0) { - break; /* NOTE BREAK OUT */ + /* search table */ + for (cn = cnames; cn->name != NULL; cn++) + { + if (strlen(cn->name) == len && + pg_char_and_wchar_strncmp(cn->name, startp, len) == 0) + { + break; /* NOTE BREAK OUT */ + } } - } - if (cn->name != NULL) { - return CHR(cn->code); - } + if (cn->name != NULL) + return CHR(cn->code); - /* couldn't find it */ - ERR(REG_ECOLLATE); - return 0; + /* couldn't find it */ + ERR(REG_ECOLLATE); + return 0; } /* * range - supply cvec for a range, including legality check */ static struct cvec * -range(struct vars *v, /* context */ - celt a, /* range start */ - celt b, /* range end, might equal a */ +range(struct vars * v, /* context */ + celt a, /* range start */ + celt b, /* range end, might equal a */ int cases) /* case-independent? */ { - int nchrs; - struct cvec *cv; - celt c, lc, uc; + int nchrs; + struct cvec *cv; + celt c, + lc, + uc; - if (a != b && !before(a, b)) { - ERR(REG_ERANGE); - return NULL; - } + if (a != b && !before(a, b)) + { + ERR(REG_ERANGE); + return NULL; + } - if (!cases) { /* easy version */ - cv = getcvec(v, 0, 1, 0); + if (!cases) + { /* easy version */ + cv = getcvec(v, 0, 1, 0); + NOERRN(); + addrange(cv, a, b); + return cv; + } + + /* + * When case-independent, it's hard to decide when cvec ranges are + * usable, so for now at least, we won't try. We allocate enough + * space for two case variants plus a little extra for the two title + * case variants. + */ + + nchrs = (b - a + 1) * 2 + 4; + + cv = getcvec(v, nchrs, 0, 0); NOERRN(); - addrange(cv, a, b); + + for (c = a; c <= b; c++) + { + addchr(cv, c); + lc = pg_tolower((chr) c); + if (c != lc) + addchr(cv, lc); + uc = pg_toupper((chr) c); + if (c != uc) + addchr(cv, uc); + } + return cv; - } - - /* - * When case-independent, it's hard to decide when cvec ranges are - * usable, so for now at least, we won't try. We allocate enough - * space for two case variants plus a little extra for the two - * title case variants. - */ - - nchrs = (b - a + 1)*2 + 4; - - cv = getcvec(v, nchrs, 0, 0); - NOERRN(); - - for (c=a; c<=b; c++) { - addchr(cv, c); - lc = pg_tolower((chr)c); - if (c != lc) { - addchr(cv, lc); - } - uc = pg_toupper((chr)c); - if (c != uc) { - addchr(cv, uc); - } - } - - return cv; } /* * before - is celt x before celt y, for purposes of range legality? */ -static int /* predicate */ +static int /* predicate */ before(celt x, celt y) { - /* trivial because no MCCEs */ - if (x < y) { - return 1; - } - return 0; + /* trivial because no MCCEs */ + if (x < y) + return 1; + return 0; } /* @@ -359,33 +556,34 @@ before(celt x, celt y) * Must include case counterparts on request. */ static struct cvec * -eclass(struct vars *v, /* context */ - celt c, /* Collating element representing - * the equivalence class. */ +eclass(struct vars * v, /* context */ + celt c, /* Collating element representing the + * equivalence class. */ int cases) /* all cases? */ { - struct cvec *cv; + struct cvec *cv; - /* crude fake equivalence class for testing */ - if ((v->cflags®_FAKE) && c == 'x') { - cv = getcvec(v, 4, 0, 0); - addchr(cv, (chr)'x'); - addchr(cv, (chr)'y'); - if (cases) { - addchr(cv, (chr)'X'); - addchr(cv, (chr)'Y'); + /* crude fake equivalence class for testing */ + if ((v->cflags & REG_FAKE) && c == 'x') + { + cv = getcvec(v, 4, 0, 0); + addchr(cv, (chr) 'x'); + addchr(cv, (chr) 'y'); + if (cases) + { + addchr(cv, (chr) 'X'); + addchr(cv, (chr) 'Y'); + } + return cv; } - return cv; - } - /* otherwise, none */ - if (cases) { - return allcases(v, c); - } - cv = getcvec(v, 1, 0, 0); - assert(cv != NULL); - addchr(cv, (chr)c); - return cv; + /* otherwise, none */ + if (cases) + return allcases(v, c); + cv = getcvec(v, 1, 0, 0); + assert(cv != NULL); + addchr(cv, (chr) c); + return cv; } /* @@ -394,164 +592,182 @@ eclass(struct vars *v, /* context */ * Must include case counterparts on request. */ static struct cvec * -cclass(struct vars *v, /* context */ - chr *startp, /* where the name starts */ - chr *endp, /* just past the end of the name */ +cclass(struct vars * v, /* context */ + chr * startp, /* where the name starts */ + chr * endp, /* just past the end of the name */ int cases) /* case-independent? */ { - size_t len; - struct cvec *cv = NULL; - char **namePtr; - int i, index; + size_t len; + struct cvec *cv = NULL; + char **namePtr; + int i, + index; - /* - * The following arrays define the valid character class names. - */ + /* + * The following arrays define the valid character class names. + */ - static char *classNames[] = { - "alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph", - "lower", "print", "punct", "space", "upper", "xdigit", NULL - }; + static char *classNames[] = { + "alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph", + "lower", "print", "punct", "space", "upper", "xdigit", NULL + }; - enum classes { - CC_ALNUM, CC_ALPHA, CC_ASCII, CC_BLANK, CC_CNTRL, CC_DIGIT, CC_GRAPH, - CC_LOWER, CC_PRINT, CC_PUNCT, CC_SPACE, CC_UPPER, CC_XDIGIT - }; + enum classes + { + CC_ALNUM, CC_ALPHA, CC_ASCII, CC_BLANK, CC_CNTRL, CC_DIGIT, CC_GRAPH, + CC_LOWER, CC_PRINT, CC_PUNCT, CC_SPACE, CC_UPPER, CC_XDIGIT + }; - /* - * Map the name to the corresponding enumerated value. - */ - len = endp - startp; - index = -1; - for (namePtr=classNames,i=0 ; *namePtr!=NULL ; namePtr++,i++) { - if (strlen(*namePtr) == len && - pg_char_and_wchar_strncmp(*namePtr, startp, len) == 0) { - index = i; - break; + /* + * Map the name to the corresponding enumerated value. + */ + len = endp - startp; + index = -1; + for (namePtr = classNames, i = 0; *namePtr != NULL; namePtr++, i++) + { + if (strlen(*namePtr) == len && + pg_char_and_wchar_strncmp(*namePtr, startp, len) == 0) + { + index = i; + break; + } + } + if (index == -1) + { + ERR(REG_ECTYPE); + return NULL; } - } - if (index == -1) { - ERR(REG_ECTYPE); - return NULL; - } - /* - * Remap lower and upper to alpha if the match is case insensitive. - */ + /* + * Remap lower and upper to alpha if the match is case insensitive. + */ - if (cases && + if (cases && ((enum classes) index == CC_LOWER || (enum classes) index == CC_UPPER)) index = (int) CC_ALPHA; - - /* - * Now compute the character class contents. + + /* + * Now compute the character class contents. * * For the moment, assume that only char codes < 256 can be in these * classes. - */ + */ - switch((enum classes) index) { - case CC_PRINT: - case CC_ALNUM: - cv = getcvec(v, UCHAR_MAX, 1, 0); - if (cv) { - for (i=0 ; i<= UCHAR_MAX ; i++) { - if (pg_isalpha((chr) i)) - addchr(cv, (chr) i); - } - addrange(cv, (chr) '0', (chr) '9'); + switch ((enum classes) index) + { + case CC_PRINT: + case CC_ALNUM: + cv = getcvec(v, UCHAR_MAX, 1, 0); + if (cv) + { + for (i = 0; i <= UCHAR_MAX; i++) + { + if (pg_isalpha((chr) i)) + addchr(cv, (chr) i); + } + addrange(cv, (chr) '0', (chr) '9'); + } + break; + case CC_ALPHA: + cv = getcvec(v, UCHAR_MAX, 0, 0); + if (cv) + { + for (i = 0; i <= UCHAR_MAX; i++) + { + if (pg_isalpha((chr) i)) + addchr(cv, (chr) i); + } + } + break; + case CC_ASCII: + cv = getcvec(v, 0, 1, 0); + if (cv) + addrange(cv, 0, 0x7f); + break; + case CC_BLANK: + cv = getcvec(v, 2, 0, 0); + addchr(cv, '\t'); + addchr(cv, ' '); + break; + case CC_CNTRL: + cv = getcvec(v, 0, 2, 0); + addrange(cv, 0x0, 0x1f); + addrange(cv, 0x7f, 0x9f); + break; + case CC_DIGIT: + cv = getcvec(v, 0, 1, 0); + if (cv) + addrange(cv, (chr) '0', (chr) '9'); + break; + case CC_PUNCT: + cv = getcvec(v, UCHAR_MAX, 0, 0); + if (cv) + { + for (i = 0; i <= UCHAR_MAX; i++) + { + if (pg_ispunct((chr) i)) + addchr(cv, (chr) i); + } + } + break; + case CC_XDIGIT: + cv = getcvec(v, 0, 3, 0); + if (cv) + { + addrange(cv, '0', '9'); + addrange(cv, 'a', 'f'); + addrange(cv, 'A', 'F'); + } + break; + case CC_SPACE: + cv = getcvec(v, UCHAR_MAX, 0, 0); + if (cv) + { + for (i = 0; i <= UCHAR_MAX; i++) + { + if (pg_isspace((chr) i)) + addchr(cv, (chr) i); + } + } + break; + case CC_LOWER: + cv = getcvec(v, UCHAR_MAX, 0, 0); + if (cv) + { + for (i = 0; i <= UCHAR_MAX; i++) + { + if (pg_islower((chr) i)) + addchr(cv, (chr) i); + } + } + break; + case CC_UPPER: + cv = getcvec(v, UCHAR_MAX, 0, 0); + if (cv) + { + for (i = 0; i <= UCHAR_MAX; i++) + { + if (pg_isupper((chr) i)) + addchr(cv, (chr) i); + } + } + break; + case CC_GRAPH: + cv = getcvec(v, UCHAR_MAX, 0, 0); + if (cv) + { + for (i = 0; i <= UCHAR_MAX; i++) + { + if (pg_isgraph((chr) i)) + addchr(cv, (chr) i); + } + } + break; } - break; - case CC_ALPHA: - cv = getcvec(v, UCHAR_MAX, 0, 0); - if (cv) { - for (i=0 ; i<= UCHAR_MAX ; i++) { - if (pg_isalpha((chr) i)) - addchr(cv, (chr) i); - } - } - break; - case CC_ASCII: - cv = getcvec(v, 0, 1, 0); - if (cv) { - addrange(cv, 0, 0x7f); - } - break; - case CC_BLANK: - cv = getcvec(v, 2, 0, 0); - addchr(cv, '\t'); - addchr(cv, ' '); - break; - case CC_CNTRL: - cv = getcvec(v, 0, 2, 0); - addrange(cv, 0x0, 0x1f); - addrange(cv, 0x7f, 0x9f); - break; - case CC_DIGIT: - cv = getcvec(v, 0, 1, 0); - if (cv) { - addrange(cv, (chr) '0', (chr) '9'); - } - break; - case CC_PUNCT: - cv = getcvec(v, UCHAR_MAX, 0, 0); - if (cv) { - for (i=0 ; i<= UCHAR_MAX ; i++) { - if (pg_ispunct((chr) i)) - addchr(cv, (chr) i); - } - } - break; - case CC_XDIGIT: - cv = getcvec(v, 0, 3, 0); - if (cv) { - addrange(cv, '0', '9'); - addrange(cv, 'a', 'f'); - addrange(cv, 'A', 'F'); - } - break; - case CC_SPACE: - cv = getcvec(v, UCHAR_MAX, 0, 0); - if (cv) { - for (i=0 ; i<= UCHAR_MAX ; i++) { - if (pg_isspace((chr) i)) - addchr(cv, (chr) i); - } - } - break; - case CC_LOWER: - cv = getcvec(v, UCHAR_MAX, 0, 0); - if (cv) { - for (i=0 ; i<= UCHAR_MAX ; i++) { - if (pg_islower((chr) i)) - addchr(cv, (chr) i); - } - } - break; - case CC_UPPER: - cv = getcvec(v, UCHAR_MAX, 0, 0); - if (cv) { - for (i=0 ; i<= UCHAR_MAX ; i++) { - if (pg_isupper((chr) i)) - addchr(cv, (chr) i); - } - } - break; - case CC_GRAPH: - cv = getcvec(v, UCHAR_MAX, 0, 0); - if (cv) { - for (i=0 ; i<= UCHAR_MAX ; i++) { - if (pg_isgraph((chr) i)) - addchr(cv, (chr) i); - } - } - break; - } - if (cv == NULL) { - ERR(REG_ESPACE); - } - return cv; + if (cv == NULL) + ERR(REG_ESPACE); + return cv; } /* @@ -561,37 +777,37 @@ cclass(struct vars *v, /* context */ * messy cases are done via range(). */ static struct cvec * -allcases(struct vars *v, /* context */ +allcases(struct vars * v, /* context */ chr pc) /* character to get case equivs of */ { - struct cvec *cv; - chr c = (chr)pc; - chr lc, uc; + struct cvec *cv; + chr c = (chr) pc; + chr lc, + uc; - lc = pg_tolower((chr)c); - uc = pg_toupper((chr)c); + lc = pg_tolower((chr) c); + uc = pg_toupper((chr) c); cv = getcvec(v, 2, 0, 0); - addchr(cv, lc); - if (lc != uc) { - addchr(cv, uc); - } - return cv; + addchr(cv, lc); + if (lc != uc) + addchr(cv, uc); + return cv; } /* * cmp - chr-substring compare * - * Backrefs need this. It should preferably be efficient. + * Backrefs need this. It should preferably be efficient. * Note that it does not need to report anything except equal/unequal. * Note also that the length is exact, and the comparison should not * stop at embedded NULs! */ -static int /* 0 for equal, nonzero for unequal */ -cmp(const chr *x, const chr *y, /* strings to compare */ - size_t len) /* exact length of comparison */ +static int /* 0 for equal, nonzero for unequal */ +cmp(const chr * x, const chr * y, /* strings to compare */ + size_t len) /* exact length of comparison */ { - return memcmp(VS(x), VS(y), len*sizeof(chr)); + return memcmp(VS(x), VS(y), len * sizeof(chr)); } /* @@ -602,14 +818,14 @@ cmp(const chr *x, const chr *y, /* strings to compare */ * Note also that the length is exact, and the comparison should not * stop at embedded NULs! */ -static int /* 0 for equal, nonzero for unequal */ -casecmp(const chr *x, const chr *y, /* strings to compare */ +static int /* 0 for equal, nonzero for unequal */ +casecmp(const chr * x, const chr * y, /* strings to compare */ size_t len) /* exact length of comparison */ { - for (; len > 0; len--, x++, y++) { - if ((*x!=*y) && (pg_tolower(*x) != pg_tolower(*y))) { - return 1; + for (; len > 0; len--, x++, y++) + { + if ((*x != *y) && (pg_tolower(*x) != pg_tolower(*y))) + return 1; } - } - return 0; + return 0; } diff --git a/src/backend/regex/regc_nfa.c b/src/backend/regex/regc_nfa.c index 43e01ebe92..51fd8bfb85 100644 --- a/src/backend/regex/regc_nfa.c +++ b/src/backend/regex/regc_nfa.c @@ -2,21 +2,21 @@ * NFA utilities. * This file is #included by regcomp.c. * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -28,7 +28,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regc_nfa.c,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regc_nfa.c,v 1.2 2003/08/04 00:43:21 momjian Exp $ * * * One or two things that technically ought to be in here @@ -36,21 +36,21 @@ * the color chains. */ -#define NISERR() VISERR(nfa->v) -#define NERR(e) VERR(nfa->v, (e)) +#define NISERR() VISERR(nfa->v) +#define NERR(e) VERR(nfa->v, (e)) /* * newnfa - set up an NFA */ -static struct nfa * /* the NFA, or NULL */ -newnfa(struct vars *v, - struct colormap *cm, - struct nfa *parent) /* NULL if primary NFA */ +static struct nfa * /* the NFA, or NULL */ +newnfa(struct vars * v, + struct colormap * cm, + struct nfa * parent) /* NULL if primary NFA */ { struct nfa *nfa; - nfa = (struct nfa *)MALLOC(sizeof(struct nfa)); + nfa = (struct nfa *) MALLOC(sizeof(struct nfa)); if (nfa == NULL) return NULL; @@ -66,9 +66,10 @@ newnfa(struct vars *v, nfa->pre = newfstate(nfa, '>'); /* number 1 */ nfa->parent = parent; - nfa->init = newstate(nfa); /* may become invalid later */ + nfa->init = newstate(nfa); /* may become invalid later */ nfa->final = newstate(nfa); - if (ISERR()) { + if (ISERR()) + { freenfa(nfa); return NULL; } @@ -79,7 +80,8 @@ newnfa(struct vars *v, newarc(nfa, '$', 1, nfa->final, nfa->post); newarc(nfa, '$', 0, nfa->final, nfa->post); - if (ISERR()) { + if (ISERR()) + { freenfa(nfa); return NULL; } @@ -90,15 +92,17 @@ newnfa(struct vars *v, * freenfa - free an entire NFA */ static void -freenfa(struct nfa *nfa) +freenfa(struct nfa * nfa) { struct state *s; - while ((s = nfa->states) != NULL) { - s->nins = s->nouts = 0; /* don't worry about arcs */ + while ((s = nfa->states) != NULL) + { + s->nins = s->nouts = 0; /* don't worry about arcs */ freestate(nfa, s); } - while ((s = nfa->free) != NULL) { + while ((s = nfa->free) != NULL) + { nfa->free = s->next; destroystate(nfa, s); } @@ -113,17 +117,21 @@ freenfa(struct nfa *nfa) /* * newstate - allocate an NFA state, with zero flag value */ -static struct state * /* NULL on error */ -newstate(struct nfa *nfa) +static struct state * /* NULL on error */ +newstate(struct nfa * nfa) { struct state *s; - if (nfa->free != NULL) { + if (nfa->free != NULL) + { s = nfa->free; nfa->free = s->next; - } else { - s = (struct state *)MALLOC(sizeof(struct state)); - if (s == NULL) { + } + else + { + s = (struct state *) MALLOC(sizeof(struct state)); + if (s == NULL) + { NERR(REG_ESPACE); return NULL; } @@ -143,7 +151,8 @@ newstate(struct nfa *nfa) s->outs = NULL; s->tmp = NULL; s->next = NULL; - if (nfa->slast != NULL) { + if (nfa->slast != NULL) + { assert(nfa->slast->next == NULL); nfa->slast->next = s; } @@ -155,14 +164,14 @@ newstate(struct nfa *nfa) /* * newfstate - allocate an NFA state with a specified flag value */ -static struct state * /* NULL on error */ -newfstate(struct nfa *nfa, int flag) +static struct state * /* NULL on error */ +newfstate(struct nfa * nfa, int flag) { struct state *s; s = newstate(nfa); if (s != NULL) - s->flag = (char)flag; + s->flag = (char) flag; return s; } @@ -170,8 +179,8 @@ newfstate(struct nfa *nfa, int flag) * dropstate - delete a state's inarcs and outarcs and free it */ static void -dropstate(struct nfa *nfa, - struct state *s) +dropstate(struct nfa * nfa, + struct state * s) { struct arc *a; @@ -186,8 +195,8 @@ dropstate(struct nfa *nfa, * freestate - free a state, which has no in-arcs or out-arcs */ static void -freestate(struct nfa *nfa, - struct state *s) +freestate(struct nfa * nfa, + struct state * s) { assert(s != NULL); assert(s->nins == 0 && s->nouts == 0); @@ -196,18 +205,21 @@ freestate(struct nfa *nfa, s->flag = 0; if (s->next != NULL) s->next->prev = s->prev; - else { + else + { assert(s == nfa->slast); nfa->slast = s->prev; } if (s->prev != NULL) s->prev->next = s->next; - else { + else + { assert(s == nfa->states); nfa->states = s->next; } s->prev = NULL; - s->next = nfa->free; /* don't delete it, put it on the free list */ + s->next = nfa->free; /* don't delete it, put it on the free + * list */ nfa->free = s; } @@ -215,14 +227,15 @@ freestate(struct nfa *nfa, * destroystate - really get rid of an already-freed state */ static void -destroystate(struct nfa *nfa, - struct state *s) +destroystate(struct nfa * nfa, + struct state * s) { struct arcbatch *ab; struct arcbatch *abnext; assert(s->no == FREESTATE); - for (ab = s->oas.next; ab != NULL; ab = abnext) { + for (ab = s->oas.next; ab != NULL; ab = abnext) + { abnext = ab->next; FREE(ab); } @@ -236,11 +249,11 @@ destroystate(struct nfa *nfa, * newarc - set up a new arc within an NFA */ static void -newarc(struct nfa *nfa, +newarc(struct nfa * nfa, int t, pcolor co, - struct state *from, - struct state *to) + struct state * from, + struct state * to) { struct arc *a; @@ -257,13 +270,13 @@ newarc(struct nfa *nfa, assert(a != NULL); a->type = t; - a->co = (color)co; + a->co = (color) co; a->to = to; a->from = from; /* - * Put the new arc on the beginning, not the end, of the chains. - * Not only is this easier, it has the very useful side effect that + * Put the new arc on the beginning, not the end, of the chains. Not + * only is this easier, it has the very useful side effect that * deleting the most-recently-added arc is the cheapest case rather * than the most expensive one. */ @@ -284,36 +297,40 @@ newarc(struct nfa *nfa, /* * allocarc - allocate a new out-arc within a state */ -static struct arc * /* NULL for failure */ -allocarc(struct nfa *nfa, - struct state *s) +static struct arc * /* NULL for failure */ +allocarc(struct nfa * nfa, + struct state * s) { struct arc *a; struct arcbatch *new; - int i; + int i; /* shortcut */ - if (s->free == NULL && s->noas < ABSIZE) { + if (s->free == NULL && s->noas < ABSIZE) + { a = &s->oas.a[s->noas]; s->noas++; return a; } /* if none at hand, get more */ - if (s->free == NULL) { - new = (struct arcbatch *)MALLOC(sizeof(struct arcbatch)); - if (new == NULL) { + if (s->free == NULL) + { + new = (struct arcbatch *) MALLOC(sizeof(struct arcbatch)); + if (new == NULL) + { NERR(REG_ESPACE); return NULL; } new->next = s->oas.next; s->oas.next = new; - for (i = 0; i < ABSIZE; i++) { + for (i = 0; i < ABSIZE; i++) + { new->a[i].type = 0; - new->a[i].freechain = &new->a[i+1]; + new->a[i].freechain = &new->a[i + 1]; } - new->a[ABSIZE-1].freechain = NULL; + new->a[ABSIZE - 1].freechain = NULL; s->free = &new->a[0]; } assert(s->free != NULL); @@ -327,8 +344,8 @@ allocarc(struct nfa *nfa, * freearc - free an arc */ static void -freearc(struct nfa *nfa, - struct arc *victim) +freearc(struct nfa * nfa, + struct arc * victim) { struct state *from = victim->from; struct state *to = victim->to; @@ -344,9 +361,10 @@ freearc(struct nfa *nfa, assert(from != NULL); assert(from->outs != NULL); a = from->outs; - if (a == victim) /* simple case: first in chain */ + if (a == victim) /* simple case: first in chain */ from->outs = victim->outchain; - else { + else + { for (; a != NULL && a->outchain != victim; a = a->outchain) continue; assert(a != NULL); @@ -358,9 +376,10 @@ freearc(struct nfa *nfa, assert(to != NULL); assert(to->ins != NULL); a = to->ins; - if (a == victim) /* simple case: first in chain */ + if (a == victim) /* simple case: first in chain */ to->ins = victim->inchain; - else { + else + { for (; a != NULL && a->inchain != victim; a = a->inchain) continue; assert(a != NULL); @@ -383,7 +402,7 @@ freearc(struct nfa *nfa, * If there is more than one such arc, the result is random. */ static struct arc * -findarc(struct state *s, +findarc(struct state * s, int type, pcolor co) { @@ -399,10 +418,10 @@ findarc(struct state *s, * cparc - allocate a new arc within an NFA, copying details from old one */ static void -cparc(struct nfa *nfa, - struct arc *oa, - struct state *from, - struct state *to) +cparc(struct nfa * nfa, + struct arc * oa, + struct state * from, + struct state * to) { newarc(nfa, oa->type, oa->co, from, to); } @@ -416,15 +435,16 @@ cparc(struct nfa *nfa, * ones to exploit the suppression built into newarc. */ static void -moveins(struct nfa *nfa, - struct state *old, - struct state *new) +moveins(struct nfa * nfa, + struct state * old, + struct state * new) { struct arc *a; assert(old != new); - while ((a = old->ins) != NULL) { + while ((a = old->ins) != NULL) + { cparc(nfa, a, a->from, new); freearc(nfa, a); } @@ -436,9 +456,9 @@ moveins(struct nfa *nfa, * copyins - copy all in arcs of a state to another state */ static void -copyins(struct nfa *nfa, - struct state *old, - struct state *new) +copyins(struct nfa * nfa, + struct state * old, + struct state * new) { struct arc *a; @@ -452,15 +472,16 @@ copyins(struct nfa *nfa, * moveouts - move all out arcs of a state to another state */ static void -moveouts(struct nfa *nfa, - struct state *old, - struct state *new) +moveouts(struct nfa * nfa, + struct state * old, + struct state * new) { struct arc *a; assert(old != new); - while ((a = old->outs) != NULL) { + while ((a = old->outs) != NULL) + { cparc(nfa, a, new, a->to); freearc(nfa, a); } @@ -470,9 +491,9 @@ moveouts(struct nfa *nfa, * copyouts - copy all out arcs of a state to another state */ static void -copyouts(struct nfa *nfa, - struct state *old, - struct state *new) +copyouts(struct nfa * nfa, + struct state * old, + struct state * new) { struct arc *a; @@ -486,10 +507,10 @@ copyouts(struct nfa *nfa, * cloneouts - copy out arcs of a state to another state pair, modifying type */ static void -cloneouts(struct nfa *nfa, - struct state *old, - struct state *from, - struct state *to, +cloneouts(struct nfa * nfa, + struct state * old, + struct state * from, + struct state * to, int type) { struct arc *a; @@ -507,20 +528,20 @@ cloneouts(struct nfa *nfa, * states using their tmp pointer. */ static void -delsub(struct nfa *nfa, - struct state *lp, /* the sub-NFA goes from here... */ - struct state *rp) /* ...to here, *not* inclusive */ +delsub(struct nfa * nfa, + struct state * lp, /* the sub-NFA goes from here... */ + struct state * rp) /* ...to here, *not* inclusive */ { assert(lp != rp); - rp->tmp = rp; /* mark end */ + rp->tmp = rp; /* mark end */ deltraverse(nfa, lp, lp); assert(lp->nouts == 0 && rp->nins == 0); /* did the job */ - assert(lp->no != FREESTATE && rp->no != FREESTATE); /* no more */ + assert(lp->no != FREESTATE && rp->no != FREESTATE); /* no more */ - rp->tmp = NULL; /* unmark end */ - lp->tmp = NULL; /* and begin, marked by deltraverse */ + rp->tmp = NULL; /* unmark end */ + lp->tmp = NULL; /* and begin, marked by deltraverse */ } /* @@ -528,36 +549,38 @@ delsub(struct nfa *nfa, * This routine's basic job is to destroy all out-arcs of the state. */ static void -deltraverse(struct nfa *nfa, - struct state *leftend, - struct state *s) +deltraverse(struct nfa * nfa, + struct state * leftend, + struct state * s) { struct arc *a; struct state *to; if (s->nouts == 0) - return; /* nothing to do */ + return; /* nothing to do */ if (s->tmp != NULL) - return; /* already in progress */ + return; /* already in progress */ - s->tmp = s; /* mark as in progress */ + s->tmp = s; /* mark as in progress */ - while ((a = s->outs) != NULL) { + while ((a = s->outs) != NULL) + { to = a->to; deltraverse(nfa, leftend, to); assert(to->nouts == 0 || to->tmp != NULL); freearc(nfa, a); - if (to->nins == 0 && to->tmp == NULL) { + if (to->nins == 0 && to->tmp == NULL) + { assert(to->nouts == 0); freestate(nfa, to); } } - assert(s->no != FREESTATE); /* we're still here */ - assert(s == leftend || s->nins != 0); /* and still reachable */ + assert(s->no != FREESTATE); /* we're still here */ + assert(s == leftend || s->nins != 0); /* and still reachable */ assert(s->nouts == 0); /* but have no outarcs */ - s->tmp = NULL; /* we're done here */ + s->tmp = NULL; /* we're done here */ } /* @@ -568,13 +591,14 @@ deltraverse(struct nfa *nfa, * it's a state pointer, didn't you? :-)) */ static void -dupnfa(struct nfa *nfa, - struct state *start, /* duplicate of subNFA starting here */ - struct state *stop, /* and stopping here */ - struct state *from, /* stringing duplicate from here */ - struct state *to) /* to here */ +dupnfa(struct nfa * nfa, + struct state * start, /* duplicate of subNFA starting here */ + struct state * stop, /* and stopping here */ + struct state * from, /* stringing duplicate from here */ + struct state * to) /* to here */ { - if (start == stop) { + if (start == stop) + { newarc(nfa, EMPTY, 0, from, to); return; } @@ -591,23 +615,25 @@ dupnfa(struct nfa *nfa, * duptraverse - recursive heart of dupnfa */ static void -duptraverse(struct nfa *nfa, - struct state *s, - struct state *stmp) /* s's duplicate, or NULL */ +duptraverse(struct nfa * nfa, + struct state * s, + struct state * stmp) /* s's duplicate, or NULL */ { struct arc *a; if (s->tmp != NULL) - return; /* already done */ + return; /* already done */ s->tmp = (stmp == NULL) ? newstate(nfa) : stmp; - if (s->tmp == NULL) { + if (s->tmp == NULL) + { assert(NISERR()); return; } - for (a = s->outs; a != NULL && !NISERR(); a = a->outchain) { - duptraverse(nfa, a->to, (struct state *)NULL); + for (a = s->outs; a != NULL && !NISERR(); a = a->outchain) + { + duptraverse(nfa, a->to, (struct state *) NULL); assert(a->to->tmp != NULL); cparc(nfa, a, s->tmp, a->to->tmp); } @@ -617,8 +643,8 @@ duptraverse(struct nfa *nfa, * cleartraverse - recursive cleanup for algorithms that leave tmp ptrs set */ static void -cleartraverse(struct nfa *nfa, - struct state *s) +cleartraverse(struct nfa * nfa, + struct state * s) { struct arc *a; @@ -634,15 +660,18 @@ cleartraverse(struct nfa *nfa, * specialcolors - fill in special colors for an NFA */ static void -specialcolors(struct nfa *nfa) +specialcolors(struct nfa * nfa) { /* false colors for BOS, BOL, EOS, EOL */ - if (nfa->parent == NULL) { + if (nfa->parent == NULL) + { nfa->bos[0] = pseudocolor(nfa->cm); nfa->bos[1] = pseudocolor(nfa->cm); nfa->eos[0] = pseudocolor(nfa->cm); nfa->eos[1] = pseudocolor(nfa->cm); - } else { + } + else + { assert(nfa->parent->bos[0] != COLORLESS); nfa->bos[0] = nfa->parent->bos[0]; assert(nfa->parent->bos[1] != COLORLESS); @@ -657,57 +686,60 @@ specialcolors(struct nfa *nfa) /* * optimize - optimize an NFA */ -static long /* re_info bits */ -optimize(struct nfa *nfa, +static long /* re_info bits */ +optimize(struct nfa * nfa, FILE *f) /* for debug output; NULL none */ { #ifdef REG_DEBUG - int verbose = (f != NULL) ? 1 : 0; + int verbose = (f != NULL) ? 1 : 0; if (verbose) fprintf(f, "\ninitial cleanup:\n"); #endif - cleanup(nfa); /* may simplify situation */ + cleanup(nfa); /* may simplify situation */ #ifdef REG_DEBUG if (verbose) dumpnfa(nfa, f); if (verbose) fprintf(f, "\nempties:\n"); #endif - fixempties(nfa, f); /* get rid of EMPTY arcs */ + fixempties(nfa, f); /* get rid of EMPTY arcs */ #ifdef REG_DEBUG if (verbose) fprintf(f, "\nconstraints:\n"); #endif - pullback(nfa, f); /* pull back constraints backward */ - pushfwd(nfa, f); /* push fwd constraints forward */ + pullback(nfa, f); /* pull back constraints backward */ + pushfwd(nfa, f); /* push fwd constraints forward */ #ifdef REG_DEBUG if (verbose) fprintf(f, "\nfinal cleanup:\n"); #endif - cleanup(nfa); /* final tidying */ - return analyze(nfa); /* and analysis */ + cleanup(nfa); /* final tidying */ + return analyze(nfa); /* and analysis */ } /* * pullback - pull back constraints backward to (with luck) eliminate them */ static void -pullback(struct nfa *nfa, - FILE *f) /* for debug output; NULL none */ +pullback(struct nfa * nfa, + FILE *f) /* for debug output; NULL none */ { struct state *s; struct state *nexts; struct arc *a; struct arc *nexta; - int progress; + int progress; /* find and pull until there are no more */ - do { + do + { progress = 0; - for (s = nfa->states; s != NULL && !NISERR(); s = nexts) { + for (s = nfa->states; s != NULL && !NISERR(); s = nexts) + { nexts = s->next; - for (a = s->outs; a != NULL && !NISERR(); a = nexta) { + for (a = s->outs; a != NULL && !NISERR(); a = nexta) + { nexta = a->outchain; if (a->type == '^' || a->type == BEHIND) if (pull(nfa, a)) @@ -721,9 +753,11 @@ pullback(struct nfa *nfa, if (NISERR()) return; - for (a = nfa->pre->outs; a != NULL; a = nexta) { + for (a = nfa->pre->outs; a != NULL; a = nexta) + { nexta = a->outchain; - if (a->type == '^') { + if (a->type == '^') + { assert(a->co == 0 || a->co == 1); newarc(nfa, PLAIN, nfa->bos[a->co], a->from, a->to); freearc(nfa, a); @@ -737,9 +771,9 @@ pullback(struct nfa *nfa, * one state -- the constraint's from state -- and only if the constraint * was that state's last outarc. */ -static int /* 0 couldn't, 1 could */ -pull(struct nfa *nfa, - struct arc *con) +static int /* 0 couldn't, 1 could */ +pull(struct nfa * nfa, + struct arc * con) { struct state *from = con->from; struct state *to = con->to; @@ -747,25 +781,28 @@ pull(struct nfa *nfa, struct arc *nexta; struct state *s; - if (from == to) { /* circular constraint is pointless */ + if (from == to) + { /* circular constraint is pointless */ freearc(nfa, con); return 1; } - if (from->flag) /* can't pull back beyond start */ + if (from->flag) /* can't pull back beyond start */ return 0; - if (from->nins == 0) { /* unreachable */ + if (from->nins == 0) + { /* unreachable */ freearc(nfa, con); return 1; } /* first, clone from state if necessary to avoid other outarcs */ - if (from->nouts > 1) { + if (from->nouts > 1) + { s = newstate(nfa); if (NISERR()) return 0; assert(to != from); /* con is not an inarc */ - copyins(nfa, from, s); /* duplicate inarcs */ - cparc(nfa, con, s, to); /* move constraint arc */ + copyins(nfa, from, s); /* duplicate inarcs */ + cparc(nfa, con, s, to); /* move constraint arc */ freearc(nfa, con); from = s; con = from->outs; @@ -773,27 +810,29 @@ pull(struct nfa *nfa, assert(from->nouts == 1); /* propagate the constraint into the from state's inarcs */ - for (a = from->ins; a != NULL; a = nexta) { + for (a = from->ins; a != NULL; a = nexta) + { nexta = a->inchain; - switch (combine(con, a)) { - case INCOMPATIBLE: /* destroy the arc */ - freearc(nfa, a); - break; - case SATISFIED: /* no action needed */ - break; - case COMPATIBLE: /* swap the two arcs, more or less */ - s = newstate(nfa); - if (NISERR()) - return 0; - cparc(nfa, a, s, to); /* anticipate move */ - cparc(nfa, con, a->from, s); - if (NISERR()) - return 0; - freearc(nfa, a); - break; - default: - assert(NOTREACHED); - break; + switch (combine(con, a)) + { + case INCOMPATIBLE: /* destroy the arc */ + freearc(nfa, a); + break; + case SATISFIED: /* no action needed */ + break; + case COMPATIBLE: /* swap the two arcs, more or less */ + s = newstate(nfa); + if (NISERR()) + return 0; + cparc(nfa, a, s, to); /* anticipate move */ + cparc(nfa, con, a->from, s); + if (NISERR()) + return 0; + freearc(nfa, a); + break; + default: + assert(NOTREACHED); + break; } } @@ -807,21 +846,24 @@ pull(struct nfa *nfa, * pushfwd - push forward constraints forward to (with luck) eliminate them */ static void -pushfwd(struct nfa *nfa, - FILE *f) /* for debug output; NULL none */ +pushfwd(struct nfa * nfa, + FILE *f) /* for debug output; NULL none */ { struct state *s; struct state *nexts; struct arc *a; struct arc *nexta; - int progress; + int progress; /* find and push until there are no more */ - do { + do + { progress = 0; - for (s = nfa->states; s != NULL && !NISERR(); s = nexts) { + for (s = nfa->states; s != NULL && !NISERR(); s = nexts) + { nexts = s->next; - for (a = s->ins; a != NULL && !NISERR(); a = nexta) { + for (a = s->ins; a != NULL && !NISERR(); a = nexta) + { nexta = a->inchain; if (a->type == '$' || a->type == AHEAD) if (push(nfa, a)) @@ -835,9 +877,11 @@ pushfwd(struct nfa *nfa, if (NISERR()) return; - for (a = nfa->post->ins; a != NULL; a = nexta) { + for (a = nfa->post->ins; a != NULL; a = nexta) + { nexta = a->inchain; - if (a->type == '$') { + if (a->type == '$') + { assert(a->co == 0 || a->co == 1); newarc(nfa, PLAIN, nfa->eos[a->co], a->from, a->to); freearc(nfa, a); @@ -851,9 +895,9 @@ pushfwd(struct nfa *nfa, * one state -- the constraint's to state -- and only if the constraint * was that state's last inarc. */ -static int /* 0 couldn't, 1 could */ -push(struct nfa *nfa, - struct arc *con) +static int /* 0 couldn't, 1 could */ +push(struct nfa * nfa, + struct arc * con) { struct state *from = con->from; struct state *to = con->to; @@ -861,24 +905,27 @@ push(struct nfa *nfa, struct arc *nexta; struct state *s; - if (to == from) { /* circular constraint is pointless */ + if (to == from) + { /* circular constraint is pointless */ freearc(nfa, con); return 1; } - if (to->flag) /* can't push forward beyond end */ + if (to->flag) /* can't push forward beyond end */ return 0; - if (to->nouts == 0) { /* dead end */ + if (to->nouts == 0) + { /* dead end */ freearc(nfa, con); return 1; } /* first, clone to state if necessary to avoid other inarcs */ - if (to->nins > 1) { + if (to->nins > 1) + { s = newstate(nfa); if (NISERR()) return 0; - copyouts(nfa, to, s); /* duplicate outarcs */ - cparc(nfa, con, from, s); /* move constraint */ + copyouts(nfa, to, s); /* duplicate outarcs */ + cparc(nfa, con, from, s); /* move constraint */ freearc(nfa, con); to = s; con = to->ins; @@ -886,88 +933,91 @@ push(struct nfa *nfa, assert(to->nins == 1); /* propagate the constraint into the to state's outarcs */ - for (a = to->outs; a != NULL; a = nexta) { + for (a = to->outs; a != NULL; a = nexta) + { nexta = a->outchain; - switch (combine(con, a)) { - case INCOMPATIBLE: /* destroy the arc */ - freearc(nfa, a); - break; - case SATISFIED: /* no action needed */ - break; - case COMPATIBLE: /* swap the two arcs, more or less */ - s = newstate(nfa); - if (NISERR()) - return 0; - cparc(nfa, con, s, a->to); /* anticipate move */ - cparc(nfa, a, from, s); - if (NISERR()) - return 0; - freearc(nfa, a); - break; - default: - assert(NOTREACHED); - break; + switch (combine(con, a)) + { + case INCOMPATIBLE: /* destroy the arc */ + freearc(nfa, a); + break; + case SATISFIED: /* no action needed */ + break; + case COMPATIBLE: /* swap the two arcs, more or less */ + s = newstate(nfa); + if (NISERR()) + return 0; + cparc(nfa, con, s, a->to); /* anticipate move */ + cparc(nfa, a, from, s); + if (NISERR()) + return 0; + freearc(nfa, a); + break; + default: + assert(NOTREACHED); + break; } } /* remaining outarcs, if any, incorporate the constraint */ moveouts(nfa, to, from); - dropstate(nfa, to); /* will free the constraint */ + dropstate(nfa, to); /* will free the constraint */ return 1; } /* * combine - constraint lands on an arc, what happens? * - * #def INCOMPATIBLE 1 // destroys arc - * #def SATISFIED 2 // constraint satisfied - * #def COMPATIBLE 3 // compatible but not satisfied yet + * #def INCOMPATIBLE 1 // destroys arc + * #def SATISFIED 2 // constraint satisfied + * #def COMPATIBLE 3 // compatible but not satisfied yet */ static int -combine(struct arc *con, - struct arc *a) +combine(struct arc * con, + struct arc * a) { -# define CA(ct,at) (((ct)<type, a->type)) { - case CA('^', PLAIN): /* newlines are handled separately */ - case CA('$', PLAIN): - return INCOMPATIBLE; - break; - case CA(AHEAD, PLAIN): /* color constraints meet colors */ - case CA(BEHIND, PLAIN): - if (con->co == a->co) - return SATISFIED; - return INCOMPATIBLE; - break; - case CA('^', '^'): /* collision, similar constraints */ - case CA('$', '$'): - case CA(AHEAD, AHEAD): - case CA(BEHIND, BEHIND): - if (con->co == a->co) /* true duplication */ - return SATISFIED; - return INCOMPATIBLE; - break; - case CA('^', BEHIND): /* collision, dissimilar constraints */ - case CA(BEHIND, '^'): - case CA('$', AHEAD): - case CA(AHEAD, '$'): - return INCOMPATIBLE; - break; - case CA('^', '$'): /* constraints passing each other */ - case CA('^', AHEAD): - case CA(BEHIND, '$'): - case CA(BEHIND, AHEAD): - case CA('$', '^'): - case CA('$', BEHIND): - case CA(AHEAD, '^'): - case CA(AHEAD, BEHIND): - case CA('^', LACON): - case CA(BEHIND, LACON): - case CA('$', LACON): - case CA(AHEAD, LACON): - return COMPATIBLE; - break; + switch (CA(con->type, a->type)) + { + case CA('^', PLAIN): /* newlines are handled separately */ + case CA('$', PLAIN): + return INCOMPATIBLE; + break; + case CA(AHEAD, PLAIN): /* color constraints meet colors */ + case CA(BEHIND, PLAIN): + if (con->co == a->co) + return SATISFIED; + return INCOMPATIBLE; + break; + case CA('^', '^'): /* collision, similar constraints */ + case CA('$', '$'): + case CA(AHEAD, AHEAD): + case CA(BEHIND, BEHIND): + if (con->co == a->co) /* true duplication */ + return SATISFIED; + return INCOMPATIBLE; + break; + case CA('^', BEHIND): /* collision, dissimilar constraints */ + case CA(BEHIND, '^'): + case CA('$', AHEAD): + case CA(AHEAD, '$'): + return INCOMPATIBLE; + break; + case CA('^', '$'): /* constraints passing each other */ + case CA('^', AHEAD): + case CA(BEHIND, '$'): + case CA(BEHIND, AHEAD): + case CA('$', '^'): + case CA('$', BEHIND): + case CA(AHEAD, '^'): + case CA(AHEAD, BEHIND): + case CA('^', LACON): + case CA(BEHIND, LACON): + case CA('$', LACON): + case CA(AHEAD, LACON): + return COMPATIBLE; + break; } assert(NOTREACHED); return INCOMPATIBLE; /* for benefit of blind compilers */ @@ -977,21 +1027,24 @@ combine(struct arc *con, * fixempties - get rid of EMPTY arcs */ static void -fixempties(struct nfa *nfa, - FILE *f) /* for debug output; NULL none */ +fixempties(struct nfa * nfa, + FILE *f) /* for debug output; NULL none */ { struct state *s; struct state *nexts; struct arc *a; struct arc *nexta; - int progress; + int progress; /* find and eliminate empties until there are no more */ - do { + do + { progress = 0; - for (s = nfa->states; s != NULL && !NISERR(); s = nexts) { + for (s = nfa->states; s != NULL && !NISERR(); s = nexts) + { nexts = s->next; - for (a = s->outs; a != NULL && !NISERR(); a = nexta) { + for (a = s->outs; a != NULL && !NISERR(); a = nexta) + { nexta = a->outchain; if (a->type == EMPTY && unempty(nfa, a)) progress = 1; @@ -1009,46 +1062,55 @@ fixempties(struct nfa *nfa, * Actually, as it stands this function always succeeds, but the return * value is kept with an eye on possible future changes. */ -static int /* 0 couldn't, 1 could */ -unempty(struct nfa *nfa, - struct arc *a) +static int /* 0 couldn't, 1 could */ +unempty(struct nfa * nfa, + struct arc * a) { struct state *from = a->from; struct state *to = a->to; - int usefrom; /* work on from, as opposed to to? */ + int usefrom; /* work on from, as opposed to to? */ assert(a->type == EMPTY); assert(from != nfa->pre && to != nfa->post); - if (from == to) { /* vacuous loop */ + if (from == to) + { /* vacuous loop */ freearc(nfa, a); return 1; } /* decide which end to work on */ - usefrom = 1; /* default: attack from */ + usefrom = 1; /* default: attack from */ if (from->nouts > to->nins) usefrom = 0; - else if (from->nouts == to->nins) { + else if (from->nouts == to->nins) + { /* decide on secondary issue: move/copy fewest arcs */ if (from->nins > to->nouts) usefrom = 0; } - + freearc(nfa, a); - if (usefrom) { - if (from->nouts == 0) { + if (usefrom) + { + if (from->nouts == 0) + { /* was the state's only outarc */ moveins(nfa, from, to); freestate(nfa, from); - } else + } + else copyins(nfa, from, to); - } else { - if (to->nins == 0) { + } + else + { + if (to->nins == 0) + { /* was the state's only inarc */ moveouts(nfa, to, from); freestate(nfa, to); - } else + } + else copyouts(nfa, to, from); } @@ -1059,17 +1121,18 @@ unempty(struct nfa *nfa, * cleanup - clean up NFA after optimizations */ static void -cleanup(struct nfa *nfa) +cleanup(struct nfa * nfa) { struct state *s; struct state *nexts; - int n; + int n; /* clear out unreachable or dead-end states */ /* use pre to mark reachable, then post to mark can-reach-post */ - markreachable(nfa, nfa->pre, (struct state *)NULL, nfa->pre); + markreachable(nfa, nfa->pre, (struct state *) NULL, nfa->pre); markcanreach(nfa, nfa->post, nfa->pre, nfa->post); - for (s = nfa->states; s != NULL; s = nexts) { + for (s = nfa->states; s != NULL; s = nexts) + { nexts = s->next; if (s->tmp != nfa->post && !s->flag) dropstate(nfa, s); @@ -1090,10 +1153,11 @@ cleanup(struct nfa *nfa) * markreachable - recursive marking of reachable states */ static void -markreachable(struct nfa *nfa, - struct state *s, - struct state *okay, /* consider only states with this mark */ - struct state *mark) /* the value to mark with */ +markreachable(struct nfa * nfa, + struct state * s, + struct state * okay, /* consider only states with this + * mark */ + struct state * mark) /* the value to mark with */ { struct arc *a; @@ -1109,10 +1173,11 @@ markreachable(struct nfa *nfa, * markcanreach - recursive marking of states which can reach here */ static void -markcanreach(struct nfa *nfa, - struct state *s, - struct state *okay, /* consider only states with this mark */ - struct state *mark) /* the value to mark with */ +markcanreach(struct nfa * nfa, + struct state * s, + struct state * okay, /* consider only states with this + * mark */ + struct state * mark) /* the value to mark with */ { struct arc *a; @@ -1127,8 +1192,8 @@ markcanreach(struct nfa *nfa, /* * analyze - ascertain potentially-useful facts about an optimized NFA */ -static long /* re_info bits to be ORed in */ -analyze(struct nfa *nfa) +static long /* re_info bits to be ORed in */ +analyze(struct nfa * nfa) { struct arc *a; struct arc *aa; @@ -1146,29 +1211,31 @@ analyze(struct nfa *nfa) * compact - compact an NFA */ static void -compact(struct nfa *nfa, - struct cnfa *cnfa) +compact(struct nfa * nfa, + struct cnfa * cnfa) { struct state *s; struct arc *a; - size_t nstates; - size_t narcs; + size_t nstates; + size_t narcs; struct carc *ca; struct carc *first; - assert (!NISERR()); + assert(!NISERR()); nstates = 0; narcs = 0; - for (s = nfa->states; s != NULL; s = s->next) { + for (s = nfa->states; s != NULL; s = s->next) + { nstates++; narcs += 1 + s->nouts + 1; /* 1 as a fake for flags, nouts for arcs, 1 as endmarker */ } - cnfa->states = (struct carc **)MALLOC(nstates * sizeof(struct carc *)); - cnfa->arcs = (struct carc *)MALLOC(narcs * sizeof(struct carc)); - if (cnfa->states == NULL || cnfa->arcs == NULL) { + cnfa->states = (struct carc **) MALLOC(nstates * sizeof(struct carc *)); + cnfa->arcs = (struct carc *) MALLOC(narcs * sizeof(struct carc)); + if (cnfa->states == NULL || cnfa->arcs == NULL) + { if (cnfa->states != NULL) FREE(cnfa->states); if (cnfa->arcs != NULL) @@ -1187,31 +1254,33 @@ compact(struct nfa *nfa, cnfa->flags = 0; ca = cnfa->arcs; - for (s = nfa->states; s != NULL; s = s->next) { - assert((size_t)s->no < nstates); + for (s = nfa->states; s != NULL; s = s->next) + { + assert((size_t) s->no < nstates); cnfa->states[s->no] = ca; - ca->co = 0; /* clear and skip flags "arc" */ + ca->co = 0; /* clear and skip flags "arc" */ ca++; first = ca; for (a = s->outs; a != NULL; a = a->outchain) - switch (a->type) { - case PLAIN: - ca->co = a->co; - ca->to = a->to->no; - ca++; - break; - case LACON: - assert(s->no != cnfa->pre); - ca->co = (color)(cnfa->ncolors + a->co); - ca->to = a->to->no; - ca++; - cnfa->flags |= HASLACONS; - break; - default: - assert(NOTREACHED); - break; + switch (a->type) + { + case PLAIN: + ca->co = a->co; + ca->to = a->to->no; + ca++; + break; + case LACON: + assert(s->no != cnfa->pre); + ca->co = (color) (cnfa->ncolors + a->co); + ca->to = a->to->no; + ca++; + cnfa->flags |= HASLACONS; + break; + default: + assert(NOTREACHED); + break; } - carcsort(first, ca-1); + carcsort(first, ca - 1); ca->co = COLORLESS; ca->to = 0; ca++; @@ -1232,8 +1301,8 @@ compact(struct nfa *nfa, * you're in real trouble anyway. */ static void -carcsort(struct carc *first, - struct carc *last) +carcsort(struct carc * first, + struct carc * last) { struct carc *p; struct carc *q; @@ -1245,7 +1314,8 @@ carcsort(struct carc *first, for (p = first; p <= last; p++) for (q = p; q <= last; q++) if (p->co > q->co || - (p->co == q->co && p->to > q->to)) { + (p->co == q->co && p->to > q->to)) + { assert(p != q); tmp = *p; *p = *q; @@ -1257,9 +1327,9 @@ carcsort(struct carc *first, * freecnfa - free a compacted NFA */ static void -freecnfa(struct cnfa *cnfa) +freecnfa(struct cnfa * cnfa) { - assert(cnfa->nstates != 0); /* not empty already */ + assert(cnfa->nstates != 0); /* not empty already */ cnfa->nstates = 0; FREE(cnfa->states); FREE(cnfa->arcs); @@ -1269,7 +1339,7 @@ freecnfa(struct cnfa *cnfa) * dumpnfa - dump an NFA in human-readable form */ static void -dumpnfa(struct nfa *nfa, +dumpnfa(struct nfa * nfa, FILE *f) { #ifdef REG_DEBUG @@ -1277,13 +1347,13 @@ dumpnfa(struct nfa *nfa, fprintf(f, "pre %d, post %d", nfa->pre->no, nfa->post->no); if (nfa->bos[0] != COLORLESS) - fprintf(f, ", bos [%ld]", (long)nfa->bos[0]); + fprintf(f, ", bos [%ld]", (long) nfa->bos[0]); if (nfa->bos[1] != COLORLESS) - fprintf(f, ", bol [%ld]", (long)nfa->bos[1]); + fprintf(f, ", bol [%ld]", (long) nfa->bos[1]); if (nfa->eos[0] != COLORLESS) - fprintf(f, ", eos [%ld]", (long)nfa->eos[0]); + fprintf(f, ", eos [%ld]", (long) nfa->eos[0]); if (nfa->eos[1] != COLORLESS) - fprintf(f, ", eol [%ld]", (long)nfa->eos[1]); + fprintf(f, ", eol [%ld]", (long) nfa->eos[1]); fprintf(f, "\n"); for (s = nfa->states; s != NULL; s = s->next) dumpstate(s, f); @@ -1293,19 +1363,19 @@ dumpnfa(struct nfa *nfa, #endif } -#ifdef REG_DEBUG /* subordinates of dumpnfa */ +#ifdef REG_DEBUG /* subordinates of dumpnfa */ /* * dumpstate - dump an NFA state in human-readable form */ static void -dumpstate(struct state *s, +dumpstate(struct state * s, FILE *f) { struct arc *a; fprintf(f, "%d%s%c", s->no, (s->tmp != NULL) ? "T" : "", - (s->flag) ? s->flag : '.'); + (s->flag) ? s->flag : '.'); if (s->prev != NULL && s->prev->next != s) fprintf(f, "\tstate chain bad\n"); if (s->nouts == 0) @@ -1313,7 +1383,8 @@ dumpstate(struct state *s, else dumparcs(s, f); fflush(f); - for (a = s->ins; a != NULL; a = a->inchain) { + for (a = s->ins; a != NULL; a = a->inchain) + { if (a->to != s) fprintf(f, "\tlink from %d to %d on %d's in-chain\n", a->from->no, a->to->no, s->no); @@ -1324,10 +1395,10 @@ dumpstate(struct state *s, * dumparcs - dump out-arcs in human-readable form */ static void -dumparcs(struct state *s, +dumparcs(struct state * s, FILE *f) { - int pos; + int pos; assert(s->nouts > 0); /* printing arcs in reverse order is usually clearer */ @@ -1339,19 +1410,21 @@ dumparcs(struct state *s, /* * dumprarcs - dump remaining outarcs, recursively, in reverse order */ -static int /* resulting print position */ -dumprarcs(struct arc *a, - struct state *s, +static int /* resulting print position */ +dumprarcs(struct arc * a, + struct state * s, FILE *f, - int pos) /* initial print position */ + int pos) /* initial print position */ { if (a->outchain != NULL) pos = dumprarcs(a->outchain, s, f, pos); dumparc(a, s, f); - if (pos == 5) { + if (pos == 5) + { fprintf(f, "\n"); pos = 1; - } else + } + else pos++; return pos; } @@ -1360,83 +1433,85 @@ dumprarcs(struct arc *a, * dumparc - dump one outarc in readable form, including prefixing tab */ static void -dumparc(struct arc *a, - struct state *s, +dumparc(struct arc * a, + struct state * s, FILE *f) { struct arc *aa; struct arcbatch *ab; fprintf(f, "\t"); - switch (a->type) { - case PLAIN: - fprintf(f, "[%ld]", (long)a->co); - break; - case AHEAD: - fprintf(f, ">%ld>", (long)a->co); - break; - case BEHIND: - fprintf(f, "<%ld<", (long)a->co); - break; - case LACON: - fprintf(f, ":%ld:", (long)a->co); - break; - case '^': - case '$': - fprintf(f, "%c%d", a->type, (int)a->co); - break; - case EMPTY: - break; - default: - fprintf(f, "0x%x/0%lo", a->type, (long)a->co); - break; + switch (a->type) + { + case PLAIN: + fprintf(f, "[%ld]", (long) a->co); + break; + case AHEAD: + fprintf(f, ">%ld>", (long) a->co); + break; + case BEHIND: + fprintf(f, "<%ld<", (long) a->co); + break; + case LACON: + fprintf(f, ":%ld:", (long) a->co); + break; + case '^': + case '$': + fprintf(f, "%c%d", a->type, (int) a->co); + break; + case EMPTY: + break; + default: + fprintf(f, "0x%x/0%lo", a->type, (long) a->co); + break; } if (a->from != s) fprintf(f, "?%d?", a->from->no); - for (ab = &a->from->oas; ab != NULL; ab = ab->next) { + for (ab = &a->from->oas; ab != NULL; ab = ab->next) + { for (aa = &ab->a[0]; aa < &ab->a[ABSIZE]; aa++) if (aa == a) - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ if (aa < &ab->a[ABSIZE]) /* propagate break */ - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ } if (ab == NULL) - fprintf(f, "?!?"); /* not in allocated space */ + fprintf(f, "?!?"); /* not in allocated space */ fprintf(f, "->"); - if (a->to == NULL) { + if (a->to == NULL) + { fprintf(f, "NULL"); return; } fprintf(f, "%d", a->to->no); for (aa = a->to->ins; aa != NULL; aa = aa->inchain) if (aa == a) - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ if (aa == NULL) - fprintf(f, "?!?"); /* missing from in-chain */ + fprintf(f, "?!?"); /* missing from in-chain */ } - -#endif /* REG_DEBUG */ +#endif /* REG_DEBUG */ /* * dumpcnfa - dump a compacted NFA in human-readable form */ #ifdef REG_DEBUG static void -dumpcnfa(struct cnfa *cnfa, +dumpcnfa(struct cnfa * cnfa, FILE *f) { - int st; + int st; fprintf(f, "pre %d, post %d", cnfa->pre, cnfa->post); if (cnfa->bos[0] != COLORLESS) - fprintf(f, ", bos [%ld]", (long)cnfa->bos[0]); + fprintf(f, ", bos [%ld]", (long) cnfa->bos[0]); if (cnfa->bos[1] != COLORLESS) - fprintf(f, ", bol [%ld]", (long)cnfa->bos[1]); + fprintf(f, ", bol [%ld]", (long) cnfa->bos[1]); if (cnfa->eos[0] != COLORLESS) - fprintf(f, ", eos [%ld]", (long)cnfa->eos[0]); + fprintf(f, ", eos [%ld]", (long) cnfa->eos[0]); if (cnfa->eos[1] != COLORLESS) - fprintf(f, ", eol [%ld]", (long)cnfa->eos[1]); - if (cnfa->flags&HASLACONS) + fprintf(f, ", eol [%ld]", (long) cnfa->eos[1]); + if (cnfa->flags & HASLACONS) fprintf(f, ", haslacons"); fprintf(f, "\n"); for (st = 0; st < cnfa->nstates; st++) @@ -1445,32 +1520,35 @@ dumpcnfa(struct cnfa *cnfa, } #endif -#ifdef REG_DEBUG /* subordinates of dumpcnfa */ +#ifdef REG_DEBUG /* subordinates of dumpcnfa */ /* * dumpcstate - dump a compacted-NFA state in human-readable form */ static void dumpcstate(int st, - struct carc *ca, - struct cnfa *cnfa, + struct carc * ca, + struct cnfa * cnfa, FILE *f) { - int i; - int pos; + int i; + int pos; fprintf(f, "%d%s", st, (ca[0].co) ? ":" : "."); pos = 1; - for (i = 1; ca[i].co != COLORLESS; i++) { + for (i = 1; ca[i].co != COLORLESS; i++) + { if (ca[i].co < cnfa->ncolors) - fprintf(f, "\t[%ld]->%d", (long)ca[i].co, ca[i].to); + fprintf(f, "\t[%ld]->%d", (long) ca[i].co, ca[i].to); else - fprintf(f, "\t:%ld:->%d", (long)ca[i].co-cnfa->ncolors, - ca[i].to); - if (pos == 5) { + fprintf(f, "\t:%ld:->%d", (long) ca[i].co - cnfa->ncolors, + ca[i].to); + if (pos == 5) + { fprintf(f, "\n"); pos = 1; - } else + } + else pos++; } if (i == 1 || pos != 1) @@ -1478,4 +1556,4 @@ dumpcstate(int st, fflush(f); } -#endif /* REG_DEBUG */ +#endif /* REG_DEBUG */ diff --git a/src/backend/regex/regcomp.c b/src/backend/regex/regcomp.c index 099a1872a8..58af64539d 100644 --- a/src/backend/regex/regcomp.c +++ b/src/backend/regex/regcomp.c @@ -2,21 +2,21 @@ * re_*comp and friends - compile REs * This file #includes several others (see the bottom). * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -28,7 +28,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regcomp.c,v 1.36 2003/02/05 17:41:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regcomp.c,v 1.37 2003/08/04 00:43:21 momjian Exp $ * */ @@ -38,243 +38,252 @@ * forward declarations, up here so forward datatypes etc. are defined early */ /* === regcomp.c === */ -static void moresubs (struct vars *, int); -static int freev (struct vars *, int); -static void makesearch (struct vars *, struct nfa *); -static struct subre *parse (struct vars *, int, int, struct state *, struct state *); -static struct subre *parsebranch (struct vars *, int, int, struct state *, struct state *, int); -static void parseqatom (struct vars *, int, int, struct state *, struct state *, struct subre *); -static void nonword (struct vars *, int, struct state *, struct state *); -static void word (struct vars *, int, struct state *, struct state *); -static int scannum (struct vars *); -static void repeat (struct vars *, struct state *, struct state *, int, int); -static void bracket (struct vars *, struct state *, struct state *); -static void cbracket (struct vars *, struct state *, struct state *); -static void brackpart (struct vars *, struct state *, struct state *); -static chr *scanplain (struct vars *); -static void leaders (struct vars *, struct cvec *); -static void onechr (struct vars *, chr, struct state *, struct state *); -static void dovec (struct vars *, struct cvec *, struct state *, struct state *); -static celt nextleader (struct vars *, chr, chr); -static void wordchrs (struct vars *); -static struct subre *subre (struct vars *, int, int, struct state *, struct state *); -static void freesubre (struct vars *, struct subre *); -static void freesrnode (struct vars *, struct subre *); -static void optst (struct vars *, struct subre *); -static int numst (struct subre *, int); -static void markst (struct subre *); -static void cleanst (struct vars *); -static long nfatree (struct vars *, struct subre *, FILE *); -static long nfanode (struct vars *, struct subre *, FILE *); -static int newlacon (struct vars *, struct state *, struct state *, int); -static void freelacons (struct subre *, int); -static void rfree (regex_t *); +static void moresubs(struct vars *, int); +static int freev(struct vars *, int); +static void makesearch(struct vars *, struct nfa *); +static struct subre *parse(struct vars *, int, int, struct state *, struct state *); +static struct subre *parsebranch(struct vars *, int, int, struct state *, struct state *, int); +static void parseqatom(struct vars *, int, int, struct state *, struct state *, struct subre *); +static void nonword(struct vars *, int, struct state *, struct state *); +static void word(struct vars *, int, struct state *, struct state *); +static int scannum(struct vars *); +static void repeat(struct vars *, struct state *, struct state *, int, int); +static void bracket(struct vars *, struct state *, struct state *); +static void cbracket(struct vars *, struct state *, struct state *); +static void brackpart(struct vars *, struct state *, struct state *); +static chr *scanplain(struct vars *); +static void leaders(struct vars *, struct cvec *); +static void onechr(struct vars *, chr, struct state *, struct state *); +static void dovec(struct vars *, struct cvec *, struct state *, struct state *); +static celt nextleader(struct vars *, chr, chr); +static void wordchrs(struct vars *); +static struct subre *subre(struct vars *, int, int, struct state *, struct state *); +static void freesubre(struct vars *, struct subre *); +static void freesrnode(struct vars *, struct subre *); +static void optst(struct vars *, struct subre *); +static int numst(struct subre *, int); +static void markst(struct subre *); +static void cleanst(struct vars *); +static long nfatree(struct vars *, struct subre *, FILE *); +static long nfanode(struct vars *, struct subre *, FILE *); +static int newlacon(struct vars *, struct state *, struct state *, int); +static void freelacons(struct subre *, int); +static void rfree(regex_t *); + #ifdef REG_DEBUG -static void dump (regex_t *, FILE *); -static void dumpst (struct subre *, FILE *, int); -static void stdump (struct subre *, FILE *, int); -static char *stid (struct subre *, char *, size_t); +static void dump(regex_t *, FILE *); +static void dumpst(struct subre *, FILE *, int); +static void stdump(struct subre *, FILE *, int); +static char *stid(struct subre *, char *, size_t); #endif /* === regc_lex.c === */ -static void lexstart (struct vars *); -static void prefixes (struct vars *); -static void lexnest (struct vars *, chr *, chr *); -static void lexword (struct vars *); -static int next (struct vars *); -static int lexescape (struct vars *); -static chr lexdigits (struct vars *, int, int, int); -static int brenext (struct vars *, chr); -static void skip (struct vars *); -static chr newline (void); -static chr chrnamed (struct vars *, chr *, chr *, chr); +static void lexstart(struct vars *); +static void prefixes(struct vars *); +static void lexnest(struct vars *, chr *, chr *); +static void lexword(struct vars *); +static int next(struct vars *); +static int lexescape(struct vars *); +static chr lexdigits(struct vars *, int, int, int); +static int brenext(struct vars *, chr); +static void skip(struct vars *); +static chr newline(void); +static chr chrnamed(struct vars *, chr *, chr *, chr); + /* === regc_color.c === */ -static void initcm (struct vars *, struct colormap *); -static void freecm (struct colormap *); -static void cmtreefree (struct colormap *, union tree *, int); -static color setcolor (struct colormap *, chr, pcolor); -static color maxcolor (struct colormap *); -static color newcolor (struct colormap *); -static void freecolor (struct colormap *, pcolor); -static color pseudocolor (struct colormap *); -static color subcolor (struct colormap *, chr c); -static color newsub (struct colormap *, pcolor); -static void subrange (struct vars *, chr, chr, struct state *, struct state *); -static void subblock (struct vars *, chr, struct state *, struct state *); -static void okcolors (struct nfa *, struct colormap *); -static void colorchain (struct colormap *, struct arc *); -static void uncolorchain (struct colormap *, struct arc *); -static int singleton (struct colormap *, chr c); -static void rainbow (struct nfa *, struct colormap *, int, pcolor, struct state *, struct state *); -static void colorcomplement (struct nfa *, struct colormap *, int, struct state *, struct state *, struct state *); +static void initcm(struct vars *, struct colormap *); +static void freecm(struct colormap *); +static void cmtreefree(struct colormap *, union tree *, int); +static color setcolor(struct colormap *, chr, pcolor); +static color maxcolor(struct colormap *); +static color newcolor(struct colormap *); +static void freecolor(struct colormap *, pcolor); +static color pseudocolor(struct colormap *); +static color subcolor(struct colormap *, chr c); +static color newsub(struct colormap *, pcolor); +static void subrange(struct vars *, chr, chr, struct state *, struct state *); +static void subblock(struct vars *, chr, struct state *, struct state *); +static void okcolors(struct nfa *, struct colormap *); +static void colorchain(struct colormap *, struct arc *); +static void uncolorchain(struct colormap *, struct arc *); +static int singleton(struct colormap *, chr c); +static void rainbow(struct nfa *, struct colormap *, int, pcolor, struct state *, struct state *); +static void colorcomplement(struct nfa *, struct colormap *, int, struct state *, struct state *, struct state *); + #ifdef REG_DEBUG -static void dumpcolors (struct colormap *, FILE *); -static void fillcheck (struct colormap *, union tree *, int, FILE *); -static void dumpchr (chr, FILE *); +static void dumpcolors(struct colormap *, FILE *); +static void fillcheck(struct colormap *, union tree *, int, FILE *); +static void dumpchr(chr, FILE *); #endif /* === regc_nfa.c === */ -static struct nfa *newnfa (struct vars *, struct colormap *, struct nfa *); -static void freenfa (struct nfa *); -static struct state *newstate (struct nfa *); -static struct state *newfstate (struct nfa *, int flag); -static void dropstate (struct nfa *, struct state *); -static void freestate (struct nfa *, struct state *); -static void destroystate (struct nfa *, struct state *); -static void newarc (struct nfa *, int, pcolor, struct state *, struct state *); -static struct arc *allocarc (struct nfa *, struct state *); -static void freearc (struct nfa *, struct arc *); -static struct arc *findarc (struct state *, int, pcolor); -static void cparc (struct nfa *, struct arc *, struct state *, struct state *); -static void moveins (struct nfa *, struct state *, struct state *); -static void copyins (struct nfa *, struct state *, struct state *); -static void moveouts (struct nfa *, struct state *, struct state *); -static void copyouts (struct nfa *, struct state *, struct state *); -static void cloneouts (struct nfa *, struct state *, struct state *, struct state *, int); -static void delsub (struct nfa *, struct state *, struct state *); -static void deltraverse (struct nfa *, struct state *, struct state *); -static void dupnfa (struct nfa *, struct state *, struct state *, struct state *, struct state *); -static void duptraverse (struct nfa *, struct state *, struct state *); -static void cleartraverse (struct nfa *, struct state *); -static void specialcolors (struct nfa *); -static long optimize (struct nfa *, FILE *); -static void pullback (struct nfa *, FILE *); -static int pull (struct nfa *, struct arc *); -static void pushfwd (struct nfa *, FILE *); -static int push (struct nfa *, struct arc *); -#define INCOMPATIBLE 1 /* destroys arc */ -#define SATISFIED 2 /* constraint satisfied */ -#define COMPATIBLE 3 /* compatible but not satisfied yet */ -static int combine (struct arc *, struct arc *); -static void fixempties (struct nfa *, FILE *); -static int unempty (struct nfa *, struct arc *); -static void cleanup (struct nfa *); -static void markreachable (struct nfa *, struct state *, struct state *, struct state *); -static void markcanreach (struct nfa *, struct state *, struct state *, struct state *); -static long analyze (struct nfa *); -static void compact (struct nfa *, struct cnfa *); -static void carcsort (struct carc *, struct carc *); -static void freecnfa (struct cnfa *); -static void dumpnfa (struct nfa *, FILE *); +static struct nfa *newnfa(struct vars *, struct colormap *, struct nfa *); +static void freenfa(struct nfa *); +static struct state *newstate(struct nfa *); +static struct state *newfstate(struct nfa *, int flag); +static void dropstate(struct nfa *, struct state *); +static void freestate(struct nfa *, struct state *); +static void destroystate(struct nfa *, struct state *); +static void newarc(struct nfa *, int, pcolor, struct state *, struct state *); +static struct arc *allocarc(struct nfa *, struct state *); +static void freearc(struct nfa *, struct arc *); +static struct arc *findarc(struct state *, int, pcolor); +static void cparc(struct nfa *, struct arc *, struct state *, struct state *); +static void moveins(struct nfa *, struct state *, struct state *); +static void copyins(struct nfa *, struct state *, struct state *); +static void moveouts(struct nfa *, struct state *, struct state *); +static void copyouts(struct nfa *, struct state *, struct state *); +static void cloneouts(struct nfa *, struct state *, struct state *, struct state *, int); +static void delsub(struct nfa *, struct state *, struct state *); +static void deltraverse(struct nfa *, struct state *, struct state *); +static void dupnfa(struct nfa *, struct state *, struct state *, struct state *, struct state *); +static void duptraverse(struct nfa *, struct state *, struct state *); +static void cleartraverse(struct nfa *, struct state *); +static void specialcolors(struct nfa *); +static long optimize(struct nfa *, FILE *); +static void pullback(struct nfa *, FILE *); +static int pull(struct nfa *, struct arc *); +static void pushfwd(struct nfa *, FILE *); +static int push(struct nfa *, struct arc *); + +#define INCOMPATIBLE 1 /* destroys arc */ +#define SATISFIED 2 /* constraint satisfied */ +#define COMPATIBLE 3 /* compatible but not satisfied yet */ +static int combine(struct arc *, struct arc *); +static void fixempties(struct nfa *, FILE *); +static int unempty(struct nfa *, struct arc *); +static void cleanup(struct nfa *); +static void markreachable(struct nfa *, struct state *, struct state *, struct state *); +static void markcanreach(struct nfa *, struct state *, struct state *, struct state *); +static long analyze(struct nfa *); +static void compact(struct nfa *, struct cnfa *); +static void carcsort(struct carc *, struct carc *); +static void freecnfa(struct cnfa *); +static void dumpnfa(struct nfa *, FILE *); + #ifdef REG_DEBUG -static void dumpstate (struct state *, FILE *); -static void dumparcs (struct state *, FILE *); -static int dumprarcs (struct arc *, struct state *, FILE *, int); -static void dumparc (struct arc *, struct state *, FILE *); -static void dumpcnfa (struct cnfa *, FILE *); -static void dumpcstate (int, struct carc *, struct cnfa *, FILE *); +static void dumpstate(struct state *, FILE *); +static void dumparcs(struct state *, FILE *); +static int dumprarcs(struct arc *, struct state *, FILE *, int); +static void dumparc(struct arc *, struct state *, FILE *); +static void dumpcnfa(struct cnfa *, FILE *); +static void dumpcstate(int, struct carc *, struct cnfa *, FILE *); #endif /* === regc_cvec.c === */ -static struct cvec *newcvec (int, int, int); -static struct cvec *clearcvec (struct cvec *); -static void addchr (struct cvec *, chr); -static void addrange (struct cvec *, chr, chr); -static void addmcce (struct cvec *, chr *, chr *); -static int haschr (struct cvec *, chr); -static struct cvec *getcvec (struct vars *, int, int, int); -static void freecvec (struct cvec *); +static struct cvec *newcvec(int, int, int); +static struct cvec *clearcvec(struct cvec *); +static void addchr(struct cvec *, chr); +static void addrange(struct cvec *, chr, chr); +static void addmcce(struct cvec *, chr *, chr *); +static int haschr(struct cvec *, chr); +static struct cvec *getcvec(struct vars *, int, int, int); +static void freecvec(struct cvec *); + /* === regc_locale.c === */ -static int pg_isdigit(pg_wchar c); -static int pg_isalpha(pg_wchar c); -static int pg_isalnum(pg_wchar c); -static int pg_isupper(pg_wchar c); -static int pg_islower(pg_wchar c); -static int pg_isgraph(pg_wchar c); -static int pg_ispunct(pg_wchar c); -static int pg_isspace(pg_wchar c); +static int pg_isdigit(pg_wchar c); +static int pg_isalpha(pg_wchar c); +static int pg_isalnum(pg_wchar c); +static int pg_isupper(pg_wchar c); +static int pg_islower(pg_wchar c); +static int pg_isgraph(pg_wchar c); +static int pg_ispunct(pg_wchar c); +static int pg_isspace(pg_wchar c); static pg_wchar pg_toupper(pg_wchar c); static pg_wchar pg_tolower(pg_wchar c); -static int nmcces (struct vars *); -static int nleaders (struct vars *); -static struct cvec *allmcces (struct vars *, struct cvec *); -static celt element (struct vars *, chr *, chr *); -static struct cvec *range (struct vars *, celt, celt, int); -static int before (celt, celt); -static struct cvec *eclass (struct vars *, celt, int); -static struct cvec *cclass (struct vars *, chr *, chr *, int); -static struct cvec *allcases (struct vars *, chr); -static int cmp (const chr *, const chr *, size_t); -static int casecmp (const chr *, const chr *, size_t); +static int nmcces(struct vars *); +static int nleaders(struct vars *); +static struct cvec *allmcces(struct vars *, struct cvec *); +static celt element(struct vars *, chr *, chr *); +static struct cvec *range(struct vars *, celt, celt, int); +static int before(celt, celt); +static struct cvec *eclass(struct vars *, celt, int); +static struct cvec *cclass(struct vars *, chr *, chr *, int); +static struct cvec *allcases(struct vars *, chr); +static int cmp(const chr *, const chr *, size_t); +static int casecmp(const chr *, const chr *, size_t); /* internal variables, bundled for easy passing around */ -struct vars { - regex_t *re; - chr *now; /* scan pointer into string */ - chr *stop; /* end of string */ - chr *savenow; /* saved now and stop for "subroutine call" */ - chr *savestop; - int err; /* error code (0 if none) */ - int cflags; /* copy of compile flags */ - int lasttype; /* type of previous token */ - int nexttype; /* type of next token */ - chr nextvalue; /* value (if any) of next token */ - int lexcon; /* lexical context type (see lex.c) */ - int nsubexp; /* subexpression count */ - struct subre **subs; /* subRE pointer vector */ - size_t nsubs; /* length of vector */ +struct vars +{ + regex_t *re; + chr *now; /* scan pointer into string */ + chr *stop; /* end of string */ + chr *savenow; /* saved now and stop for "subroutine + * call" */ + chr *savestop; + int err; /* error code (0 if none) */ + int cflags; /* copy of compile flags */ + int lasttype; /* type of previous token */ + int nexttype; /* type of next token */ + chr nextvalue; /* value (if any) of next token */ + int lexcon; /* lexical context type (see lex.c) */ + int nsubexp; /* subexpression count */ + struct subre **subs; /* subRE pointer vector */ + size_t nsubs; /* length of vector */ struct subre *sub10[10]; /* initial vector, enough for most */ - struct nfa *nfa; /* the NFA */ - struct colormap *cm; /* character color map */ - color nlcolor; /* color of newline */ - struct state *wordchrs; /* state in nfa holding word-char outarcs */ - struct subre *tree; /* subexpression tree */ + struct nfa *nfa; /* the NFA */ + struct colormap *cm; /* character color map */ + color nlcolor; /* color of newline */ + struct state *wordchrs; /* state in nfa holding word-char outarcs */ + struct subre *tree; /* subexpression tree */ struct subre *treechain; /* all tree nodes allocated */ struct subre *treefree; /* any free tree nodes */ - int ntree; /* number of tree nodes */ - struct cvec *cv; /* interface cvec */ - struct cvec *cv2; /* utility cvec */ - struct cvec *mcces; /* collating-element information */ -# define ISCELEADER(v,c) (v->mcces != NULL && haschr(v->mcces, (c))) + int ntree; /* number of tree nodes */ + struct cvec *cv; /* interface cvec */ + struct cvec *cv2; /* utility cvec */ + struct cvec *mcces; /* collating-element information */ +#define ISCELEADER(v,c) (v->mcces != NULL && haschr(v->mcces, (c))) struct state *mccepbegin; /* in nfa, start of MCCE prototypes */ - struct state *mccepend; /* in nfa, end of MCCE prototypes */ - struct subre *lacons; /* lookahead-constraint vector */ - int nlacons; /* size of lacons */ + struct state *mccepend; /* in nfa, end of MCCE prototypes */ + struct subre *lacons; /* lookahead-constraint vector */ + int nlacons; /* size of lacons */ }; /* parsing macros; most know that `v' is the struct vars pointer */ -#define NEXT() (next(v)) /* advance by one token */ -#define SEE(t) (v->nexttype == (t)) /* is next token this? */ -#define EAT(t) (SEE(t) && next(v)) /* if next is this, swallow it */ -#define VISERR(vv) ((vv)->err != 0) /* have we seen an error yet? */ -#define ISERR() VISERR(v) -#define VERR(vv,e) ((vv)->nexttype = EOS, ((vv)->err) ? (vv)->err :\ +#define NEXT() (next(v)) /* advance by one token */ +#define SEE(t) (v->nexttype == (t)) /* is next token this? */ +#define EAT(t) (SEE(t) && next(v)) /* if next is this, swallow it */ +#define VISERR(vv) ((vv)->err != 0) /* have we seen an error yet? */ +#define ISERR() VISERR(v) +#define VERR(vv,e) ((vv)->nexttype = EOS, ((vv)->err) ? (vv)->err :\ ((vv)->err = (e))) -#define ERR(e) VERR(v, e) /* record an error */ -#define NOERR() {if (ISERR()) return;} /* if error seen, return */ -#define NOERRN() {if (ISERR()) return NULL;} /* NOERR with retval */ -#define NOERRZ() {if (ISERR()) return 0;} /* NOERR with retval */ -#define INSIST(c, e) ((c) ? 0 : ERR(e)) /* if condition false, error */ -#define NOTE(b) (v->re->re_info |= (b)) /* note visible condition */ -#define EMPTYARC(x, y) newarc(v->nfa, EMPTY, 0, x, y) +#define ERR(e) VERR(v, e) /* record an error */ +#define NOERR() {if (ISERR()) return;} /* if error seen, return */ +#define NOERRN() {if (ISERR()) return NULL;} /* NOERR with retval */ +#define NOERRZ() {if (ISERR()) return 0;} /* NOERR with retval */ +#define INSIST(c, e) ((c) ? 0 : ERR(e)) /* if condition false, + * error */ +#define NOTE(b) (v->re->re_info |= (b)) /* note visible condition */ +#define EMPTYARC(x, y) newarc(v->nfa, EMPTY, 0, x, y) /* token type codes, some also used as NFA arc types */ -#define EMPTY 'n' /* no token present */ -#define EOS 'e' /* end of string */ -#define PLAIN 'p' /* ordinary character */ -#define DIGIT 'd' /* digit (in bound) */ -#define BACKREF 'b' /* back reference */ -#define COLLEL 'I' /* start of [. */ -#define ECLASS 'E' /* start of [= */ -#define CCLASS 'C' /* start of [: */ -#define END 'X' /* end of [. [= [: */ -#define RANGE 'R' /* - within [] which might be range delim. */ -#define LACON 'L' /* lookahead constraint subRE */ -#define AHEAD 'a' /* color-lookahead arc */ -#define BEHIND 'r' /* color-lookbehind arc */ -#define WBDRY 'w' /* word boundary constraint */ -#define NWBDRY 'W' /* non-word-boundary constraint */ -#define SBEGIN 'A' /* beginning of string (even if not BOL) */ -#define SEND 'Z' /* end of string (even if not EOL) */ -#define PREFER 'P' /* length preference */ +#define EMPTY 'n' /* no token present */ +#define EOS 'e' /* end of string */ +#define PLAIN 'p' /* ordinary character */ +#define DIGIT 'd' /* digit (in bound) */ +#define BACKREF 'b' /* back reference */ +#define COLLEL 'I' /* start of [. */ +#define ECLASS 'E' /* start of [= */ +#define CCLASS 'C' /* start of [: */ +#define END 'X' /* end of [. [= [: */ +#define RANGE 'R' /* - within [] which might be range delim. */ +#define LACON 'L' /* lookahead constraint subRE */ +#define AHEAD 'a' /* color-lookahead arc */ +#define BEHIND 'r' /* color-lookbehind arc */ +#define WBDRY 'w' /* word boundary constraint */ +#define NWBDRY 'W' /* non-word-boundary constraint */ +#define SBEGIN 'A' /* beginning of string (even if not BOL) */ +#define SEND 'Z' /* end of string (even if not EOL) */ +#define PREFER 'P' /* length preference */ /* is an arc colored, and hence on a color chain? */ -#define COLORED(a) ((a)->type == PLAIN || (a)->type == AHEAD || \ +#define COLORED(a) ((a)->type == PLAIN || (a)->type == AHEAD || \ (a)->type == BEHIND) /* static function list */ static struct fns functions = { - rfree, /* regfree insides */ + rfree, /* regfree insides */ }; @@ -284,36 +293,38 @@ static struct fns functions = { */ int pg_regcomp(regex_t *re, - const chr *string, + const chr * string, size_t len, int flags) { struct vars var; struct vars *v = &var; struct guts *g; - int i; - size_t j; + int i; + size_t j; + #ifdef REG_DEBUG - FILE *debug = (flags®_PROGRESS) ? stdout : (FILE *)NULL; + FILE *debug = (flags & REG_PROGRESS) ? stdout : (FILE *) NULL; + #else - FILE *debug = (FILE *) NULL; + FILE *debug = (FILE *) NULL; #endif -# define CNOERR() { if (ISERR()) return freev(v, v->err); } +#define CNOERR() { if (ISERR()) return freev(v, v->err); } /* sanity checks */ if (re == NULL || string == NULL) return REG_INVARG; - if ((flags®_QUOTE) && - (flags&(REG_ADVANCED|REG_EXPANDED|REG_NEWLINE))) + if ((flags & REG_QUOTE) && + (flags & (REG_ADVANCED | REG_EXPANDED | REG_NEWLINE))) return REG_INVARG; - if (!(flags®_EXTENDED) && (flags®_ADVF)) + if (!(flags & REG_EXTENDED) && (flags & REG_ADVF)) return REG_INVARG; /* initial setup (after which freev() is callable) */ v->re = re; - v->now = (chr *)string; + v->now = (chr *) string; v->stop = v->now + len; v->savenow = v->savestop = NULL; v->err = 0; @@ -336,7 +347,7 @@ pg_regcomp(regex_t *re, v->lacons = NULL; v->nlacons = 0; re->re_magic = REMAGIC; - re->re_info = 0; /* bits get set during parse */ + re->re_info = 0; /* bits get set during parse */ re->re_csize = sizeof(chr); re->re_guts = NULL; re->re_fns = VS(&functions); @@ -345,38 +356,40 @@ pg_regcomp(regex_t *re, re->re_guts = VS(MALLOC(sizeof(struct guts))); if (re->re_guts == NULL) return freev(v, REG_ESPACE); - g = (struct guts *)re->re_guts; + g = (struct guts *) re->re_guts; g->tree = NULL; initcm(v, &g->cmap); v->cm = &g->cmap; g->lacons = NULL; g->nlacons = 0; ZAPCNFA(g->search); - v->nfa = newnfa(v, v->cm, (struct nfa *)NULL); + v->nfa = newnfa(v, v->cm, (struct nfa *) NULL); CNOERR(); v->cv = newcvec(100, 20, 10); if (v->cv == NULL) return freev(v, REG_ESPACE); i = nmcces(v); - if (i > 0) { + if (i > 0) + { v->mcces = newcvec(nleaders(v), 0, i); CNOERR(); v->mcces = allmcces(v, v->mcces); leaders(v, v->mcces); - addmcce(v->mcces, (chr *)NULL, (chr *)NULL); /* dummy */ + addmcce(v->mcces, (chr *) NULL, (chr *) NULL); /* dummy */ } CNOERR(); /* parsing */ - lexstart(v); /* also handles prefixes */ - if ((v->cflags®_NLSTOP) || (v->cflags®_NLANCH)) { + lexstart(v); /* also handles prefixes */ + if ((v->cflags & REG_NLSTOP) || (v->cflags & REG_NLANCH)) + { /* assign newline a unique color */ v->nlcolor = subcolor(v->cm, newline()); okcolors(v->nfa, v->cm); } CNOERR(); v->tree = parse(v, EOS, PLAIN, v->nfa->init, v->nfa->final); - assert(SEE(EOS)); /* even if error; ISERR() => SEE(EOS) */ + assert(SEE(EOS)); /* even if error; ISERR() => SEE(EOS) */ CNOERR(); assert(v->tree != NULL); @@ -384,7 +397,8 @@ pg_regcomp(regex_t *re, specialcolors(v->nfa); CNOERR(); #ifdef REG_DEBUG - if (debug != NULL) { + if (debug != NULL) + { fprintf(debug, "\n\n\n========= RAW ==========\n"); dumpnfa(v->nfa, debug); dumpst(v->tree, debug, 1); @@ -395,7 +409,8 @@ pg_regcomp(regex_t *re, markst(v->tree); cleanst(v); #ifdef REG_DEBUG - if (debug != NULL) { + if (debug != NULL) + { fprintf(debug, "\n\n\n========= TREE FIXED ==========\n"); dumpst(v->tree, debug, 1); } @@ -405,7 +420,8 @@ pg_regcomp(regex_t *re, re->re_info |= nfatree(v, v->tree, debug); CNOERR(); assert(v->nlacons == 0 || v->lacons != NULL); - for (i = 1; i < v->nlacons; i++) { + for (i = 1; i < v->nlacons; i++) + { #ifdef REG_DEBUG if (debug != NULL) fprintf(debug, "\n\n\n========= LA%d ==========\n", i); @@ -413,7 +429,7 @@ pg_regcomp(regex_t *re, nfanode(v, &v->lacons[i], debug); } CNOERR(); - if (v->tree->flags&SHORTER) + if (v->tree->flags & SHORTER) NOTE(REG_USHORTEST); /* build compacted NFAs for tree, lacons, fast search */ @@ -422,7 +438,7 @@ pg_regcomp(regex_t *re, fprintf(debug, "\n\n\n========= SEARCH ==========\n"); #endif /* can sacrifice main NFA now, so use it as work area */ - (DISCARD)optimize(v->nfa, debug); + (DISCARD) optimize(v->nfa, debug); CNOERR(); makesearch(v, v->nfa); CNOERR(); @@ -431,7 +447,7 @@ pg_regcomp(regex_t *re, /* looks okay, package it up */ re->re_nsub = v->nsubexp; - v->re = NULL; /* freev no longer frees re */ + v->re = NULL; /* freev no longer frees re */ g->magic = GUTSMAGIC; g->cflags = v->cflags; g->info = re->re_info; @@ -439,13 +455,13 @@ pg_regcomp(regex_t *re, g->tree = v->tree; v->tree = NULL; g->ntree = v->ntree; - g->compare = (v->cflags®_ICASE) ? casecmp : cmp; + g->compare = (v->cflags & REG_ICASE) ? casecmp : cmp; g->lacons = v->lacons; v->lacons = NULL; g->nlacons = v->nlacons; #ifdef REG_DEBUG - if (flags®_DUMP) + if (flags & REG_DUMP) dump(re, stdout); #endif @@ -457,22 +473,26 @@ pg_regcomp(regex_t *re, * moresubs - enlarge subRE vector */ static void -moresubs(struct vars *v, +moresubs(struct vars * v, int wanted) /* want enough room for this one */ { struct subre **p; - size_t n; + size_t n; - assert(wanted > 0 && (size_t)wanted >= v->nsubs); - n = (size_t)wanted * 3 / 2 + 1; - if (v->subs == v->sub10) { - p = (struct subre **)MALLOC(n * sizeof(struct subre *)); + assert(wanted > 0 && (size_t) wanted >= v->nsubs); + n = (size_t) wanted *3 / 2 + 1; + + if (v->subs == v->sub10) + { + p = (struct subre **) MALLOC(n * sizeof(struct subre *)); if (p != NULL) memcpy(VS(p), VS(v->subs), - v->nsubs * sizeof(struct subre *)); - } else - p = (struct subre **)REALLOC(v->subs, n*sizeof(struct subre *)); - if (p == NULL) { + v->nsubs * sizeof(struct subre *)); + } + else + p = (struct subre **) REALLOC(v->subs, n * sizeof(struct subre *)); + if (p == NULL) + { ERR(REG_ESPACE); return; } @@ -480,7 +500,7 @@ moresubs(struct vars *v, for (p = &v->subs[v->nsubs]; v->nsubs < n; p++, v->nsubs++) *p = NULL; assert(v->nsubs == n); - assert((size_t)wanted < v->nsubs); + assert((size_t) wanted < v->nsubs); } /* @@ -490,7 +510,7 @@ moresubs(struct vars *v, * (if any), to make error-handling code terser. */ static int -freev(struct vars *v, +freev(struct vars * v, int err) { if (v->re != NULL) @@ -511,7 +531,7 @@ freev(struct vars *v, freecvec(v->mcces); if (v->lacons != NULL) freelacons(v->lacons, v->nlacons); - ERR(err); /* nop if err==0 */ + ERR(err); /* nop if err==0 */ return v->err; } @@ -521,8 +541,8 @@ freev(struct vars *v, * NFA must have been optimize()d already. */ static void -makesearch(struct vars *v, - struct nfa *nfa) +makesearch(struct vars * v, + struct nfa * nfa) { struct arc *a; struct arc *b; @@ -532,12 +552,14 @@ makesearch(struct vars *v, struct state *slist; /* no loops are needed if it's anchored */ - for (a = pre->outs; a != NULL; a = a->outchain) { + for (a = pre->outs; a != NULL; a = a->outchain) + { assert(a->type == PLAIN); if (a->co != nfa->bos[0] && a->co != nfa->bos[1]) break; } - if (a != NULL) { + if (a != NULL) + { /* add implicit .* in front */ rainbow(nfa, v->cm, PLAIN, COLORLESS, pre, pre); @@ -548,40 +570,45 @@ makesearch(struct vars *v, /* * Now here's the subtle part. Because many REs have no lookback - * constraints, often knowing when you were in the pre state tells - * you little; it's the next state(s) that are informative. But - * some of them may have other inarcs, i.e. it may be possible to - * make actual progress and then return to one of them. We must - * de-optimize such cases, splitting each such state into progress - * and no-progress states. + * constraints, often knowing when you were in the pre state tells you + * little; it's the next state(s) that are informative. But some of + * them may have other inarcs, i.e. it may be possible to make actual + * progress and then return to one of them. We must de-optimize such + * cases, splitting each such state into progress and no-progress + * states. */ /* first, make a list of the states */ slist = NULL; - for (a = pre->outs; a != NULL; a = a->outchain) { + for (a = pre->outs; a != NULL; a = a->outchain) + { s = a->to; for (b = s->ins; b != NULL; b = b->inchain) if (b->from != pre) break; - if (b != NULL) { /* must be split */ + if (b != NULL) + { /* must be split */ s->tmp = slist; slist = s; } } /* do the splits */ - for (s = slist; s != NULL; s = s2) { + for (s = slist; s != NULL; s = s2) + { s2 = newstate(nfa); copyouts(nfa, s, s2); - for (a = s->ins; a != NULL; a = b) { + for (a = s->ins; a != NULL; a = b) + { b = a->inchain; - if (a->from != pre) { + if (a->from != pre) + { cparc(nfa, a, a->from, s2); freearc(nfa, a); } } s2 = s->tmp; - s->tmp = NULL; /* clean up while we're at it */ + s->tmp = NULL; /* clean up while we're at it */ } } @@ -589,22 +616,22 @@ makesearch(struct vars *v, * parse - parse an RE * * This is actually just the top level, which parses a bunch of branches - * tied together with '|'. They appear in the tree as the left children + * tied together with '|'. They appear in the tree as the left children * of a chain of '|' subres. */ static struct subre * -parse(struct vars *v, - int stopper, /* EOS or ')' */ - int type, /* LACON (lookahead subRE) or PLAIN */ - struct state *init, /* initial state */ - struct state *final) /* final state */ +parse(struct vars * v, + int stopper, /* EOS or ')' */ + int type, /* LACON (lookahead subRE) or PLAIN */ + struct state * init, /* initial state */ + struct state * final) /* final state */ { - struct state *left; /* scaffolding for branch */ + struct state *left; /* scaffolding for branch */ struct state *right; - struct subre *branches; /* top level */ - struct subre *branch; /* current branch */ - struct subre *t; /* temporary */ - int firstbranch; /* is this the first branch? */ + struct subre *branches; /* top level */ + struct subre *branch; /* current branch */ + struct subre *t; /* temporary */ + int firstbranch; /* is this the first branch? */ assert(stopper == ')' || stopper == EOS); @@ -612,8 +639,10 @@ parse(struct vars *v, NOERRN(); branch = branches; firstbranch = 1; - do { /* a branch */ - if (!firstbranch) { + do + { /* a branch */ + if (!firstbranch) + { /* need a place to hang it */ branch->right = subre(v, '|', LONGER, init, final); NOERRN(); @@ -629,25 +658,29 @@ parse(struct vars *v, branch->left = parsebranch(v, stopper, type, left, right, 0); NOERRN(); branch->flags |= UP(branch->flags | branch->left->flags); - if ((branch->flags &~ branches->flags) != 0) /* new flags */ + if ((branch->flags & ~branches->flags) != 0) /* new flags */ for (t = branches; t != branch; t = t->right) t->flags |= branch->flags; } while (EAT('|')); assert(SEE(stopper) || SEE(EOS)); - if (!SEE(stopper)) { + if (!SEE(stopper)) + { assert(stopper == ')' && SEE(EOS)); ERR(REG_EPAREN); } /* optimize out simple cases */ - if (branch == branches) { /* only one branch */ + if (branch == branches) + { /* only one branch */ assert(branch->right == NULL); t = branch->left; branch->left = NULL; freesubre(v, branches); branches = t; - } else if (!MESSY(branches->flags)) { /* no interesting innards */ + } + else if (!MESSY(branches->flags)) + { /* no interesting innards */ freesubre(v, branches->left); branches->left = NULL; freesubre(v, branches->right); @@ -666,23 +699,25 @@ parse(struct vars *v, * ',' nodes introduced only when necessary due to substructure. */ static struct subre * -parsebranch(struct vars *v, - int stopper, /* EOS or ')' */ +parsebranch(struct vars * v, + int stopper, /* EOS or ')' */ int type, /* LACON (lookahead subRE) or PLAIN */ - struct state *left, /* leftmost state */ - struct state *right, /* rightmost state */ - int partial) /* is this only part of a branch? */ + struct state * left, /* leftmost state */ + struct state * right, /* rightmost state */ + int partial) /* is this only part of a branch? */ { - struct state *lp; /* left end of current construct */ - int seencontent; /* is there anything in this branch yet? */ + struct state *lp; /* left end of current construct */ + int seencontent; /* is there anything in this branch yet? */ struct subre *t; lp = left; seencontent = 0; t = subre(v, '=', 0, left, right); /* op '=' is tentative */ NOERRN(); - while (!SEE('|') && !SEE(stopper) && !SEE(EOS)) { - if (seencontent) { /* implicit concat operator */ + while (!SEE('|') && !SEE(stopper) && !SEE(EOS)) + { + if (seencontent) + { /* implicit concat operator */ lp = newstate(v->nfa); NOERRN(); moveins(v->nfa, right, lp); @@ -693,7 +728,8 @@ parsebranch(struct vars *v, parseqatom(v, stopper, type, lp, right, t); } - if (!seencontent) { /* empty branch */ + if (!seencontent) + { /* empty branch */ if (!partial) NOTE(REG_UUNSPEC); assert(lp == left); @@ -711,259 +747,273 @@ parsebranch(struct vars *v, * of the branch, making this function's name somewhat inaccurate. */ static void -parseqatom(struct vars *v, +parseqatom(struct vars * v, int stopper, /* EOS or ')' */ int type, /* LACON (lookahead subRE) or PLAIN */ - struct state *lp, /* left state to hang it on */ - struct state *rp, /* right state to hang it on */ - struct subre *top) /* subtree top */ + struct state * lp, /* left state to hang it on */ + struct state * rp, /* right state to hang it on */ + struct subre * top) /* subtree top */ { - struct state *s; /* temporaries for new states */ + struct state *s; /* temporaries for new states */ struct state *s2; -# define ARCV(t, val) newarc(v->nfa, t, val, lp, rp) - int m, n; - struct subre *atom; /* atom's subtree */ + +#define ARCV(t, val) newarc(v->nfa, t, val, lp, rp) + int m, + n; + struct subre *atom; /* atom's subtree */ struct subre *t; - int cap; /* capturing parens? */ - int pos; /* positive lookahead? */ - int subno; /* capturing-parens or backref number */ - int atomtype; - int qprefer; /* quantifier short/long preference */ - int f; - struct subre **atomp; /* where the pointer to atom is */ + int cap; /* capturing parens? */ + int pos; /* positive lookahead? */ + int subno; /* capturing-parens or backref number */ + int atomtype; + int qprefer; /* quantifier short/long preference */ + int f; + struct subre **atomp; /* where the pointer to atom is */ /* initial bookkeeping */ atom = NULL; - assert(lp->nouts == 0); /* must string new code */ - assert(rp->nins == 0); /* between lp and rp */ - subno = 0; /* just to shut lint up */ + assert(lp->nouts == 0); /* must string new code */ + assert(rp->nins == 0); /* between lp and rp */ + subno = 0; /* just to shut lint up */ /* an atom or constraint... */ atomtype = v->nexttype; - switch (atomtype) { - /* first, constraints, which end by returning */ - case '^': - ARCV('^', 1); - if (v->cflags®_NLANCH) - ARCV(BEHIND, v->nlcolor); - NEXT(); - return; - break; - case '$': - ARCV('$', 1); - if (v->cflags®_NLANCH) - ARCV(AHEAD, v->nlcolor); - NEXT(); - return; - break; - case SBEGIN: - ARCV('^', 1); /* BOL */ - ARCV('^', 0); /* or BOS */ - NEXT(); - return; - break; - case SEND: - ARCV('$', 1); /* EOL */ - ARCV('$', 0); /* or EOS */ - NEXT(); - return; - break; - case '<': - wordchrs(v); /* does NEXT() */ - s = newstate(v->nfa); - NOERR(); - nonword(v, BEHIND, lp, s); - word(v, AHEAD, s, rp); - return; - break; - case '>': - wordchrs(v); /* does NEXT() */ - s = newstate(v->nfa); - NOERR(); - word(v, BEHIND, lp, s); - nonword(v, AHEAD, s, rp); - return; - break; - case WBDRY: - wordchrs(v); /* does NEXT() */ - s = newstate(v->nfa); - NOERR(); - nonword(v, BEHIND, lp, s); - word(v, AHEAD, s, rp); - s = newstate(v->nfa); - NOERR(); - word(v, BEHIND, lp, s); - nonword(v, AHEAD, s, rp); - return; - break; - case NWBDRY: - wordchrs(v); /* does NEXT() */ - s = newstate(v->nfa); - NOERR(); - word(v, BEHIND, lp, s); - word(v, AHEAD, s, rp); - s = newstate(v->nfa); - NOERR(); - nonword(v, BEHIND, lp, s); - nonword(v, AHEAD, s, rp); - return; - break; - case LACON: /* lookahead constraint */ - pos = v->nextvalue; - NEXT(); - s = newstate(v->nfa); - s2 = newstate(v->nfa); - NOERR(); - t = parse(v, ')', LACON, s, s2); - freesubre(v, t); /* internal structure irrelevant */ - assert(SEE(')') || ISERR()); - NEXT(); - n = newlacon(v, s, s2, pos); - NOERR(); - ARCV(LACON, n); - return; - break; - /* then errors, to get them out of the way */ - case '*': - case '+': - case '?': - case '{': - ERR(REG_BADRPT); - return; - break; - default: - ERR(REG_ASSERT); - return; - break; - /* then plain characters, and minor variants on that theme */ - case ')': /* unbalanced paren */ - if ((v->cflags®_ADVANCED) != REG_EXTENDED) { - ERR(REG_EPAREN); + switch (atomtype) + { + /* first, constraints, which end by returning */ + case '^': + ARCV('^', 1); + if (v->cflags & REG_NLANCH) + ARCV(BEHIND, v->nlcolor); + NEXT(); return; - } - /* legal in EREs due to specification botch */ - NOTE(REG_UPBOTCH); - /* fallthrough into case PLAIN */ - case PLAIN: - onechr(v, v->nextvalue, lp, rp); - okcolors(v->nfa, v->cm); - NOERR(); - NEXT(); - break; - case '[': - if (v->nextvalue == 1) - bracket(v, lp, rp); - else - cbracket(v, lp, rp); - assert(SEE(']') || ISERR()); - NEXT(); - break; - case '.': - rainbow(v->nfa, v->cm, PLAIN, - (v->cflags®_NLSTOP) ? v->nlcolor : COLORLESS, - lp, rp); - NEXT(); - break; - /* and finally the ugly stuff */ - case '(': /* value flags as capturing or non */ - cap = (type == LACON) ? 0 : v->nextvalue; - if (cap) { - v->nsubexp++; - subno = v->nsubexp; - if ((size_t)subno >= v->nsubs) - moresubs(v, subno); - assert((size_t)subno < v->nsubs); - } else - atomtype = PLAIN; /* something that's not '(' */ - NEXT(); - /* need new endpoints because tree will contain pointers */ - s = newstate(v->nfa); - s2 = newstate(v->nfa); - NOERR(); - EMPTYARC(lp, s); - EMPTYARC(s2, rp); - NOERR(); - atom = parse(v, ')', PLAIN, s, s2); - assert(SEE(')') || ISERR()); - NEXT(); - NOERR(); - if (cap) { - v->subs[subno] = atom; - t = subre(v, '(', atom->flags|CAP, lp, rp); + break; + case '$': + ARCV('$', 1); + if (v->cflags & REG_NLANCH) + ARCV(AHEAD, v->nlcolor); + NEXT(); + return; + break; + case SBEGIN: + ARCV('^', 1); /* BOL */ + ARCV('^', 0); /* or BOS */ + NEXT(); + return; + break; + case SEND: + ARCV('$', 1); /* EOL */ + ARCV('$', 0); /* or EOS */ + NEXT(); + return; + break; + case '<': + wordchrs(v); /* does NEXT() */ + s = newstate(v->nfa); NOERR(); - t->subno = subno; - t->left = atom; - atom = t; - } - /* postpone everything else pending possible {0} */ - break; - case BACKREF: /* the Feature From The Black Lagoon */ - INSIST(type != LACON, REG_ESUBREG); - INSIST(v->nextvalue < v->nsubs, REG_ESUBREG); - INSIST(v->subs[v->nextvalue] != NULL, REG_ESUBREG); - NOERR(); - assert(v->nextvalue > 0); - atom = subre(v, 'b', BACKR, lp, rp); - subno = v->nextvalue; - atom->subno = subno; - EMPTYARC(lp, rp); /* temporarily, so there's something */ - NEXT(); - break; + nonword(v, BEHIND, lp, s); + word(v, AHEAD, s, rp); + return; + break; + case '>': + wordchrs(v); /* does NEXT() */ + s = newstate(v->nfa); + NOERR(); + word(v, BEHIND, lp, s); + nonword(v, AHEAD, s, rp); + return; + break; + case WBDRY: + wordchrs(v); /* does NEXT() */ + s = newstate(v->nfa); + NOERR(); + nonword(v, BEHIND, lp, s); + word(v, AHEAD, s, rp); + s = newstate(v->nfa); + NOERR(); + word(v, BEHIND, lp, s); + nonword(v, AHEAD, s, rp); + return; + break; + case NWBDRY: + wordchrs(v); /* does NEXT() */ + s = newstate(v->nfa); + NOERR(); + word(v, BEHIND, lp, s); + word(v, AHEAD, s, rp); + s = newstate(v->nfa); + NOERR(); + nonword(v, BEHIND, lp, s); + nonword(v, AHEAD, s, rp); + return; + break; + case LACON: /* lookahead constraint */ + pos = v->nextvalue; + NEXT(); + s = newstate(v->nfa); + s2 = newstate(v->nfa); + NOERR(); + t = parse(v, ')', LACON, s, s2); + freesubre(v, t); /* internal structure irrelevant */ + assert(SEE(')') || ISERR()); + NEXT(); + n = newlacon(v, s, s2, pos); + NOERR(); + ARCV(LACON, n); + return; + break; + /* then errors, to get them out of the way */ + case '*': + case '+': + case '?': + case '{': + ERR(REG_BADRPT); + return; + break; + default: + ERR(REG_ASSERT); + return; + break; + /* then plain characters, and minor variants on that theme */ + case ')': /* unbalanced paren */ + if ((v->cflags & REG_ADVANCED) != REG_EXTENDED) + { + ERR(REG_EPAREN); + return; + } + /* legal in EREs due to specification botch */ + NOTE(REG_UPBOTCH); + /* fallthrough into case PLAIN */ + case PLAIN: + onechr(v, v->nextvalue, lp, rp); + okcolors(v->nfa, v->cm); + NOERR(); + NEXT(); + break; + case '[': + if (v->nextvalue == 1) + bracket(v, lp, rp); + else + cbracket(v, lp, rp); + assert(SEE(']') || ISERR()); + NEXT(); + break; + case '.': + rainbow(v->nfa, v->cm, PLAIN, + (v->cflags & REG_NLSTOP) ? v->nlcolor : COLORLESS, + lp, rp); + NEXT(); + break; + /* and finally the ugly stuff */ + case '(': /* value flags as capturing or non */ + cap = (type == LACON) ? 0 : v->nextvalue; + if (cap) + { + v->nsubexp++; + subno = v->nsubexp; + if ((size_t) subno >= v->nsubs) + moresubs(v, subno); + assert((size_t) subno < v->nsubs); + } + else + atomtype = PLAIN; /* something that's not '(' */ + NEXT(); + /* need new endpoints because tree will contain pointers */ + s = newstate(v->nfa); + s2 = newstate(v->nfa); + NOERR(); + EMPTYARC(lp, s); + EMPTYARC(s2, rp); + NOERR(); + atom = parse(v, ')', PLAIN, s, s2); + assert(SEE(')') || ISERR()); + NEXT(); + NOERR(); + if (cap) + { + v->subs[subno] = atom; + t = subre(v, '(', atom->flags | CAP, lp, rp); + NOERR(); + t->subno = subno; + t->left = atom; + atom = t; + } + /* postpone everything else pending possible {0} */ + break; + case BACKREF: /* the Feature From The Black Lagoon */ + INSIST(type != LACON, REG_ESUBREG); + INSIST(v->nextvalue < v->nsubs, REG_ESUBREG); + INSIST(v->subs[v->nextvalue] != NULL, REG_ESUBREG); + NOERR(); + assert(v->nextvalue > 0); + atom = subre(v, 'b', BACKR, lp, rp); + subno = v->nextvalue; + atom->subno = subno; + EMPTYARC(lp, rp); /* temporarily, so there's something */ + NEXT(); + break; } /* ...and an atom may be followed by a quantifier */ - switch (v->nexttype) { - case '*': - m = 0; - n = INFINITY; - qprefer = (v->nextvalue) ? LONGER : SHORTER; - NEXT(); - break; - case '+': - m = 1; - n = INFINITY; - qprefer = (v->nextvalue) ? LONGER : SHORTER; - NEXT(); - break; - case '?': - m = 0; - n = 1; - qprefer = (v->nextvalue) ? LONGER : SHORTER; - NEXT(); - break; - case '{': - NEXT(); - m = scannum(v); - if (EAT(',')) { - if (SEE(DIGIT)) - n = scannum(v); + switch (v->nexttype) + { + case '*': + m = 0; + n = INFINITY; + qprefer = (v->nextvalue) ? LONGER : SHORTER; + NEXT(); + break; + case '+': + m = 1; + n = INFINITY; + qprefer = (v->nextvalue) ? LONGER : SHORTER; + NEXT(); + break; + case '?': + m = 0; + n = 1; + qprefer = (v->nextvalue) ? LONGER : SHORTER; + NEXT(); + break; + case '{': + NEXT(); + m = scannum(v); + if (EAT(',')) + { + if (SEE(DIGIT)) + n = scannum(v); + else + n = INFINITY; + if (m > n) + { + ERR(REG_BADBR); + return; + } + /* {m,n} exercises preference, even if it's {m,m} */ + qprefer = (v->nextvalue) ? LONGER : SHORTER; + } else - n = INFINITY; - if (m > n) { + { + n = m; + /* {m} passes operand's preference through */ + qprefer = 0; + } + if (!SEE('}')) + { /* catches errors too */ ERR(REG_BADBR); return; } - /* {m,n} exercises preference, even if it's {m,m} */ - qprefer = (v->nextvalue) ? LONGER : SHORTER; - } else { - n = m; - /* {m} passes operand's preference through */ + NEXT(); + break; + default: /* no quantifier */ + m = n = 1; qprefer = 0; - } - if (!SEE('}')) { /* catches errors too */ - ERR(REG_BADBR); - return; - } - NEXT(); - break; - default: /* no quantifier */ - m = n = 1; - qprefer = 0; - break; + break; } /* annoying special case: {0} or {0,0} cancels everything */ - if (m == 0 && n == 0) { + if (m == 0 && n == 0) + { if (atom != NULL) freesubre(v, atom); if (atomtype == '(') @@ -976,7 +1026,8 @@ parseqatom(struct vars *v, /* if not a messy case, avoid hard part */ assert(!MESSY(top->flags)); f = top->flags | qprefer | ((atom != NULL) ? atom->flags : 0); - if (atomtype != '(' && atomtype != BACKREF && !MESSY(UP(f))) { + if (atomtype != '(' && atomtype != BACKREF && !MESSY(UP(f))) + { if (!(m == 1 && n == 1)) repeat(v, lp, rp, m, n); if (atom != NULL) @@ -986,13 +1037,14 @@ parseqatom(struct vars *v, } /* - * hard part: something messy - * That is, capturing parens, back reference, short/long clash, or - * an atom with substructure containing one of those. + * hard part: something messy That is, capturing parens, back + * reference, short/long clash, or an atom with substructure + * containing one of those. */ /* now we'll need a subre for the contents even if they're boring */ - if (atom == NULL) { + if (atom == NULL) + { atom = subre(v, '=', 0, lp, rp); NOERR(); } @@ -1000,9 +1052,8 @@ parseqatom(struct vars *v, /* * prepare a general-purpose state skeleton * - * ---> [s] ---prefix---> [begin] ---atom---> [end] ----rest---> [rp] - * / / - * [lp] ----> [s2] ----bypass--------------------- + * ---> [s] ---prefix---> [begin] ---atom---> [end] ----rest---> [rp] / + * / [lp] ----> [s2] ----bypass--------------------- * * where bypass is an empty, and prefix is some repetitions of atom */ @@ -1034,21 +1085,23 @@ parseqatom(struct vars *v, top->right = t; /* if it's a backref, now is the time to replicate the subNFA */ - if (atomtype == BACKREF) { - assert(atom->begin->nouts == 1); /* just the EMPTY */ + if (atomtype == BACKREF) + { + assert(atom->begin->nouts == 1); /* just the EMPTY */ delsub(v->nfa, atom->begin, atom->end); assert(v->subs[subno] != NULL); /* and here's why the recursion got postponed: it must */ /* wait until the skeleton is filled in, because it may */ /* hit a backref that wants to copy the filled-in skeleton */ dupnfa(v->nfa, v->subs[subno]->begin, v->subs[subno]->end, - atom->begin, atom->end); + atom->begin, atom->end); NOERR(); } /* it's quantifier time; first, turn x{0,...} into x{1,...}|empty */ - if (m == 0) { - EMPTYARC(s2, atom->end); /* the bypass */ + if (m == 0) + { + EMPTYARC(s2, atom->end); /* the bypass */ assert(PREF(qprefer) != 0); f = COMBINE(qprefer, atom->flags); t = subre(v, '|', f, lp, atom->end); @@ -1064,25 +1117,30 @@ parseqatom(struct vars *v, } /* deal with the rest of the quantifier */ - if (atomtype == BACKREF) { + if (atomtype == BACKREF) + { /* special case: backrefs have internal quantifiers */ - EMPTYARC(s, atom->begin); /* empty prefix */ + EMPTYARC(s, atom->begin); /* empty prefix */ /* just stuff everything into atom */ repeat(v, atom->begin, atom->end, m, n); - atom->min = (short)m; - atom->max = (short)n; + atom->min = (short) m; + atom->max = (short) n; atom->flags |= COMBINE(qprefer, atom->flags); - } else if (m == 1 && n == 1) { + } + else if (m == 1 && n == 1) + { /* no/vacuous quantifier: done */ - EMPTYARC(s, atom->begin); /* empty prefix */ - } else { + EMPTYARC(s, atom->begin); /* empty prefix */ + } + else + { /* turn x{m,n} into x{m-1,n-1}x, with capturing */ - /* parens in only second x */ + /* parens in only second x */ dupnfa(v->nfa, atom->begin, atom->end, s, atom->begin); assert(m >= 1 && m != INFINITY && n >= 1); - repeat(v, s, atom->begin, m-1, (n == INFINITY) ? n : n-1); + repeat(v, s, atom->begin, m - 1, (n == INFINITY) ? n : n - 1); f = COMBINE(qprefer, atom->flags); - t = subre(v, '.', f, s, atom->end); /* prefix and atom */ + t = subre(v, '.', f, s, atom->end); /* prefix and atom */ NOERR(); t->left = subre(v, '=', PREF(f), s, atom->begin); NOERR(); @@ -1094,7 +1152,8 @@ parseqatom(struct vars *v, t = top->right; if (!(SEE('|') || SEE(stopper) || SEE(EOS))) t->right = parsebranch(v, stopper, type, atom->end, rp, 1); - else { + else + { EMPTYARC(atom->end, rp); t->right = subre(v, '=', 0, atom->end, rp); } @@ -1107,12 +1166,12 @@ parseqatom(struct vars *v, * nonword - generate arcs for non-word-character ahead or behind */ static void -nonword(struct vars *v, - int dir, /* AHEAD or BEHIND */ - struct state *lp, - struct state *rp) +nonword(struct vars * v, + int dir, /* AHEAD or BEHIND */ + struct state * lp, + struct state * rp) { - int anchor = (dir == AHEAD) ? '$' : '^'; + int anchor = (dir == AHEAD) ? '$' : '^'; assert(dir == AHEAD || dir == BEHIND); newarc(v->nfa, anchor, 1, lp, rp); @@ -1125,10 +1184,10 @@ nonword(struct vars *v, * word - generate arcs for word character ahead or behind */ static void -word(struct vars *v, - int dir, /* AHEAD or BEHIND */ - struct state *lp, - struct state *rp) +word(struct vars * v, + int dir, /* AHEAD or BEHIND */ + struct state * lp, + struct state * rp) { assert(dir == AHEAD || dir == BEHIND); cloneouts(v->nfa, v->wordchrs, lp, rp, dir); @@ -1138,16 +1197,18 @@ word(struct vars *v, /* * scannum - scan a number */ -static int /* value, <= DUPMAX */ -scannum(struct vars *v) +static int /* value, <= DUPMAX */ +scannum(struct vars * v) { - int n = 0; + int n = 0; - while (SEE(DIGIT) && n < DUPMAX) { - n = n*10 + v->nextvalue; + while (SEE(DIGIT) && n < DUPMAX) + { + n = n * 10 + v->nextvalue; NEXT(); } - if (SEE(DIGIT) || n > DUPMAX) { + if (SEE(DIGIT) || n > DUPMAX) + { ERR(REG_BADBR); return 0; } @@ -1165,83 +1226,84 @@ scannum(struct vars *v) * code in parse(), and when this is called, it doesn't matter any more. */ static void -repeat(struct vars *v, - struct state *lp, - struct state *rp, +repeat(struct vars * v, + struct state * lp, + struct state * rp, int m, int n) { -# define SOME 2 -# define INF 3 -# define PAIR(x, y) ((x)*4 + (y)) -# define REDUCE(x) ( ((x) == INFINITY) ? INF : (((x) > 1) ? SOME : (x)) ) - const int rm = REDUCE(m); - const int rn = REDUCE(n); +#define SOME 2 +#define INF 3 +#define PAIR(x, y) ((x)*4 + (y)) +#define REDUCE(x) ( ((x) == INFINITY) ? INF : (((x) > 1) ? SOME : (x)) ) + const int rm = REDUCE(m); + const int rn = REDUCE(n); struct state *s; struct state *s2; - switch (PAIR(rm, rn)) { - case PAIR(0, 0): /* empty string */ - delsub(v->nfa, lp, rp); - EMPTYARC(lp, rp); - break; - case PAIR(0, 1): /* do as x| */ - EMPTYARC(lp, rp); - break; - case PAIR(0, SOME): /* do as x{1,n}| */ - repeat(v, lp, rp, 1, n); - NOERR(); - EMPTYARC(lp, rp); - break; - case PAIR(0, INF): /* loop x around */ - s = newstate(v->nfa); - NOERR(); - moveouts(v->nfa, lp, s); - moveins(v->nfa, rp, s); - EMPTYARC(lp, s); - EMPTYARC(s, rp); - break; - case PAIR(1, 1): /* no action required */ - break; - case PAIR(1, SOME): /* do as x{0,n-1}x = (x{1,n-1}|)x */ - s = newstate(v->nfa); - NOERR(); - moveouts(v->nfa, lp, s); - dupnfa(v->nfa, s, rp, lp, s); - NOERR(); - repeat(v, lp, s, 1, n-1); - NOERR(); - EMPTYARC(lp, s); - break; - case PAIR(1, INF): /* add loopback arc */ - s = newstate(v->nfa); - s2 = newstate(v->nfa); - NOERR(); - moveouts(v->nfa, lp, s); - moveins(v->nfa, rp, s2); - EMPTYARC(lp, s); - EMPTYARC(s2, rp); - EMPTYARC(s2, s); - break; - case PAIR(SOME, SOME): /* do as x{m-1,n-1}x */ - s = newstate(v->nfa); - NOERR(); - moveouts(v->nfa, lp, s); - dupnfa(v->nfa, s, rp, lp, s); - NOERR(); - repeat(v, lp, s, m-1, n-1); - break; - case PAIR(SOME, INF): /* do as x{m-1,}x */ - s = newstate(v->nfa); - NOERR(); - moveouts(v->nfa, lp, s); - dupnfa(v->nfa, s, rp, lp, s); - NOERR(); - repeat(v, lp, s, m-1, n); - break; - default: - ERR(REG_ASSERT); - break; + switch (PAIR(rm, rn)) + { + case PAIR(0, 0): /* empty string */ + delsub(v->nfa, lp, rp); + EMPTYARC(lp, rp); + break; + case PAIR(0, 1): /* do as x| */ + EMPTYARC(lp, rp); + break; + case PAIR(0, SOME): /* do as x{1,n}| */ + repeat(v, lp, rp, 1, n); + NOERR(); + EMPTYARC(lp, rp); + break; + case PAIR(0, INF): /* loop x around */ + s = newstate(v->nfa); + NOERR(); + moveouts(v->nfa, lp, s); + moveins(v->nfa, rp, s); + EMPTYARC(lp, s); + EMPTYARC(s, rp); + break; + case PAIR(1, 1): /* no action required */ + break; + case PAIR(1, SOME): /* do as x{0,n-1}x = (x{1,n-1}|)x */ + s = newstate(v->nfa); + NOERR(); + moveouts(v->nfa, lp, s); + dupnfa(v->nfa, s, rp, lp, s); + NOERR(); + repeat(v, lp, s, 1, n - 1); + NOERR(); + EMPTYARC(lp, s); + break; + case PAIR(1, INF): /* add loopback arc */ + s = newstate(v->nfa); + s2 = newstate(v->nfa); + NOERR(); + moveouts(v->nfa, lp, s); + moveins(v->nfa, rp, s2); + EMPTYARC(lp, s); + EMPTYARC(s2, rp); + EMPTYARC(s2, s); + break; + case PAIR(SOME, SOME): /* do as x{m-1,n-1}x */ + s = newstate(v->nfa); + NOERR(); + moveouts(v->nfa, lp, s); + dupnfa(v->nfa, s, rp, lp, s); + NOERR(); + repeat(v, lp, s, m - 1, n - 1); + break; + case PAIR(SOME, INF): /* do as x{m-1,}x */ + s = newstate(v->nfa); + NOERR(); + moveouts(v->nfa, lp, s); + dupnfa(v->nfa, s, rp, lp, s); + NOERR(); + repeat(v, lp, s, m - 1, n); + break; + default: + ERR(REG_ASSERT); + break; } } @@ -1250,9 +1312,9 @@ repeat(struct vars *v, * Also called from cbracket for complemented bracket expressions. */ static void -bracket(struct vars *v, - struct state *lp, - struct state *rp) +bracket(struct vars * v, + struct state * lp, + struct state * rp) { assert(SEE('[')); NEXT(); @@ -1265,27 +1327,27 @@ bracket(struct vars *v, /* * cbracket - handle complemented bracket expression * We do it by calling bracket() with dummy endpoints, and then complementing - * the result. The alternative would be to invoke rainbow(), and then delete + * the result. The alternative would be to invoke rainbow(), and then delete * arcs as the b.e. is seen... but that gets messy. */ static void -cbracket(struct vars *v, - struct state *lp, - struct state *rp) +cbracket(struct vars * v, + struct state * lp, + struct state * rp) { struct state *left = newstate(v->nfa); struct state *right = newstate(v->nfa); struct state *s; - struct arc *a; /* arc from lp */ - struct arc *ba; /* arc from left, from bracket() */ - struct arc *pa; /* MCCE-prototype arc */ - color co; - chr *p; - int i; + struct arc *a; /* arc from lp */ + struct arc *ba; /* arc from left, from bracket() */ + struct arc *pa; /* MCCE-prototype arc */ + color co; + chr *p; + int i; NOERR(); bracket(v, left, right); - if (v->cflags®_NLSTOP) + if (v->cflags & REG_NLSTOP) newarc(v->nfa, PLAIN, v->nlcolor, left, right); NOERR(); @@ -1294,7 +1356,8 @@ cbracket(struct vars *v, /* easy part of complementing */ colorcomplement(v->nfa, v->cm, PLAIN, left, lp, rp); NOERR(); - if (v->mcces == NULL) { /* no MCCEs -- we're done */ + if (v->mcces == NULL) + { /* no MCCEs -- we're done */ dropstate(v->nfa, left); assert(right->nins == 0); freestate(v->nfa, right); @@ -1303,33 +1366,39 @@ cbracket(struct vars *v, /* but complementing gets messy in the presence of MCCEs... */ NOTE(REG_ULOCALE); - for (p = v->mcces->chrs, i = v->mcces->nchrs; i > 0; p++, i--) { + for (p = v->mcces->chrs, i = v->mcces->nchrs; i > 0; p++, i--) + { co = GETCOLOR(v->cm, *p); a = findarc(lp, PLAIN, co); ba = findarc(left, PLAIN, co); - if (ba == NULL) { + if (ba == NULL) + { assert(a != NULL); freearc(v->nfa, a); - } else { - assert(a == NULL); } + else + assert(a == NULL); s = newstate(v->nfa); NOERR(); newarc(v->nfa, PLAIN, co, lp, s); NOERR(); pa = findarc(v->mccepbegin, PLAIN, co); assert(pa != NULL); - if (ba == NULL) { /* easy case, need all of them */ + if (ba == NULL) + { /* easy case, need all of them */ cloneouts(v->nfa, pa->to, s, rp, PLAIN); newarc(v->nfa, '$', 1, s, rp); newarc(v->nfa, '$', 0, s, rp); colorcomplement(v->nfa, v->cm, AHEAD, pa->to, s, rp); - } else { /* must be selective */ - if (findarc(ba->to, '$', 1) == NULL) { + } + else + { /* must be selective */ + if (findarc(ba->to, '$', 1) == NULL) + { newarc(v->nfa, '$', 1, s, rp); newarc(v->nfa, '$', 0, s, rp); colorcomplement(v->nfa, v->cm, AHEAD, pa->to, - s, rp); + s, rp); } for (pa = pa->to->outs; pa != NULL; pa = pa->outchain) if (findarc(ba->to, PLAIN, pa->co) == NULL) @@ -1346,83 +1415,39 @@ cbracket(struct vars *v, assert(right->nins == 0); freestate(v->nfa, right); } - + /* * brackpart - handle one item (or range) within a bracket expression */ static void -brackpart(struct vars *v, - struct state *lp, - struct state *rp) +brackpart(struct vars * v, + struct state * lp, + struct state * rp) { - celt startc; - celt endc; + celt startc; + celt endc; struct cvec *cv; - chr *startp; - chr *endp; - chr c[1]; + chr *startp; + chr *endp; + chr c[1]; /* parse something, get rid of special cases, take shortcuts */ - switch (v->nexttype) { - case RANGE: /* a-b-c or other botch */ - ERR(REG_ERANGE); - return; - break; - case PLAIN: - c[0] = v->nextvalue; - NEXT(); - /* shortcut for ordinary chr (not range, not MCCE leader) */ - if (!SEE(RANGE) && !ISCELEADER(v, c[0])) { - onechr(v, c[0], lp, rp); + switch (v->nexttype) + { + case RANGE: /* a-b-c or other botch */ + ERR(REG_ERANGE); return; - } - startc = element(v, c, c+1); - NOERR(); - break; - case COLLEL: - startp = v->now; - endp = scanplain(v); - INSIST(startp < endp, REG_ECOLLATE); - NOERR(); - startc = element(v, startp, endp); - NOERR(); - break; - case ECLASS: - startp = v->now; - endp = scanplain(v); - INSIST(startp < endp, REG_ECOLLATE); - NOERR(); - startc = element(v, startp, endp); - NOERR(); - cv = eclass(v, startc, (v->cflags®_ICASE)); - NOERR(); - dovec(v, cv, lp, rp); - return; - break; - case CCLASS: - startp = v->now; - endp = scanplain(v); - INSIST(startp < endp, REG_ECTYPE); - NOERR(); - cv = cclass(v, startp, endp, (v->cflags®_ICASE)); - NOERR(); - dovec(v, cv, lp, rp); - return; - break; - default: - ERR(REG_ASSERT); - return; - break; - } - - if (SEE(RANGE)) { - NEXT(); - switch (v->nexttype) { + break; case PLAIN: - case RANGE: c[0] = v->nextvalue; NEXT(); - endc = element(v, c, c+1); + /* shortcut for ordinary chr (not range, not MCCE leader) */ + if (!SEE(RANGE) && !ISCELEADER(v, c[0])) + { + onechr(v, c[0], lp, rp); + return; + } + startc = element(v, c, c + 1); NOERR(); break; case COLLEL: @@ -1430,25 +1455,74 @@ brackpart(struct vars *v, endp = scanplain(v); INSIST(startp < endp, REG_ECOLLATE); NOERR(); - endc = element(v, startp, endp); + startc = element(v, startp, endp); NOERR(); break; - default: - ERR(REG_ERANGE); + case ECLASS: + startp = v->now; + endp = scanplain(v); + INSIST(startp < endp, REG_ECOLLATE); + NOERR(); + startc = element(v, startp, endp); + NOERR(); + cv = eclass(v, startc, (v->cflags & REG_ICASE)); + NOERR(); + dovec(v, cv, lp, rp); return; break; + case CCLASS: + startp = v->now; + endp = scanplain(v); + INSIST(startp < endp, REG_ECTYPE); + NOERR(); + cv = cclass(v, startp, endp, (v->cflags & REG_ICASE)); + NOERR(); + dovec(v, cv, lp, rp); + return; + break; + default: + ERR(REG_ASSERT); + return; + break; + } + + if (SEE(RANGE)) + { + NEXT(); + switch (v->nexttype) + { + case PLAIN: + case RANGE: + c[0] = v->nextvalue; + NEXT(); + endc = element(v, c, c + 1); + NOERR(); + break; + case COLLEL: + startp = v->now; + endp = scanplain(v); + INSIST(startp < endp, REG_ECOLLATE); + NOERR(); + endc = element(v, startp, endp); + NOERR(); + break; + default: + ERR(REG_ERANGE); + return; + break; } - } else + } + else endc = startc; /* - * Ranges are unportable. Actually, standard C does - * guarantee that digits are contiguous, but making - * that an exception is just too complicated. + * Ranges are unportable. Actually, standard C does guarantee that + * digits are contiguous, but making that an exception is just too + * complicated. */ if (startc != endc) NOTE(REG_UUNPORT); - cv = range(v, startc, endc, (v->cflags®_ICASE)); + cv = range(v, startc, endc, (v->cflags & REG_ICASE)); NOERR(); dovec(v, cv, lp, rp); } @@ -1459,16 +1533,17 @@ brackpart(struct vars *v, * Certain bits of trickery in lex.c know that this code does not try * to look past the final bracket of the [. etc. */ -static chr * /* just after end of sequence */ -scanplain(struct vars *v) +static chr * /* just after end of sequence */ +scanplain(struct vars * v) { - chr *endp; + chr *endp; assert(SEE(COLLEL) || SEE(ECLASS) || SEE(CCLASS)); NEXT(); endp = v->now; - while (SEE(PLAIN)) { + while (SEE(PLAIN)) + { endp = v->now; NEXT(); } @@ -1485,12 +1560,12 @@ scanplain(struct vars *v) * certainly necessary, and sets up little disconnected subNFA. */ static void -leaders(struct vars *v, - struct cvec *cv) +leaders(struct vars * v, + struct cvec * cv) { - int mcce; - chr *p; - chr leader; + int mcce; + chr *p; + chr leader; struct state *s; struct arc *a; @@ -1498,16 +1573,20 @@ leaders(struct vars *v, v->mccepend = newstate(v->nfa); NOERR(); - for (mcce = 0; mcce < cv->nmcces; mcce++) { + for (mcce = 0; mcce < cv->nmcces; mcce++) + { p = cv->mcces[mcce]; leader = *p; - if (!haschr(cv, leader)) { + if (!haschr(cv, leader)) + { addchr(cv, leader); s = newstate(v->nfa); newarc(v->nfa, PLAIN, subcolor(v->cm, leader), - v->mccepbegin, s); + v->mccepbegin, s); okcolors(v->nfa, v->cm); - } else { + } + else + { a = findarc(v->mccepbegin, PLAIN, GETCOLOR(v->cm, leader)); assert(a != NULL); @@ -1515,7 +1594,8 @@ leaders(struct vars *v, assert(s != v->mccepend); } p++; - assert(*p != 0 && *(p+1) == 0); /* only 2-char MCCEs for now */ + assert(*p != 0 && *(p + 1) == 0); /* only 2-char MCCEs for + * now */ newarc(v->nfa, PLAIN, subcolor(v->cm, *p), s, v->mccepend); okcolors(v->nfa, v->cm); } @@ -1526,12 +1606,13 @@ leaders(struct vars *v, * This is mostly a shortcut for efficient handling of the common case. */ static void -onechr(struct vars *v, +onechr(struct vars * v, chr c, - struct state *lp, - struct state *rp) + struct state * lp, + struct state * rp) { - if (!(v->cflags®_ICASE)) { + if (!(v->cflags & REG_ICASE)) + { newarc(v->nfa, PLAIN, subcolor(v->cm, c), lp, rp); return; } @@ -1545,42 +1626,50 @@ onechr(struct vars *v, * This one has to handle the messy cases, like MCCEs and MCCE leaders. */ static void -dovec(struct vars *v, - struct cvec *cv, - struct state *lp, - struct state *rp) +dovec(struct vars * v, + struct cvec * cv, + struct state * lp, + struct state * rp) { - chr ch, from, to; - celt ce; - chr *p; - int i; - color co; + chr ch, + from, + to; + celt ce; + chr *p; + int i; + color co; struct cvec *leads; struct arc *a; - struct arc *pa; /* arc in prototype */ + struct arc *pa; /* arc in prototype */ struct state *s; - struct state *ps; /* state in prototype */ + struct state *ps; /* state in prototype */ /* need a place to store leaders, if any */ - if (nmcces(v) > 0) { + if (nmcces(v) > 0) + { assert(v->mcces != NULL); - if (v->cv2 == NULL || v->cv2->nchrs < v->mcces->nchrs) { + if (v->cv2 == NULL || v->cv2->nchrs < v->mcces->nchrs) + { if (v->cv2 != NULL) free(v->cv2); v->cv2 = newcvec(v->mcces->nchrs, 0, v->mcces->nmcces); NOERR(); leads = v->cv2; - } else + } + else leads = clearcvec(v->cv2); - } else + } + else leads = NULL; /* first, get the ordinary characters out of the way */ - for (p = cv->chrs, i = cv->nchrs; i > 0; p++, i--) { + for (p = cv->chrs, i = cv->nchrs; i > 0; p++, i--) + { ch = *p; if (!ISCELEADER(v, ch)) newarc(v->nfa, PLAIN, subcolor(v->cm, ch), lp, rp); - else { + else + { assert(singleton(v->cm, ch)); assert(leads != NULL); if (!haschr(leads, ch)) @@ -1589,10 +1678,12 @@ dovec(struct vars *v, } /* and the ranges */ - for (p = cv->ranges, i = cv->nranges; i > 0; p += 2, i--) { + for (p = cv->ranges, i = cv->nranges; i > 0; p += 2, i--) + { from = *p; - to = *(p+1); - while (from <= to && (ce = nextleader(v, from, to)) != NOCELT) { + to = *(p + 1); + while (from <= to && (ce = nextleader(v, from, to)) != NOCELT) + { if (from < ce) subrange(v, from, ce - 1, lp, rp); assert(singleton(v->cm, ce)); @@ -1610,12 +1701,14 @@ dovec(struct vars *v, /* deal with the MCCE leaders */ NOTE(REG_ULOCALE); - for (p = leads->chrs, i = leads->nchrs; i > 0; p++, i--) { + for (p = leads->chrs, i = leads->nchrs; i > 0; p++, i--) + { co = GETCOLOR(v->cm, *p); a = findarc(lp, PLAIN, co); if (a != NULL) s = a->to; - else { + else + { s = newstate(v->nfa); NOERR(); newarc(v->nfa, PLAIN, co, lp, s); @@ -1631,10 +1724,12 @@ dovec(struct vars *v, } /* and the MCCEs */ - for (i = 0; i < cv->nmcces; i++) { + for (i = 0; i < cv->nmcces; i++) + { p = cv->mcces[i]; assert(singleton(v->cm, *p)); - if (!singleton(v->cm, *p)) { + if (!singleton(v->cm, *p)) + { ERR(REG_ASSERT); return; } @@ -1643,17 +1738,18 @@ dovec(struct vars *v, a = findarc(lp, PLAIN, co); if (a != NULL) s = a->to; - else { + else + { s = newstate(v->nfa); NOERR(); newarc(v->nfa, PLAIN, co, lp, s); NOERR(); } - assert(*p != 0); /* at least two chars */ + assert(*p != 0); /* at least two chars */ assert(singleton(v->cm, *p)); ch = *p++; co = GETCOLOR(v->cm, ch); - assert(*p == 0); /* and only two, for now */ + assert(*p == 0); /* and only two, for now */ newarc(v->nfa, PLAIN, co, s, rp); NOERR(); } @@ -1662,20 +1758,21 @@ dovec(struct vars *v, /* * nextleader - find next MCCE leader within range */ -static celt /* NOCELT means none */ -nextleader(struct vars *v, +static celt /* NOCELT means none */ +nextleader(struct vars * v, chr from, chr to) { - int i; - chr *p; - chr ch; - celt it = NOCELT; + int i; + chr *p; + chr ch; + celt it = NOCELT; if (v->mcces == NULL) return it; - for (i = v->mcces->nchrs, p = v->mcces->chrs; i > 0; i--, p++) { + for (i = v->mcces->nchrs, p = v->mcces->chrs; i > 0; i--, p++) + { ch = *p; if (from <= ch && ch <= to) if (it == NOCELT || ch < it) @@ -1694,20 +1791,21 @@ nextleader(struct vars *v, * should be cleaned up to reduce dependencies on input scanning. */ static void -wordchrs(struct vars *v) +wordchrs(struct vars * v) { struct state *left; struct state *right; - if (v->wordchrs != NULL) { - NEXT(); /* for consistency */ + if (v->wordchrs != NULL) + { + NEXT(); /* for consistency */ return; } left = newstate(v->nfa); right = newstate(v->nfa); NOERR(); - /* fine point: implemented with [::], and lexer will set REG_ULOCALE */ + /* fine point: implemented with [::], and lexer will set REG_ULOCALE */ lexword(v); NEXT(); assert(v->savenow != NULL && SEE('[')); @@ -1722,20 +1820,22 @@ wordchrs(struct vars *v) * subre - allocate a subre */ static struct subre * -subre(struct vars *v, +subre(struct vars * v, int op, int flags, - struct state *begin, - struct state *end) + struct state * begin, + struct state * end) { struct subre *ret; ret = v->treefree; if (ret != NULL) v->treefree = ret->left; - else { - ret = (struct subre *)MALLOC(sizeof(struct subre)); - if (ret == NULL) { + else + { + ret = (struct subre *) MALLOC(sizeof(struct subre)); + if (ret == NULL) + { ERR(REG_ESPACE); return NULL; } @@ -1763,8 +1863,8 @@ subre(struct vars *v, * freesubre - free a subRE subtree */ static void -freesubre(struct vars *v, /* might be NULL */ - struct subre *sr) +freesubre(struct vars * v, /* might be NULL */ + struct subre * sr) { if (sr == NULL) return; @@ -1781,8 +1881,8 @@ freesubre(struct vars *v, /* might be NULL */ * freesrnode - free one node in a subRE subtree */ static void -freesrnode(struct vars *v, /* might be NULL */ - struct subre *sr) +freesrnode(struct vars * v, /* might be NULL */ + struct subre * sr) { if (sr == NULL) return; @@ -1791,10 +1891,12 @@ freesrnode(struct vars *v, /* might be NULL */ freecnfa(&sr->cnfa); sr->flags = 0; - if (v != NULL) { + if (v != NULL) + { sr->left = v->treefree; v->treefree = sr; - } else + } + else FREE(sr); } @@ -1802,8 +1904,8 @@ freesrnode(struct vars *v, /* might be NULL */ * optst - optimize a subRE subtree */ static void -optst(struct vars *v, - struct subre *t) +optst(struct vars * v, + struct subre * t) { if (t == NULL) return; @@ -1818,16 +1920,16 @@ optst(struct vars *v, /* * numst - number tree nodes (assigning retry indexes) */ -static int /* next number */ -numst(struct subre *t, - int start) /* starting point for subtree numbers */ +static int /* next number */ +numst(struct subre * t, + int start) /* starting point for subtree numbers */ { - int i; + int i; assert(t != NULL); i = start; - t->retry = (short)i++; + t->retry = (short) i++; if (t->left != NULL) i = numst(t->left, i); if (t->right != NULL) @@ -1839,7 +1941,7 @@ numst(struct subre *t, * markst - mark tree nodes as INUSE */ static void -markst(struct subre *t) +markst(struct subre * t) { assert(t != NULL); @@ -1854,34 +1956,35 @@ markst(struct subre *t) * cleanst - free any tree nodes not marked INUSE */ static void -cleanst(struct vars *v) +cleanst(struct vars * v) { struct subre *t; struct subre *next; - for (t = v->treechain; t != NULL; t = next) { + for (t = v->treechain; t != NULL; t = next) + { next = t->chain; - if (!(t->flags&INUSE)) + if (!(t->flags & INUSE)) FREE(t); } v->treechain = NULL; - v->treefree = NULL; /* just on general principles */ + v->treefree = NULL; /* just on general principles */ } /* * nfatree - turn a subRE subtree into a tree of compacted NFAs */ -static long /* optimize results from top node */ -nfatree(struct vars *v, - struct subre *t, +static long /* optimize results from top node */ +nfatree(struct vars * v, + struct subre * t, FILE *f) /* for debug output */ { assert(t != NULL && t->begin != NULL); if (t->left != NULL) - (DISCARD)nfatree(v, t->left, f); + (DISCARD) nfatree(v, t->left, f); if (t->right != NULL) - (DISCARD)nfatree(v, t->right, f); + (DISCARD) nfatree(v, t->right, f); return nfanode(v, t, f); } @@ -1889,29 +1992,30 @@ nfatree(struct vars *v, /* * nfanode - do one NFA for nfatree */ -static long /* optimize results */ -nfanode(struct vars *v, - struct subre *t, +static long /* optimize results */ +nfanode(struct vars * v, + struct subre * t, FILE *f) /* for debug output */ { struct nfa *nfa; - long ret = 0; + long ret = 0; assert(t->begin != NULL); #ifdef REG_DEBUG if (f != NULL) { - char idbuf[50]; + char idbuf[50]; fprintf(f, "\n\n\n========= TREE NODE %s ==========\n", - stid(t, idbuf, sizeof(idbuf))); + stid(t, idbuf, sizeof(idbuf))); } #endif nfa = newnfa(v, v->cm, v->nfa); NOERRZ(); dupnfa(nfa, t->begin, t->end, nfa->init, nfa->final); - if (!ISERR()) { + if (!ISERR()) + { specialcolors(nfa); ret = optimize(nfa, f); } @@ -1925,25 +2029,29 @@ nfanode(struct vars *v, /* * newlacon - allocate a lookahead-constraint subRE */ -static int /* lacon number */ -newlacon(struct vars *v, - struct state *begin, - struct state *end, +static int /* lacon number */ +newlacon(struct vars * v, + struct state * begin, + struct state * end, int pos) { - int n; + int n; struct subre *sub; - if (v->nlacons == 0) { - v->lacons = (struct subre *)MALLOC(2 * sizeof(struct subre)); - n = 1; /* skip 0th */ + if (v->nlacons == 0) + { + v->lacons = (struct subre *) MALLOC(2 * sizeof(struct subre)); + n = 1; /* skip 0th */ v->nlacons = 2; - } else { - v->lacons = (struct subre *)REALLOC(v->lacons, - (v->nlacons+1)*sizeof(struct subre)); + } + else + { + v->lacons = (struct subre *) REALLOC(v->lacons, + (v->nlacons + 1) * sizeof(struct subre)); n = v->nlacons++; } - if (v->lacons == NULL) { + if (v->lacons == NULL) + { ERR(REG_ESPACE); return 0; } @@ -1959,11 +2067,11 @@ newlacon(struct vars *v, * freelacons - free lookahead-constraint subRE vector */ static void -freelacons(struct subre *subs, +freelacons(struct subre * subs, int n) { struct subre *sub; - int i; + int i; assert(n > 0); for (sub = subs + 1, i = n - 1; i > 0; sub++, i--) /* no 0th */ @@ -1983,14 +2091,14 @@ rfree(regex_t *re) if (re == NULL || re->re_magic != REMAGIC) return; - re->re_magic = 0; /* invalidate RE */ - g = (struct guts *)re->re_guts; + re->re_magic = 0; /* invalidate RE */ + g = (struct guts *) re->re_guts; re->re_guts = NULL; re->re_fns = NULL; g->magic = 0; freecm(&g->cmap); if (g->tree != NULL) - freesubre((struct vars *)NULL, g->tree); + freesubre((struct vars *) NULL, g->tree); if (g->lacons != NULL) freelacons(g->lacons, g->nlacons); if (!NULLCNFA(g->search)) @@ -2008,30 +2116,33 @@ dump(regex_t *re, FILE *f) { struct guts *g; - int i; + int i; if (re->re_magic != REMAGIC) fprintf(f, "bad magic number (0x%x not 0x%x)\n", re->re_magic, - REMAGIC); - if (re->re_guts == NULL) { + REMAGIC); + if (re->re_guts == NULL) + { fprintf(f, "NULL guts!!!\n"); return; } - g = (struct guts *)re->re_guts; + g = (struct guts *) re->re_guts; if (g->magic != GUTSMAGIC) fprintf(f, "bad guts magic number (0x%x not 0x%x)\n", g->magic, - GUTSMAGIC); + GUTSMAGIC); fprintf(f, "\n\n\n========= DUMP ==========\n"); - fprintf(f, "nsub %d, info 0%lo, csize %d, ntree %d\n", - re->re_nsub, re->re_info, re->re_csize, g->ntree); + fprintf(f, "nsub %d, info 0%lo, csize %d, ntree %d\n", + re->re_nsub, re->re_info, re->re_csize, g->ntree); dumpcolors(&g->cmap, f); - if (!NULLCNFA(g->search)) { + if (!NULLCNFA(g->search)) + { printf("\nsearch:\n"); dumpcnfa(&g->search, f); } - for (i = 1; i < g->nlacons; i++) { + for (i = 1; i < g->nlacons; i++) + { fprintf(f, "\nla%d (%s):\n", i, (g->lacons[i].subno) ? "positive" : "negative"); dumpcnfa(&g->lacons[i].cnfa, f); @@ -2044,7 +2155,7 @@ dump(regex_t *re, * dumpst - dump a subRE tree */ static void -dumpst(struct subre *t, +dumpst(struct subre * t, FILE *f, int nfapresent) /* is the original NFA still around? */ { @@ -2059,40 +2170,42 @@ dumpst(struct subre *t, * stdump - recursive guts of dumpst */ static void -stdump(struct subre *t, +stdump(struct subre * t, FILE *f, int nfapresent) /* is the original NFA still around? */ { - char idbuf[50]; + char idbuf[50]; fprintf(f, "%s. `%c'", stid(t, idbuf, sizeof(idbuf)), t->op); - if (t->flags&LONGER) + if (t->flags & LONGER) fprintf(f, " longest"); - if (t->flags&SHORTER) + if (t->flags & SHORTER) fprintf(f, " shortest"); - if (t->flags&MIXED) + if (t->flags & MIXED) fprintf(f, " hasmixed"); - if (t->flags&CAP) + if (t->flags & CAP) fprintf(f, " hascapture"); - if (t->flags&BACKR) + if (t->flags & BACKR) fprintf(f, " hasbackref"); - if (!(t->flags&INUSE)) + if (!(t->flags & INUSE)) fprintf(f, " UNUSED"); if (t->subno != 0) fprintf(f, " (#%d)", t->subno); - if (t->min != 1 || t->max != 1) { + if (t->min != 1 || t->max != 1) + { fprintf(f, " {%d,", t->min); if (t->max != INFINITY) fprintf(f, "%d", t->max); fprintf(f, "}"); } if (nfapresent) - fprintf(f, " %ld-%ld", (long)t->begin->no, (long)t->end->no); + fprintf(f, " %ld-%ld", (long) t->begin->no, (long) t->end->no); if (t->left != NULL) fprintf(f, " L:%s", stid(t->left, idbuf, sizeof(idbuf))); if (t->right != NULL) fprintf(f, " R:%s", stid(t->right, idbuf, sizeof(idbuf))); - if (!NULLCNFA(t->cnfa)) { + if (!NULLCNFA(t->cnfa)) + { fprintf(f, "\n"); dumpcnfa(&t->cnfa, f); fprintf(f, "\n"); @@ -2106,22 +2219,21 @@ stdump(struct subre *t, /* * stid - identify a subtree node for dumping */ -static char * /* points to buf or constant string */ -stid(struct subre *t, +static char * /* points to buf or constant string */ +stid(struct subre * t, char *buf, size_t bufsize) { /* big enough for hex int or decimal t->retry? */ - if (bufsize < sizeof(int)*2 + 3 || bufsize < sizeof(t->retry)*3 + 1) + if (bufsize < sizeof(int) * 2 + 3 || bufsize < sizeof(t->retry) * 3 + 1) return "unable"; if (t->retry != 0) sprintf(buf, "%d", t->retry); else - sprintf(buf, "0x%x", (int)t); /* may lose bits, that's okay */ + sprintf(buf, "0x%x", (int) t); /* may lose bits, that's okay */ return buf; } - -#endif /* REG_DEBUG */ +#endif /* REG_DEBUG */ #include "regc_lex.c" diff --git a/src/backend/regex/rege_dfa.c b/src/backend/regex/rege_dfa.c index 3bdfc2ab18..6004462c93 100644 --- a/src/backend/regex/rege_dfa.c +++ b/src/backend/regex/rege_dfa.c @@ -2,21 +2,21 @@ * DFA routines * This file is #included by regexec.c. * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -28,27 +28,27 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/rege_dfa.c,v 1.1 2003/02/05 17:41:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/rege_dfa.c,v 1.2 2003/08/04 00:43:21 momjian Exp $ * */ /* * longest - longest-preferred matching engine */ -static chr * /* endpoint, or NULL */ -longest(struct vars *v, /* used only for debug and exec flags */ - struct dfa *d, - chr *start, /* where the match should start */ - chr *stop, /* match must end at or before here */ +static chr * /* endpoint, or NULL */ +longest(struct vars * v, /* used only for debug and exec flags */ + struct dfa * d, + chr * start, /* where the match should start */ + chr * stop, /* match must end at or before here */ int *hitstopp) /* record whether hit v->stop, if non-NULL */ { - chr *cp; - chr *realstop = (stop == v->stop) ? stop : stop + 1; - color co; + chr *cp; + chr *realstop = (stop == v->stop) ? stop : stop + 1; + color co; struct sset *css; struct sset *ss; - chr *post; - int i; + chr *post; + int i; struct colormap *cm = d->cm; /* initialize */ @@ -59,12 +59,15 @@ longest(struct vars *v, /* used only for debug and exec flags */ /* startup */ FDEBUG(("+++ startup +++\n")); - if (cp == v->start) { - co = d->cnfa->bos[(v->eflags®_NOTBOL) ? 0 : 1]; - FDEBUG(("color %ld\n", (long)co)); - } else { + if (cp == v->start) + { + co = d->cnfa->bos[(v->eflags & REG_NOTBOL) ? 0 : 1]; + FDEBUG(("color %ld\n", (long) co)); + } + else + { co = GETCOLOR(cm, *(cp - 1)); - FDEBUG(("char %c, color %ld\n", (char)*(cp-1), (long)co)); + FDEBUG(("char %c, color %ld\n", (char) *(cp - 1), (long) co)); } css = miss(v, d, css, co, cp, start); if (css == NULL) @@ -72,29 +75,33 @@ longest(struct vars *v, /* used only for debug and exec flags */ css->lastseen = cp; /* main loop */ - if (v->eflags®_FTRACE) - while (cp < realstop) { + if (v->eflags & REG_FTRACE) + while (cp < realstop) + { FDEBUG(("+++ at c%d +++\n", css - d->ssets)); co = GETCOLOR(cm, *cp); - FDEBUG(("char %c, color %ld\n", (char)*cp, (long)co)); + FDEBUG(("char %c, color %ld\n", (char) *cp, (long) co)); ss = css->outs[co]; - if (ss == NULL) { - ss = miss(v, d, css, co, cp+1, start); + if (ss == NULL) + { + ss = miss(v, d, css, co, cp + 1, start); if (ss == NULL) - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ } cp++; ss->lastseen = cp; css = ss; } else - while (cp < realstop) { + while (cp < realstop) + { co = GETCOLOR(cm, *cp); ss = css->outs[co]; - if (ss == NULL) { - ss = miss(v, d, css, co, cp+1, start); + if (ss == NULL) + { + ss = miss(v, d, css, co, cp + 1, start); if (ss == NULL) - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ } cp++; ss->lastseen = cp; @@ -103,14 +110,15 @@ longest(struct vars *v, /* used only for debug and exec flags */ /* shutdown */ FDEBUG(("+++ shutdown at c%d +++\n", css - d->ssets)); - if (cp == v->stop && stop == v->stop) { + if (cp == v->stop && stop == v->stop) + { if (hitstopp != NULL) *hitstopp = 1; - co = d->cnfa->eos[(v->eflags®_NOTEOL) ? 0 : 1]; - FDEBUG(("color %ld\n", (long)co)); + co = d->cnfa->eos[(v->eflags & REG_NOTEOL) ? 0 : 1]; + FDEBUG(("color %ld\n", (long) co)); ss = miss(v, d, css, co, cp, start); /* special case: match ended at eol? */ - if (ss != NULL && (ss->flags&POSTSTATE)) + if (ss != NULL && (ss->flags & POSTSTATE)) return cp; else if (ss != NULL) ss->lastseen = cp; /* to be tidy */ @@ -119,10 +127,10 @@ longest(struct vars *v, /* used only for debug and exec flags */ /* find last match, if any */ post = d->lastpost; for (ss = d->ssets, i = d->nssused; i > 0; ss++, i--) - if ((ss->flags&POSTSTATE) && post != ss->lastseen && - (post == NULL || post < ss->lastseen)) + if ((ss->flags & POSTSTATE) && post != ss->lastseen && + (post == NULL || post < ss->lastseen)) post = ss->lastseen; - if (post != NULL) /* found one */ + if (post != NULL) /* found one */ return post - 1; return NULL; @@ -131,19 +139,20 @@ longest(struct vars *v, /* used only for debug and exec flags */ /* * shortest - shortest-preferred matching engine */ -static chr * /* endpoint, or NULL */ -shortest(struct vars *v, - struct dfa *d, - chr *start, /* where the match should start */ - chr *min, /* match must end at or after here */ - chr *max, /* match must end at or before here */ - chr **coldp, /* store coldstart pointer here, if nonNULL */ +static chr * /* endpoint, or NULL */ +shortest(struct vars * v, + struct dfa * d, + chr * start, /* where the match should start */ + chr * min, /* match must end at or after here */ + chr * max, /* match must end at or before here */ + chr ** coldp, /* store coldstart pointer here, if + * nonNULL */ int *hitstopp) /* record whether hit v->stop, if non-NULL */ { - chr *cp; - chr *realmin = (min == v->stop) ? min : min + 1; - chr *realmax = (max == v->stop) ? max : max + 1; - color co; + chr *cp; + chr *realmin = (min == v->stop) ? min : min + 1; + chr *realmax = (max == v->stop) ? max : max + 1; + color co; struct sset *css; struct sset *ss; struct colormap *cm = d->cm; @@ -156,12 +165,15 @@ shortest(struct vars *v, /* startup */ FDEBUG(("--- startup ---\n")); - if (cp == v->start) { - co = d->cnfa->bos[(v->eflags®_NOTBOL) ? 0 : 1]; - FDEBUG(("color %ld\n", (long)co)); - } else { + if (cp == v->start) + { + co = d->cnfa->bos[(v->eflags & REG_NOTBOL) ? 0 : 1]; + FDEBUG(("color %ld\n", (long) co)); + } + else + { co = GETCOLOR(cm, *(cp - 1)); - FDEBUG(("char %c, color %ld\n", (char)*(cp-1), (long)co)); + FDEBUG(("char %c, color %ld\n", (char) *(cp - 1), (long) co)); } css = miss(v, d, css, co, cp, start); if (css == NULL) @@ -170,58 +182,66 @@ shortest(struct vars *v, ss = css; /* main loop */ - if (v->eflags®_FTRACE) - while (cp < realmax) { + if (v->eflags & REG_FTRACE) + while (cp < realmax) + { FDEBUG(("--- at c%d ---\n", css - d->ssets)); co = GETCOLOR(cm, *cp); - FDEBUG(("char %c, color %ld\n", (char)*cp, (long)co)); + FDEBUG(("char %c, color %ld\n", (char) *cp, (long) co)); ss = css->outs[co]; - if (ss == NULL) { - ss = miss(v, d, css, co, cp+1, start); + if (ss == NULL) + { + ss = miss(v, d, css, co, cp + 1, start); if (ss == NULL) - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ } cp++; ss->lastseen = cp; css = ss; - if ((ss->flags&POSTSTATE) && cp >= realmin) - break; /* NOTE BREAK OUT */ + if ((ss->flags & POSTSTATE) && cp >= realmin) + break; /* NOTE BREAK OUT */ } else - while (cp < realmax) { + while (cp < realmax) + { co = GETCOLOR(cm, *cp); ss = css->outs[co]; - if (ss == NULL) { - ss = miss(v, d, css, co, cp+1, start); + if (ss == NULL) + { + ss = miss(v, d, css, co, cp + 1, start); if (ss == NULL) - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ } cp++; ss->lastseen = cp; css = ss; - if ((ss->flags&POSTSTATE) && cp >= realmin) - break; /* NOTE BREAK OUT */ + if ((ss->flags & POSTSTATE) && cp >= realmin) + break; /* NOTE BREAK OUT */ } if (ss == NULL) return NULL; - if (coldp != NULL) /* report last no-progress state set, if any */ + if (coldp != NULL) /* report last no-progress state set, if + * any */ *coldp = lastcold(v, d); - if ((ss->flags&POSTSTATE) && cp > min) { + if ((ss->flags & POSTSTATE) && cp > min) + { assert(cp >= realmin); cp--; - } else if (cp == v->stop && max == v->stop) { - co = d->cnfa->eos[(v->eflags®_NOTEOL) ? 0 : 1]; - FDEBUG(("color %ld\n", (long)co)); + } + else if (cp == v->stop && max == v->stop) + { + co = d->cnfa->eos[(v->eflags & REG_NOTEOL) ? 0 : 1]; + FDEBUG(("color %ld\n", (long) co)); ss = miss(v, d, css, co, cp, start); /* match might have ended at eol */ - if ((ss == NULL || !(ss->flags&POSTSTATE)) && hitstopp != NULL) + if ((ss == NULL || !(ss->flags & POSTSTATE)) && hitstopp != NULL) *hitstopp = 1; } - if (ss == NULL || !(ss->flags&POSTSTATE)) + if (ss == NULL || !(ss->flags & POSTSTATE)) return NULL; return cp; @@ -230,19 +250,19 @@ shortest(struct vars *v, /* * lastcold - determine last point at which no progress had been made */ -static chr * /* endpoint, or NULL */ -lastcold(struct vars *v, - struct dfa *d) +static chr * /* endpoint, or NULL */ +lastcold(struct vars * v, + struct dfa * d) { struct sset *ss; - chr *nopr; - int i; + chr *nopr; + int i; nopr = d->lastnopr; if (nopr == NULL) nopr = v->start; for (ss = d->ssets, i = d->nssused; i > 0; ss++, i--) - if ((ss->flags&NOPROGRESS) && nopr < ss->lastseen) + if ((ss->flags & NOPROGRESS) && nopr < ss->lastseen) nopr = ss->lastseen; return nopr; } @@ -251,24 +271,27 @@ lastcold(struct vars *v, * newdfa - set up a fresh DFA */ static struct dfa * -newdfa(struct vars *v, - struct cnfa *cnfa, - struct colormap *cm, - struct smalldfa *small) /* preallocated space, may be NULL */ +newdfa(struct vars * v, + struct cnfa * cnfa, + struct colormap * cm, + struct smalldfa * small) /* preallocated space, may be NULL */ { struct dfa *d; - size_t nss = cnfa->nstates * 2; - int wordsper = (cnfa->nstates + UBITS - 1) / UBITS; + size_t nss = cnfa->nstates * 2; + int wordsper = (cnfa->nstates + UBITS - 1) / UBITS; struct smalldfa *smallwas = small; assert(cnfa != NULL && cnfa->nstates != 0); - if (nss <= FEWSTATES && cnfa->ncolors <= FEWCOLORS) { + if (nss <= FEWSTATES && cnfa->ncolors <= FEWCOLORS) + { assert(wordsper == 1); - if (small == NULL) { - small = (struct smalldfa *)MALLOC( - sizeof(struct smalldfa)); - if (small == NULL) { + if (small == NULL) + { + small = (struct smalldfa *) MALLOC( + sizeof(struct smalldfa)); + if (small == NULL) + { ERR(REG_ESPACE); return NULL; } @@ -280,32 +303,36 @@ newdfa(struct vars *v, d->outsarea = small->outsarea; d->incarea = small->incarea; d->cptsmalloced = 0; - d->mallocarea = (smallwas == NULL) ? (char *)small : NULL; - } else { - d = (struct dfa *)MALLOC(sizeof(struct dfa)); - if (d == NULL) { + d->mallocarea = (smallwas == NULL) ? (char *) small : NULL; + } + else + { + d = (struct dfa *) MALLOC(sizeof(struct dfa)); + if (d == NULL) + { ERR(REG_ESPACE); return NULL; } - d->ssets = (struct sset *)MALLOC(nss * sizeof(struct sset)); - d->statesarea = (unsigned *)MALLOC((nss+WORK) * wordsper * - sizeof(unsigned)); + d->ssets = (struct sset *) MALLOC(nss * sizeof(struct sset)); + d->statesarea = (unsigned *) MALLOC((nss + WORK) * wordsper * + sizeof(unsigned)); d->work = &d->statesarea[nss * wordsper]; - d->outsarea = (struct sset **)MALLOC(nss * cnfa->ncolors * - sizeof(struct sset *)); - d->incarea = (struct arcp *)MALLOC(nss * cnfa->ncolors * - sizeof(struct arcp)); + d->outsarea = (struct sset **) MALLOC(nss * cnfa->ncolors * + sizeof(struct sset *)); + d->incarea = (struct arcp *) MALLOC(nss * cnfa->ncolors * + sizeof(struct arcp)); d->cptsmalloced = 1; - d->mallocarea = (char *)d; + d->mallocarea = (char *) d; if (d->ssets == NULL || d->statesarea == NULL || - d->outsarea == NULL || d->incarea == NULL) { + d->outsarea == NULL || d->incarea == NULL) + { freedfa(d); ERR(REG_ESPACE); return NULL; } } - d->nssets = (v->eflags®_SMALL) ? 7 : nss; + d->nssets = (v->eflags & REG_SMALL) ? 7 : nss; d->nssused = 0; d->nstates = cnfa->nstates; d->ncolors = cnfa->ncolors; @@ -325,9 +352,10 @@ newdfa(struct vars *v, * freedfa - free a DFA */ static void -freedfa(struct dfa *d) +freedfa(struct dfa * d) { - if (d->cptsmalloced) { + if (d->cptsmalloced) + { if (d->ssets != NULL) FREE(d->ssets); if (d->statesarea != NULL) @@ -351,8 +379,8 @@ static unsigned hash(unsigned *uv, int n) { - int i; - unsigned h; + int i; + unsigned h; h = 0; for (i = 0; i < n; i++) @@ -364,24 +392,25 @@ hash(unsigned *uv, * initialize - hand-craft a cache entry for startup, otherwise get ready */ static struct sset * -initialize(struct vars *v, /* used only for debug flags */ - struct dfa *d, - chr *start) +initialize(struct vars * v, /* used only for debug flags */ + struct dfa * d, + chr * start) { struct sset *ss; - int i; + int i; /* is previous one still there? */ - if (d->nssused > 0 && (d->ssets[0].flags&STARTER)) + if (d->nssused > 0 && (d->ssets[0].flags & STARTER)) ss = &d->ssets[0]; - else { /* no, must (re)build it */ + else + { /* no, must (re)build it */ ss = getvacant(v, d, start, start); for (i = 0; i < d->wordsper; i++) ss->states[i] = 0; BSET(ss->states, d->cnfa->pre); ss->hash = HASH(ss->states, d->wordsper); assert(d->cnfa->pre != d->cnfa->post); - ss->flags = STARTER|LOCKED|NOPROGRESS; + ss->flags = STARTER | LOCKED | NOPROGRESS; /* lastseen dealt with below */ } @@ -396,27 +425,28 @@ initialize(struct vars *v, /* used only for debug flags */ /* * miss - handle a cache miss */ -static struct sset * /* NULL if goes to empty set */ -miss(struct vars *v, /* used only for debug flags */ - struct dfa *d, - struct sset *css, +static struct sset * /* NULL if goes to empty set */ +miss(struct vars * v, /* used only for debug flags */ + struct dfa * d, + struct sset * css, pcolor co, - chr *cp, /* next chr */ - chr *start) /* where the attempt got started */ + chr * cp, /* next chr */ + chr * start) /* where the attempt got started */ { struct cnfa *cnfa = d->cnfa; - int i; - unsigned h; + int i; + unsigned h; struct carc *ca; struct sset *p; - int ispost; - int noprogress; - int gotstate; - int dolacons; - int sawlacons; + int ispost; + int noprogress; + int gotstate; + int dolacons; + int sawlacons; /* for convenience, we can be called even if it might not be a miss */ - if (css->outs[co] != NULL) { + if (css->outs[co] != NULL) + { FDEBUG(("hit\n")); return css->outs[co]; } @@ -430,8 +460,9 @@ miss(struct vars *v, /* used only for debug flags */ gotstate = 0; for (i = 0; i < d->nstates; i++) if (ISBSET(css->states, i)) - for (ca = cnfa->states[i]+1; ca->co != COLORLESS; ca++) - if (ca->co == co) { + for (ca = cnfa->states[i] + 1; ca->co != COLORLESS; ca++) + if (ca->co == co) + { BSET(d->work, ca->to); gotstate = 1; if (ca->to == cnfa->post) @@ -440,21 +471,23 @@ miss(struct vars *v, /* used only for debug flags */ noprogress = 0; FDEBUG(("%d -> %d\n", i, ca->to)); } - dolacons = (gotstate) ? (cnfa->flags&HASLACONS) : 0; + dolacons = (gotstate) ? (cnfa->flags & HASLACONS) : 0; sawlacons = 0; - while (dolacons) { /* transitive closure */ + while (dolacons) + { /* transitive closure */ dolacons = 0; for (i = 0; i < d->nstates; i++) if (ISBSET(d->work, i)) - for (ca = cnfa->states[i]+1; ca->co != COLORLESS; - ca++) { + for (ca = cnfa->states[i] + 1; ca->co != COLORLESS; + ca++) + { if (ca->co <= cnfa->ncolors) - continue; /* NOTE CONTINUE */ + continue; /* NOTE CONTINUE */ sawlacons = 1; if (ISBSET(d->work, ca->to)) - continue; /* NOTE CONTINUE */ + continue; /* NOTE CONTINUE */ if (!lacon(v, cnfa, cp, ca->co)) - continue; /* NOTE CONTINUE */ + continue; /* NOTE CONTINUE */ BSET(d->work, ca->to); dolacons = 1; if (ca->to == cnfa->post) @@ -470,11 +503,13 @@ miss(struct vars *v, /* used only for debug flags */ /* next, is that in the cache? */ for (p = d->ssets, i = d->nssused; i > 0; p++, i--) - if (HIT(h, d->work, p, d->wordsper)) { + if (HIT(h, d->work, p, d->wordsper)) + { FDEBUG(("cached c%d\n", p - d->ssets)); - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ } - if (i == 0) { /* nope, need a new cache entry */ + if (i == 0) + { /* nope, need a new cache entry */ p = getvacant(v, d, cp, start); assert(p != css); for (i = 0; i < d->wordsper; i++) @@ -486,12 +521,13 @@ miss(struct vars *v, /* used only for debug flags */ /* lastseen to be dealt with by caller */ } - if (!sawlacons) { /* lookahead conds. always cache miss */ + if (!sawlacons) + { /* lookahead conds. always cache miss */ FDEBUG(("c%d[%d]->c%d\n", css - d->ssets, co, p - d->ssets)); css->outs[co] = p; css->inchain[co] = p->ins; p->ins.ss = css; - p->ins.co = (color)co; + p->ins.co = (color) co; } return p; } @@ -499,28 +535,29 @@ miss(struct vars *v, /* used only for debug flags */ /* * lacon - lookahead-constraint checker for miss() */ -static int /* predicate: constraint satisfied? */ -lacon(struct vars *v, - struct cnfa *pcnfa, /* parent cnfa */ - chr *cp, - pcolor co) /* "color" of the lookahead constraint */ +static int /* predicate: constraint satisfied? */ +lacon(struct vars * v, + struct cnfa * pcnfa, /* parent cnfa */ + chr * cp, + pcolor co) /* "color" of the lookahead constraint */ { - int n; + int n; struct subre *sub; struct dfa *d; struct smalldfa sd; - chr *end; + chr *end; n = co - pcnfa->ncolors; assert(n < v->g->nlacons && v->g->lacons != NULL); FDEBUG(("=== testing lacon %d\n", n)); sub = &v->g->lacons[n]; d = newdfa(v, &sub->cnfa, &v->g->cmap, &sd); - if (d == NULL) { + if (d == NULL) + { ERR(REG_ESPACE); return 0; } - end = longest(v, d, cp, v->stop, (int *)NULL); + end = longest(v, d, cp, v->stop, (int *) NULL); freedfa(d); FDEBUG(("=== lacon %d match %d\n", n, (end != NULL))); return (sub->subno) ? (end != NULL) : (end == NULL); @@ -532,46 +569,49 @@ lacon(struct vars *v, * clear the innards of the state set -- that's up to the caller. */ static struct sset * -getvacant(struct vars *v, /* used only for debug flags */ - struct dfa *d, - chr *cp, - chr *start) +getvacant(struct vars * v, /* used only for debug flags */ + struct dfa * d, + chr * cp, + chr * start) { - int i; + int i; struct sset *ss; struct sset *p; struct arcp ap; struct arcp lastap; - color co; + color co; ss = pickss(v, d, cp, start); - assert(!(ss->flags&LOCKED)); + assert(!(ss->flags & LOCKED)); /* clear out its inarcs, including self-referential ones */ ap = ss->ins; - while ((p = ap.ss) != NULL) { + while ((p = ap.ss) != NULL) + { co = ap.co; - FDEBUG(("zapping c%d's %ld outarc\n", p - d->ssets, (long)co)); + FDEBUG(("zapping c%d's %ld outarc\n", p - d->ssets, (long) co)); p->outs[co] = NULL; ap = p->inchain[co]; - p->inchain[co].ss = NULL; /* paranoia */ + p->inchain[co].ss = NULL; /* paranoia */ } ss->ins.ss = NULL; /* take it off the inarc chains of the ssets reached by its outarcs */ - for (i = 0; i < d->ncolors; i++) { + for (i = 0; i < d->ncolors; i++) + { p = ss->outs[i]; assert(p != ss); /* not self-referential */ if (p == NULL) - continue; /* NOTE CONTINUE */ + continue; /* NOTE CONTINUE */ FDEBUG(("del outarc %d from c%d's in chn\n", i, p - d->ssets)); if (p->ins.ss == ss && p->ins.co == i) p->ins = ss->inchain[i]; - else { + else + { assert(p->ins.ss != NULL); for (ap = p->ins; ap.ss != NULL && - !(ap.ss == ss && ap.co == i); - ap = ap.ss->inchain[ap.co]) + !(ap.ss == ss && ap.co == i); + ap = ap.ss->inchain[ap.co]) lastap = ap; assert(ap.ss != NULL); lastap.ss->inchain[lastap.co] = ss->inchain[i]; @@ -581,13 +621,13 @@ getvacant(struct vars *v, /* used only for debug flags */ } /* if ss was a success state, may need to remember location */ - if ((ss->flags&POSTSTATE) && ss->lastseen != d->lastpost && - (d->lastpost == NULL || d->lastpost < ss->lastseen)) + if ((ss->flags & POSTSTATE) && ss->lastseen != d->lastpost && + (d->lastpost == NULL || d->lastpost < ss->lastseen)) d->lastpost = ss->lastseen; /* likewise for a no-progress state */ - if ((ss->flags&NOPROGRESS) && ss->lastseen != d->lastnopr && - (d->lastnopr == NULL || d->lastnopr < ss->lastseen)) + if ((ss->flags & NOPROGRESS) && ss->lastseen != d->lastnopr && + (d->lastnopr == NULL || d->lastnopr < ss->lastseen)) d->lastnopr = ss->lastseen; return ss; @@ -597,18 +637,19 @@ getvacant(struct vars *v, /* used only for debug flags */ * pickss - pick the next stateset to be used */ static struct sset * -pickss(struct vars *v, /* used only for debug flags */ - struct dfa *d, - chr *cp, - chr *start) +pickss(struct vars * v, /* used only for debug flags */ + struct dfa * d, + chr * cp, + chr * start) { - int i; + int i; struct sset *ss; struct sset *end; - chr *ancient; + chr *ancient; /* shortcut for cases where cache isn't full */ - if (d->nssused < d->nssets) { + if (d->nssused < d->nssets) + { i = d->nssused; d->nssused++; ss = &d->ssets[i]; @@ -620,7 +661,8 @@ pickss(struct vars *v, /* used only for debug flags */ ss->ins.co = WHITE; /* give it some value */ ss->outs = &d->outsarea[i * d->ncolors]; ss->inchain = &d->incarea[i * d->ncolors]; - for (i = 0; i < d->ncolors; i++) { + for (i = 0; i < d->ncolors; i++) + { ss->outs[i] = NULL; ss->inchain[i].ss = NULL; } @@ -628,20 +670,22 @@ pickss(struct vars *v, /* used only for debug flags */ } /* look for oldest, or old enough anyway */ - if (cp - start > d->nssets*2/3) /* oldest 33% are expendable */ - ancient = cp - d->nssets*2/3; + if (cp - start > d->nssets * 2 / 3) /* oldest 33% are expendable */ + ancient = cp - d->nssets * 2 / 3; else ancient = start; for (ss = d->search, end = &d->ssets[d->nssets]; ss < end; ss++) if ((ss->lastseen == NULL || ss->lastseen < ancient) && - !(ss->flags&LOCKED)) { + !(ss->flags & LOCKED)) + { d->search = ss + 1; FDEBUG(("replacing c%d\n", ss - d->ssets)); return ss; } for (ss = d->ssets, end = d->search; ss < end; ss++) if ((ss->lastseen == NULL || ss->lastseen < ancient) && - !(ss->flags&LOCKED)) { + !(ss->flags & LOCKED)) + { d->search = ss + 1; FDEBUG(("replacing c%d\n", ss - d->ssets)); return ss; diff --git a/src/backend/regex/regerror.c b/src/backend/regex/regerror.c index 94693eba21..a0a9d3f041 100644 --- a/src/backend/regex/regerror.c +++ b/src/backend/regex/regerror.c @@ -1,21 +1,21 @@ /* * regerror - error-code expansion * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -27,7 +27,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regerror.c,v 1.25 2003/02/05 17:41:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regerror.c,v 1.26 2003/08/04 00:43:21 momjian Exp $ * */ @@ -37,72 +37,82 @@ static char unk[] = "*** unknown regex error code 0x%x ***"; /* struct to map among codes, code names, and explanations */ -static struct rerr { - int code; - char *name; - char *explain; -} rerrs[] = { +static struct rerr +{ + int code; + char *name; + char *explain; +} rerrs[] = + +{ /* the actual table is built from regex.h */ #include "regex/regerrs.h" - { -1, "", "oops" }, /* explanation special-cased in code */ + { + -1, "", "oops" + }, /* explanation special-cased in code */ }; /* * pg_regerror - the interface to error numbers */ /* ARGSUSED */ -size_t /* actual space needed (including NUL) */ +size_t /* actual space needed (including NUL) */ pg_regerror(int errcode, /* error code, or REG_ATOI or REG_ITOA */ - const regex_t *preg, /* associated regex_t (unused at present) */ + const regex_t *preg, /* associated regex_t (unused at present) */ char *errbuf, /* result buffer (unless errbuf_size==0) */ - size_t errbuf_size) /* available space in errbuf, can be 0 */ + size_t errbuf_size) /* available space in errbuf, can be 0 */ { struct rerr *r; - char *msg; - char convbuf[sizeof(unk)+50]; /* 50 = plenty for int */ - size_t len; - int icode; + char *msg; + char convbuf[sizeof(unk) + 50]; /* 50 = plenty for int */ + size_t len; + int icode; - switch (errcode) { - case REG_ATOI: /* convert name to number */ - for (r = rerrs; r->code >= 0; r++) - if (strcmp(r->name, errbuf) == 0) - break; - sprintf(convbuf, "%d", r->code); /* -1 for unknown */ - msg = convbuf; - break; - case REG_ITOA: /* convert number to name */ - icode = atoi(errbuf); /* not our problem if this fails */ - for (r = rerrs; r->code >= 0; r++) - if (r->code == icode) - break; - if (r->code >= 0) - msg = r->name; - else { /* unknown; tell him the number */ - sprintf(convbuf, "REG_%u", (unsigned)icode); + switch (errcode) + { + case REG_ATOI: /* convert name to number */ + for (r = rerrs; r->code >= 0; r++) + if (strcmp(r->name, errbuf) == 0) + break; + sprintf(convbuf, "%d", r->code); /* -1 for unknown */ msg = convbuf; - } - break; - default: /* a real, normal error code */ - for (r = rerrs; r->code >= 0; r++) - if (r->code == errcode) - break; - if (r->code >= 0) - msg = r->explain; - else { /* unknown; say so */ - sprintf(convbuf, unk, errcode); - msg = convbuf; - } - break; + break; + case REG_ITOA: /* convert number to name */ + icode = atoi(errbuf); /* not our problem if this fails */ + for (r = rerrs; r->code >= 0; r++) + if (r->code == icode) + break; + if (r->code >= 0) + msg = r->name; + else + { /* unknown; tell him the number */ + sprintf(convbuf, "REG_%u", (unsigned) icode); + msg = convbuf; + } + break; + default: /* a real, normal error code */ + for (r = rerrs; r->code >= 0; r++) + if (r->code == errcode) + break; + if (r->code >= 0) + msg = r->explain; + else + { /* unknown; say so */ + sprintf(convbuf, unk, errcode); + msg = convbuf; + } + break; } len = strlen(msg) + 1; /* space needed, including NUL */ - if (errbuf_size > 0) { + if (errbuf_size > 0) + { if (errbuf_size > len) strcpy(errbuf, msg); - else { /* truncate to fit */ - strncpy(errbuf, msg, errbuf_size-1); - errbuf[errbuf_size-1] = '\0'; + else + { /* truncate to fit */ + strncpy(errbuf, msg, errbuf_size - 1); + errbuf[errbuf_size - 1] = '\0'; } } diff --git a/src/backend/regex/regexec.c b/src/backend/regex/regexec.c index eef01b0bd5..535501ff0b 100644 --- a/src/backend/regex/regexec.c +++ b/src/backend/regex/regexec.c @@ -1,21 +1,21 @@ /* * re_*exec and friends - match REs * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -27,7 +27,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regexec.c,v 1.21 2003/02/05 17:41:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regexec.c,v 1.22 2003/08/04 00:43:21 momjian Exp $ * */ @@ -36,87 +36,95 @@ /* lazy-DFA representation */ -struct arcp { /* "pointer" to an outarc */ +struct arcp +{ /* "pointer" to an outarc */ struct sset *ss; - color co; + color co; }; -struct sset { /* state set */ - unsigned *states; /* pointer to bitvector */ - unsigned hash; /* hash of bitvector */ -# define HASH(bv, nw) (((nw) == 1) ? *(bv) : hash(bv, nw)) -# define HIT(h,bv,ss,nw) ((ss)->hash == (h) && ((nw) == 1 || \ +struct sset +{ /* state set */ + unsigned *states; /* pointer to bitvector */ + unsigned hash; /* hash of bitvector */ +#define HASH(bv, nw) (((nw) == 1) ? *(bv) : hash(bv, nw)) +#define HIT(h,bv,ss,nw) ((ss)->hash == (h) && ((nw) == 1 || \ memcmp(VS(bv), VS((ss)->states), (nw)*sizeof(unsigned)) == 0)) - int flags; -# define STARTER 01 /* the initial state set */ -# define POSTSTATE 02 /* includes the goal state */ -# define LOCKED 04 /* locked in cache */ -# define NOPROGRESS 010 /* zero-progress state set */ - struct arcp ins; /* chain of inarcs pointing here */ - chr *lastseen; /* last entered on arrival here */ - struct sset **outs; /* outarc vector indexed by color */ - struct arcp *inchain; /* chain-pointer vector for outarcs */ + int flags; +#define STARTER 01 /* the initial state set */ +#define POSTSTATE 02 /* includes the goal state */ +#define LOCKED 04 /* locked in cache */ +#define NOPROGRESS 010 /* zero-progress state set */ + struct arcp ins; /* chain of inarcs pointing here */ + chr *lastseen; /* last entered on arrival here */ + struct sset **outs; /* outarc vector indexed by color */ + struct arcp *inchain; /* chain-pointer vector for outarcs */ }; -struct dfa { - int nssets; /* size of cache */ - int nssused; /* how many entries occupied yet */ - int nstates; /* number of states */ - int ncolors; /* length of outarc and inchain vectors */ - int wordsper; /* length of state-set bitvectors */ - struct sset *ssets; /* state-set cache */ - unsigned *statesarea; /* bitvector storage */ - unsigned *work; /* pointer to work area within statesarea */ - struct sset **outsarea; /* outarc-vector storage */ - struct arcp *incarea; /* inchain storage */ +struct dfa +{ + int nssets; /* size of cache */ + int nssused; /* how many entries occupied yet */ + int nstates; /* number of states */ + int ncolors; /* length of outarc and inchain vectors */ + int wordsper; /* length of state-set bitvectors */ + struct sset *ssets; /* state-set cache */ + unsigned *statesarea; /* bitvector storage */ + unsigned *work; /* pointer to work area within statesarea */ + struct sset **outsarea; /* outarc-vector storage */ + struct arcp *incarea; /* inchain storage */ struct cnfa *cnfa; struct colormap *cm; - chr *lastpost; /* location of last cache-flushed success */ - chr *lastnopr; /* location of last cache-flushed NOPROGRESS */ - struct sset *search; /* replacement-search-pointer memory */ - int cptsmalloced; /* were the areas individually malloced? */ - char *mallocarea; /* self, or master malloced area, or NULL */ + chr *lastpost; /* location of last cache-flushed success */ + chr *lastnopr; /* location of last cache-flushed + * NOPROGRESS */ + struct sset *search; /* replacement-search-pointer memory */ + int cptsmalloced; /* were the areas individually malloced? */ + char *mallocarea; /* self, or master malloced area, or NULL */ }; -#define WORK 1 /* number of work bitvectors needed */ +#define WORK 1 /* number of work bitvectors needed */ /* setup for non-malloc allocation for small cases */ -#define FEWSTATES 20 /* must be less than UBITS */ -#define FEWCOLORS 15 -struct smalldfa { - struct dfa dfa; - struct sset ssets[FEWSTATES*2]; - unsigned statesarea[FEWSTATES*2 + WORK]; - struct sset *outsarea[FEWSTATES*2 * FEWCOLORS]; - struct arcp incarea[FEWSTATES*2 * FEWCOLORS]; +#define FEWSTATES 20 /* must be less than UBITS */ +#define FEWCOLORS 15 +struct smalldfa +{ + struct dfa dfa; + struct sset ssets[FEWSTATES * 2]; + unsigned statesarea[FEWSTATES * 2 + WORK]; + struct sset *outsarea[FEWSTATES * 2 * FEWCOLORS]; + struct arcp incarea[FEWSTATES * 2 * FEWCOLORS]; }; -#define DOMALLOC ((struct smalldfa *)NULL) /* force malloc */ + +#define DOMALLOC ((struct smalldfa *)NULL) /* force malloc */ /* internal variables, bundled for easy passing around */ -struct vars { - regex_t *re; +struct vars +{ + regex_t *re; struct guts *g; - int eflags; /* copies of arguments */ - size_t nmatch; + int eflags; /* copies of arguments */ + size_t nmatch; regmatch_t *pmatch; rm_detail_t *details; - chr *start; /* start of string */ - chr *stop; /* just past end of string */ - int err; /* error code if any (0 none) */ - regoff_t *mem; /* memory vector for backtracking */ + chr *start; /* start of string */ + chr *stop; /* just past end of string */ + int err; /* error code if any (0 none) */ + regoff_t *mem; /* memory vector for backtracking */ struct smalldfa dfa1; struct smalldfa dfa2; }; -#define VISERR(vv) ((vv)->err != 0) /* have we seen an error yet? */ -#define ISERR() VISERR(v) -#define VERR(vv,e) (((vv)->err) ? (vv)->err : ((vv)->err = (e))) -#define ERR(e) VERR(v, e) /* record an error */ -#define NOERR() {if (ISERR()) return v->err;} /* if error seen, return it */ -#define OFF(p) ((p) - v->start) -#define LOFF(p) ((long)OFF(p)) +#define VISERR(vv) ((vv)->err != 0) /* have we seen an error yet? */ +#define ISERR() VISERR(v) +#define VERR(vv,e) (((vv)->err) ? (vv)->err : ((vv)->err = (e))) +#define ERR(e) VERR(v, e) /* record an error */ +#define NOERR() {if (ISERR()) return v->err;} /* if error seen, return + * it */ +#define OFF(p) ((p) - v->start) +#define LOFF(p) ((long)OFF(p)) @@ -124,32 +132,33 @@ struct vars { * forward declarations */ /* === regexec.c === */ -static int find (struct vars *, struct cnfa *, struct colormap *); -static int cfind (struct vars *, struct cnfa *, struct colormap *); -static int cfindloop (struct vars *, struct cnfa *, struct colormap *, struct dfa *, struct dfa *, chr **); -static void zapsubs (regmatch_t *, size_t); -static void zapmem (struct vars *, struct subre *); -static void subset (struct vars *, struct subre *, chr *, chr *); -static int dissect (struct vars *, struct subre *, chr *, chr *); -static int condissect (struct vars *, struct subre *, chr *, chr *); -static int altdissect (struct vars *, struct subre *, chr *, chr *); -static int cdissect (struct vars *, struct subre *, chr *, chr *); -static int ccondissect (struct vars *, struct subre *, chr *, chr *); -static int crevdissect (struct vars *, struct subre *, chr *, chr *); -static int cbrdissect (struct vars *, struct subre *, chr *, chr *); -static int caltdissect (struct vars *, struct subre *, chr *, chr *); +static int find(struct vars *, struct cnfa *, struct colormap *); +static int cfind(struct vars *, struct cnfa *, struct colormap *); +static int cfindloop(struct vars *, struct cnfa *, struct colormap *, struct dfa *, struct dfa *, chr **); +static void zapsubs(regmatch_t *, size_t); +static void zapmem(struct vars *, struct subre *); +static void subset(struct vars *, struct subre *, chr *, chr *); +static int dissect(struct vars *, struct subre *, chr *, chr *); +static int condissect(struct vars *, struct subre *, chr *, chr *); +static int altdissect(struct vars *, struct subre *, chr *, chr *); +static int cdissect(struct vars *, struct subre *, chr *, chr *); +static int ccondissect(struct vars *, struct subre *, chr *, chr *); +static int crevdissect(struct vars *, struct subre *, chr *, chr *); +static int cbrdissect(struct vars *, struct subre *, chr *, chr *); +static int caltdissect(struct vars *, struct subre *, chr *, chr *); + /* === rege_dfa.c === */ -static chr *longest (struct vars *, struct dfa *, chr *, chr *, int *); -static chr *shortest (struct vars *, struct dfa *, chr *, chr *, chr *, chr **, int *); -static chr *lastcold (struct vars *, struct dfa *); -static struct dfa *newdfa (struct vars *, struct cnfa *, struct colormap *, struct smalldfa *); -static void freedfa (struct dfa *); -static unsigned hash (unsigned *, int); -static struct sset *initialize (struct vars *, struct dfa *, chr *); -static struct sset *miss (struct vars *, struct dfa *, struct sset *, pcolor, chr *, chr *); -static int lacon (struct vars *, struct cnfa *, chr *, pcolor); -static struct sset *getvacant (struct vars *, struct dfa *, chr *, chr *); -static struct sset *pickss (struct vars *, struct dfa *, chr *, chr *); +static chr *longest(struct vars *, struct dfa *, chr *, chr *, int *); +static chr *shortest(struct vars *, struct dfa *, chr *, chr *, chr *, chr **, int *); +static chr *lastcold(struct vars *, struct dfa *); +static struct dfa *newdfa(struct vars *, struct cnfa *, struct colormap *, struct smalldfa *); +static void freedfa(struct dfa *); +static unsigned hash(unsigned *, int); +static struct sset *initialize(struct vars *, struct dfa *, chr *); +static struct sset *miss(struct vars *, struct dfa *, struct sset *, pcolor, chr *, chr *); +static int lacon(struct vars *, struct cnfa *, chr *, pcolor); +static struct sset *getvacant(struct vars *, struct dfa *, chr *, chr *); +static struct sset *pickss(struct vars *, struct dfa *, chr *, chr *); /* @@ -157,22 +166,24 @@ static struct sset *pickss (struct vars *, struct dfa *, chr *, chr *); */ int pg_regexec(regex_t *re, - const chr *string, + const chr * string, size_t len, - rm_detail_t *details, + rm_detail_t * details, size_t nmatch, regmatch_t pmatch[], int flags) { struct vars var; register struct vars *v = &var; - int st; - size_t n; - int backref; -# define LOCALMAT 20 - regmatch_t mat[LOCALMAT]; -# define LOCALMEM 40 - regoff_t mem[LOCALMEM]; + int st; + size_t n; + int backref; + +#define LOCALMAT 20 + regmatch_t mat[LOCALMAT]; + +#define LOCALMEM 40 + regoff_t mem[LOCALMEM]; /* sanity checks */ if (re == NULL || string == NULL || re->re_magic != REMAGIC) @@ -182,46 +193,51 @@ pg_regexec(regex_t *re, /* setup */ v->re = re; - v->g = (struct guts *)re->re_guts; - if ((v->g->cflags®_EXPECT) && details == NULL) + v->g = (struct guts *) re->re_guts; + if ((v->g->cflags & REG_EXPECT) && details == NULL) return REG_INVARG; - if (v->g->info®_UIMPOSSIBLE) + if (v->g->info & REG_UIMPOSSIBLE) return REG_NOMATCH; - backref = (v->g->info®_UBACKREF) ? 1 : 0; + backref = (v->g->info & REG_UBACKREF) ? 1 : 0; v->eflags = flags; - if (v->g->cflags®_NOSUB) - nmatch = 0; /* override client */ + if (v->g->cflags & REG_NOSUB) + nmatch = 0; /* override client */ v->nmatch = nmatch; - if (backref) { + if (backref) + { /* need work area */ if (v->g->nsub + 1 <= LOCALMAT) v->pmatch = mat; else - v->pmatch = (regmatch_t *)MALLOC((v->g->nsub + 1) * - sizeof(regmatch_t)); + v->pmatch = (regmatch_t *) MALLOC((v->g->nsub + 1) * + sizeof(regmatch_t)); if (v->pmatch == NULL) return REG_ESPACE; v->nmatch = v->g->nsub + 1; - } else + } + else v->pmatch = pmatch; v->details = details; - v->start = (chr *)string; - v->stop = (chr *)string + len; + v->start = (chr *) string; + v->stop = (chr *) string + len; v->err = 0; - if (backref) { + if (backref) + { /* need retry memory */ assert(v->g->ntree >= 0); - n = (size_t)v->g->ntree; + n = (size_t) v->g->ntree; if (n <= LOCALMEM) v->mem = mem; else - v->mem = (regoff_t *)MALLOC(n*sizeof(regoff_t)); - if (v->mem == NULL) { + v->mem = (regoff_t *) MALLOC(n * sizeof(regoff_t)); + if (v->mem == NULL) + { if (v->pmatch != pmatch && v->pmatch != mat) FREE(v->pmatch); return REG_ESPACE; } - } else + } + else v->mem = NULL; /* do it */ @@ -232,10 +248,11 @@ pg_regexec(regex_t *re, st = find(v, &v->g->tree->cnfa, &v->g->cmap); /* copy (portion of) match vector over if necessary */ - if (st == REG_OKAY && v->pmatch != pmatch && nmatch > 0) { + if (st == REG_OKAY && v->pmatch != pmatch && nmatch > 0) + { zapsubs(pmatch, nmatch); n = (nmatch < v->nmatch) ? nmatch : v->nmatch; - memcpy(VS(pmatch), VS(v->pmatch), n*sizeof(regmatch_t)); + memcpy(VS(pmatch), VS(v->pmatch), n * sizeof(regmatch_t)); } /* clean up */ @@ -250,19 +267,20 @@ pg_regexec(regex_t *re, * find - find a match for the main NFA (no-complications case) */ static int -find(struct vars *v, - struct cnfa *cnfa, - struct colormap *cm) +find(struct vars * v, + struct cnfa * cnfa, + struct colormap * cm) { struct dfa *s; struct dfa *d; - chr *begin; - chr *end = NULL; - chr *cold; - chr *open; /* open and close of range of possible starts */ - chr *close; - int hitend; - int shorter = (v->g->tree->flags&SHORTER) ? 1 : 0; + chr *begin; + chr *end = NULL; + chr *cold; + chr *open; /* open and close of range of possible + * starts */ + chr *close; + int hitend; + int shorter = (v->g->tree->flags & SHORTER) ? 1 : 0; /* first, a shot with the search RE */ s = newdfa(v, &v->g->search, cm, &v->dfa1); @@ -270,20 +288,21 @@ find(struct vars *v, NOERR(); MDEBUG(("\nsearch at %ld\n", LOFF(v->start))); cold = NULL; - close = shortest(v, s, v->start, v->start, v->stop, &cold, (int *)NULL); + close = shortest(v, s, v->start, v->start, v->stop, &cold, (int *) NULL); freedfa(s); NOERR(); - if (v->g->cflags®_EXPECT) { + if (v->g->cflags & REG_EXPECT) + { assert(v->details != NULL); if (cold != NULL) v->details->rm_extend.rm_so = OFF(cold); else v->details->rm_extend.rm_so = OFF(v->stop); - v->details->rm_extend.rm_eo = OFF(v->stop); /* unknown */ + v->details->rm_extend.rm_eo = OFF(v->stop); /* unknown */ } - if (close == NULL) /* not found */ + if (close == NULL) /* not found */ return REG_NOMATCH; - if (v->nmatch == 0) /* found, don't need exact location */ + if (v->nmatch == 0) /* found, don't need exact location */ return REG_OKAY; /* find starting point and match */ @@ -294,18 +313,19 @@ find(struct vars *v, d = newdfa(v, cnfa, cm, &v->dfa1); assert(!(ISERR() && d != NULL)); NOERR(); - for (begin = open; begin <= close; begin++) { + for (begin = open; begin <= close; begin++) + { MDEBUG(("\nfind trying at %ld\n", LOFF(begin))); if (shorter) end = shortest(v, d, begin, begin, v->stop, - (chr **)NULL, &hitend); + (chr **) NULL, &hitend); else end = longest(v, d, begin, v->stop, &hitend); NOERR(); if (hitend && cold == NULL) cold = begin; if (end != NULL) - break; /* NOTE BREAK OUT */ + break; /* NOTE BREAK OUT */ } assert(end != NULL); /* search RE succeeded so loop should */ freedfa(d); @@ -314,14 +334,15 @@ find(struct vars *v, assert(v->nmatch > 0); v->pmatch[0].rm_so = OFF(begin); v->pmatch[0].rm_eo = OFF(end); - if (v->g->cflags®_EXPECT) { + if (v->g->cflags & REG_EXPECT) + { if (cold != NULL) v->details->rm_extend.rm_so = OFF(cold); else v->details->rm_extend.rm_so = OFF(v->stop); - v->details->rm_extend.rm_eo = OFF(v->stop); /* unknown */ + v->details->rm_extend.rm_eo = OFF(v->stop); /* unknown */ } - if (v->nmatch == 1) /* no need for submatches */ + if (v->nmatch == 1) /* no need for submatches */ return REG_OKAY; /* submatches */ @@ -333,19 +354,20 @@ find(struct vars *v, * cfind - find a match for the main NFA (with complications) */ static int -cfind(struct vars *v, - struct cnfa *cnfa, - struct colormap *cm) +cfind(struct vars * v, + struct cnfa * cnfa, + struct colormap * cm) { struct dfa *s; struct dfa *d; - chr *cold; - int ret; + chr *cold; + int ret; s = newdfa(v, &v->g->search, cm, &v->dfa1); NOERR(); d = newdfa(v, cnfa, cm, &v->dfa2); - if (ISERR()) { + if (ISERR()) + { assert(d == NULL); freedfa(s); return v->err; @@ -356,13 +378,14 @@ cfind(struct vars *v, freedfa(d); freedfa(s); NOERR(); - if (v->g->cflags®_EXPECT) { + if (v->g->cflags & REG_EXPECT) + { assert(v->details != NULL); if (cold != NULL) v->details->rm_extend.rm_so = OFF(cold); else v->details->rm_extend.rm_so = OFF(v->stop); - v->details->rm_extend.rm_eo = OFF(v->stop); /* unknown */ + v->details->rm_extend.rm_eo = OFF(v->stop); /* unknown */ } return ret; } @@ -371,47 +394,51 @@ cfind(struct vars *v, * cfindloop - the heart of cfind */ static int -cfindloop(struct vars *v, - struct cnfa *cnfa, - struct colormap *cm, - struct dfa *d, - struct dfa *s, - chr **coldp) /* where to put coldstart pointer */ +cfindloop(struct vars * v, + struct cnfa * cnfa, + struct colormap * cm, + struct dfa * d, + struct dfa * s, + chr ** coldp) /* where to put coldstart pointer */ { - chr *begin; - chr *end; - chr *cold; - chr *open; /* open and close of range of possible starts */ - chr *close; - chr *estart; - chr *estop; - int er; - int shorter = v->g->tree->flags&SHORTER; - int hitend; + chr *begin; + chr *end; + chr *cold; + chr *open; /* open and close of range of possible + * starts */ + chr *close; + chr *estart; + chr *estop; + int er; + int shorter = v->g->tree->flags & SHORTER; + int hitend; assert(d != NULL && s != NULL); cold = NULL; close = v->start; - do { + do + { MDEBUG(("\ncsearch at %ld\n", LOFF(close))); - close = shortest(v, s, close, close, v->stop, &cold, (int *)NULL); + close = shortest(v, s, close, close, v->stop, &cold, (int *) NULL); if (close == NULL) break; /* NOTE BREAK */ assert(cold != NULL); open = cold; cold = NULL; MDEBUG(("cbetween %ld and %ld\n", LOFF(open), LOFF(close))); - for (begin = open; begin <= close; begin++) { + for (begin = open; begin <= close; begin++) + { MDEBUG(("\ncfind trying at %ld\n", LOFF(begin))); estart = begin; estop = v->stop; - for (;;) { + for (;;) + { if (shorter) end = shortest(v, d, begin, estart, - estop, (chr **)NULL, &hitend); + estop, (chr **) NULL, &hitend); else end = longest(v, d, begin, estop, - &hitend); + &hitend); if (hitend && cold == NULL) cold = begin; if (end == NULL) @@ -420,19 +447,23 @@ cfindloop(struct vars *v, zapsubs(v->pmatch, v->nmatch); zapmem(v, v->g->tree); er = cdissect(v, v->g->tree, begin, end); - if (er == REG_OKAY) { - if (v->nmatch > 0) { + if (er == REG_OKAY) + { + if (v->nmatch > 0) + { v->pmatch[0].rm_so = OFF(begin); v->pmatch[0].rm_eo = OFF(end); } *coldp = cold; return REG_OKAY; } - if (er != REG_NOMATCH) { + if (er != REG_NOMATCH) + { ERR(er); return er; } - if ((shorter) ? end == estop : end == begin) { + if ((shorter) ? end == estop : end == begin) + { /* no point in trying again */ *coldp = cold; return REG_NOMATCH; @@ -457,9 +488,10 @@ static void zapsubs(regmatch_t *p, size_t n) { - size_t i; + size_t i; - for (i = n-1; i > 0; i--) { + for (i = n - 1; i > 0; i--) + { p[i].rm_so = -1; p[i].rm_eo = -1; } @@ -469,15 +501,16 @@ zapsubs(regmatch_t *p, * zapmem - initialize the retry memory of a subtree to zeros */ static void -zapmem(struct vars *v, - struct subre *t) +zapmem(struct vars * v, + struct subre * t) { if (t == NULL) return; assert(v->mem != NULL); v->mem[t->retry] = 0; - if (t->op == '(') { + if (t->op == '(') + { assert(t->subno > 0); v->pmatch[t->subno].rm_so = -1; v->pmatch[t->subno].rm_eo = -1; @@ -493,15 +526,15 @@ zapmem(struct vars *v, * subset - set any subexpression relevant to a successful subre */ static void -subset(struct vars *v, - struct subre *sub, - chr *begin, - chr *end) +subset(struct vars * v, + struct subre * sub, + chr * begin, + chr * end) { - int n = sub->subno; + int n = sub->subno; assert(n > 0); - if ((size_t)n >= v->nmatch) + if ((size_t) n >= v->nmatch) return; MDEBUG(("setting %d\n", n)); @@ -512,58 +545,59 @@ subset(struct vars *v, /* * dissect - determine subexpression matches (uncomplicated case) */ -static int /* regexec return code */ -dissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +dissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { assert(t != NULL); MDEBUG(("dissect %ld-%ld\n", LOFF(begin), LOFF(end))); - switch (t->op) { - case '=': /* terminal node */ - assert(t->left == NULL && t->right == NULL); - return REG_OKAY; /* no action, parent did the work */ - break; - case '|': /* alternation */ - assert(t->left != NULL); - return altdissect(v, t, begin, end); - break; - case 'b': /* back ref -- shouldn't be calling us! */ - return REG_ASSERT; - break; - case '.': /* concatenation */ - assert(t->left != NULL && t->right != NULL); - return condissect(v, t, begin, end); - break; - case '(': /* capturing */ - assert(t->left != NULL && t->right == NULL); - assert(t->subno > 0); - subset(v, t, begin, end); - return dissect(v, t->left, begin, end); - break; - default: - return REG_ASSERT; - break; + switch (t->op) + { + case '=': /* terminal node */ + assert(t->left == NULL && t->right == NULL); + return REG_OKAY; /* no action, parent did the work */ + break; + case '|': /* alternation */ + assert(t->left != NULL); + return altdissect(v, t, begin, end); + break; + case 'b': /* back ref -- shouldn't be calling us! */ + return REG_ASSERT; + break; + case '.': /* concatenation */ + assert(t->left != NULL && t->right != NULL); + return condissect(v, t, begin, end); + break; + case '(': /* capturing */ + assert(t->left != NULL && t->right == NULL); + assert(t->subno > 0); + subset(v, t, begin, end); + return dissect(v, t->left, begin, end); + break; + default: + return REG_ASSERT; + break; } } /* * condissect - determine concatenation subexpression matches (uncomplicated) */ -static int /* regexec return code */ -condissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +condissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { struct dfa *d; struct dfa *d2; - chr *mid; - int i; - int shorter = (t->left->flags&SHORTER) ? 1 : 0; - chr *stop = (shorter) ? end : begin; + chr *mid; + int i; + int shorter = (t->left->flags & SHORTER) ? 1 : 0; + chr *stop = (shorter) ? end : begin; assert(t->op == '.'); assert(t->left != NULL && t->left->cnfa.nstates > 0); @@ -572,7 +606,8 @@ condissect(struct vars *v, d = newdfa(v, &t->left->cnfa, &v->g->cmap, &v->dfa1); NOERR(); d2 = newdfa(v, &t->right->cnfa, &v->g->cmap, &v->dfa2); - if (ISERR()) { + if (ISERR()) + { assert(d2 == NULL); freedfa(d); return v->err; @@ -580,11 +615,12 @@ condissect(struct vars *v, /* pick a tentative midpoint */ if (shorter) - mid = shortest(v, d, begin, begin, end, (chr **)NULL, - (int *)NULL); + mid = shortest(v, d, begin, begin, end, (chr **) NULL, + (int *) NULL); else - mid = longest(v, d, begin, end, (int *)NULL); - if (mid == NULL) { + mid = longest(v, d, begin, end, (int *) NULL); + if (mid == NULL) + { freedfa(d); freedfa(d2); return REG_ASSERT; @@ -592,9 +628,11 @@ condissect(struct vars *v, MDEBUG(("tentative midpoint %ld\n", LOFF(mid))); /* iterate until satisfaction or failure */ - while (longest(v, d2, mid, end, (int *)NULL) != end) { + while (longest(v, d2, mid, end, (int *) NULL) != end) + { /* that midpoint didn't work, find a new one */ - if (mid == stop) { + if (mid == stop) + { /* all possibilities exhausted! */ MDEBUG(("no midpoint!\n")); freedfa(d); @@ -602,11 +640,12 @@ condissect(struct vars *v, return REG_ASSERT; } if (shorter) - mid = shortest(v, d, begin, mid+1, end, (chr **)NULL, - (int *)NULL); + mid = shortest(v, d, begin, mid + 1, end, (chr **) NULL, + (int *) NULL); else - mid = longest(v, d, begin, mid-1, (int *)NULL); - if (mid == NULL) { + mid = longest(v, d, begin, mid - 1, (int *) NULL); + if (mid == NULL) + { /* failed to find a new one! */ MDEBUG(("failed midpoint!\n")); freedfa(d); @@ -629,154 +668,166 @@ condissect(struct vars *v, /* * altdissect - determine alternative subexpression matches (uncomplicated) */ -static int /* regexec return code */ -altdissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +altdissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { struct dfa *d; - int i; + int i; assert(t != NULL); assert(t->op == '|'); - for (i = 0; t != NULL; t = t->right, i++) { + for (i = 0; t != NULL; t = t->right, i++) + { MDEBUG(("trying %dth\n", i)); assert(t->left != NULL && t->left->cnfa.nstates > 0); d = newdfa(v, &t->left->cnfa, &v->g->cmap, &v->dfa1); if (ISERR()) return v->err; - if (longest(v, d, begin, end, (int *)NULL) == end) { + if (longest(v, d, begin, end, (int *) NULL) == end) + { MDEBUG(("success\n")); freedfa(d); return dissect(v, t->left, begin, end); } freedfa(d); } - return REG_ASSERT; /* none of them matched?!? */ + return REG_ASSERT; /* none of them matched?!? */ } /* * cdissect - determine subexpression matches (with complications) - * The retry memory stores the offset of the trial midpoint from begin, + * The retry memory stores the offset of the trial midpoint from begin, * plus 1 so that 0 uniquely means "clean slate". */ -static int /* regexec return code */ -cdissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +cdissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { - int er; + int er; assert(t != NULL); MDEBUG(("cdissect %ld-%ld %c\n", LOFF(begin), LOFF(end), t->op)); - switch (t->op) { - case '=': /* terminal node */ - assert(t->left == NULL && t->right == NULL); - return REG_OKAY; /* no action, parent did the work */ - break; - case '|': /* alternation */ - assert(t->left != NULL); - return caltdissect(v, t, begin, end); - break; - case 'b': /* back ref -- shouldn't be calling us! */ - assert(t->left == NULL && t->right == NULL); - return cbrdissect(v, t, begin, end); - break; - case '.': /* concatenation */ - assert(t->left != NULL && t->right != NULL); - return ccondissect(v, t, begin, end); - break; - case '(': /* capturing */ - assert(t->left != NULL && t->right == NULL); - assert(t->subno > 0); - er = cdissect(v, t->left, begin, end); - if (er == REG_OKAY) - subset(v, t, begin, end); - return er; - break; - default: - return REG_ASSERT; - break; + switch (t->op) + { + case '=': /* terminal node */ + assert(t->left == NULL && t->right == NULL); + return REG_OKAY; /* no action, parent did the work */ + break; + case '|': /* alternation */ + assert(t->left != NULL); + return caltdissect(v, t, begin, end); + break; + case 'b': /* back ref -- shouldn't be calling us! */ + assert(t->left == NULL && t->right == NULL); + return cbrdissect(v, t, begin, end); + break; + case '.': /* concatenation */ + assert(t->left != NULL && t->right != NULL); + return ccondissect(v, t, begin, end); + break; + case '(': /* capturing */ + assert(t->left != NULL && t->right == NULL); + assert(t->subno > 0); + er = cdissect(v, t->left, begin, end); + if (er == REG_OKAY) + subset(v, t, begin, end); + return er; + break; + default: + return REG_ASSERT; + break; } } /* * ccondissect - concatenation subexpression matches (with complications) - * The retry memory stores the offset of the trial midpoint from begin, + * The retry memory stores the offset of the trial midpoint from begin, * plus 1 so that 0 uniquely means "clean slate". */ -static int /* regexec return code */ -ccondissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +ccondissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { struct dfa *d; struct dfa *d2; - chr *mid; - int er; + chr *mid; + int er; assert(t->op == '.'); assert(t->left != NULL && t->left->cnfa.nstates > 0); assert(t->right != NULL && t->right->cnfa.nstates > 0); - if (t->left->flags&SHORTER) /* reverse scan */ + if (t->left->flags & SHORTER) /* reverse scan */ return crevdissect(v, t, begin, end); d = newdfa(v, &t->left->cnfa, &v->g->cmap, DOMALLOC); if (ISERR()) return v->err; d2 = newdfa(v, &t->right->cnfa, &v->g->cmap, DOMALLOC); - if (ISERR()) { + if (ISERR()) + { freedfa(d); return v->err; } MDEBUG(("cconcat %d\n", t->retry)); /* pick a tentative midpoint */ - if (v->mem[t->retry] == 0) { - mid = longest(v, d, begin, end, (int *)NULL); - if (mid == NULL) { + if (v->mem[t->retry] == 0) + { + mid = longest(v, d, begin, end, (int *) NULL); + if (mid == NULL) + { freedfa(d); freedfa(d2); return REG_NOMATCH; } MDEBUG(("tentative midpoint %ld\n", LOFF(mid))); v->mem[t->retry] = (mid - begin) + 1; - } else { + } + else + { mid = begin + (v->mem[t->retry] - 1); MDEBUG(("working midpoint %ld\n", LOFF(mid))); } /* iterate until satisfaction or failure */ - for (;;) { + for (;;) + { /* try this midpoint on for size */ er = cdissect(v, t->left, begin, mid); if (er == REG_OKAY && - longest(v, d2, mid, end, (int *)NULL) == end && - (er = cdissect(v, t->right, mid, end)) == - REG_OKAY) - break; /* NOTE BREAK OUT */ - if (er != REG_OKAY && er != REG_NOMATCH) { + longest(v, d2, mid, end, (int *) NULL) == end && + (er = cdissect(v, t->right, mid, end)) == + REG_OKAY) + break; /* NOTE BREAK OUT */ + if (er != REG_OKAY && er != REG_NOMATCH) + { freedfa(d); freedfa(d2); return er; } /* that midpoint didn't work, find a new one */ - if (mid == begin) { + if (mid == begin) + { /* all possibilities exhausted */ MDEBUG(("%d no midpoint\n", t->retry)); freedfa(d); freedfa(d2); return REG_NOMATCH; } - mid = longest(v, d, begin, mid-1, (int *)NULL); - if (mid == NULL) { + mid = longest(v, d, begin, mid - 1, (int *) NULL); + if (mid == NULL) + { /* failed to find a new one */ MDEBUG(("%d failed midpoint\n", t->retry)); freedfa(d); @@ -798,76 +849,85 @@ ccondissect(struct vars *v, /* * crevdissect - determine backref shortest-first subexpression matches - * The retry memory stores the offset of the trial midpoint from begin, + * The retry memory stores the offset of the trial midpoint from begin, * plus 1 so that 0 uniquely means "clean slate". */ -static int /* regexec return code */ -crevdissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +crevdissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { struct dfa *d; struct dfa *d2; - chr *mid; - int er; + chr *mid; + int er; assert(t->op == '.'); assert(t->left != NULL && t->left->cnfa.nstates > 0); assert(t->right != NULL && t->right->cnfa.nstates > 0); - assert(t->left->flags&SHORTER); + assert(t->left->flags & SHORTER); /* concatenation -- need to split the substring between parts */ d = newdfa(v, &t->left->cnfa, &v->g->cmap, DOMALLOC); if (ISERR()) return v->err; d2 = newdfa(v, &t->right->cnfa, &v->g->cmap, DOMALLOC); - if (ISERR()) { + if (ISERR()) + { freedfa(d); return v->err; } MDEBUG(("crev %d\n", t->retry)); /* pick a tentative midpoint */ - if (v->mem[t->retry] == 0) { - mid = shortest(v, d, begin, begin, end, (chr **)NULL, (int *)NULL); - if (mid == NULL) { + if (v->mem[t->retry] == 0) + { + mid = shortest(v, d, begin, begin, end, (chr **) NULL, (int *) NULL); + if (mid == NULL) + { freedfa(d); freedfa(d2); return REG_NOMATCH; } MDEBUG(("tentative midpoint %ld\n", LOFF(mid))); v->mem[t->retry] = (mid - begin) + 1; - } else { + } + else + { mid = begin + (v->mem[t->retry] - 1); MDEBUG(("working midpoint %ld\n", LOFF(mid))); } /* iterate until satisfaction or failure */ - for (;;) { + for (;;) + { /* try this midpoint on for size */ er = cdissect(v, t->left, begin, mid); if (er == REG_OKAY && - longest(v, d2, mid, end, (int *)NULL) == end && - (er = cdissect(v, t->right, mid, end)) == - REG_OKAY) - break; /* NOTE BREAK OUT */ - if (er != REG_OKAY && er != REG_NOMATCH) { + longest(v, d2, mid, end, (int *) NULL) == end && + (er = cdissect(v, t->right, mid, end)) == + REG_OKAY) + break; /* NOTE BREAK OUT */ + if (er != REG_OKAY && er != REG_NOMATCH) + { freedfa(d); freedfa(d2); return er; } /* that midpoint didn't work, find a new one */ - if (mid == end) { + if (mid == end) + { /* all possibilities exhausted */ MDEBUG(("%d no midpoint\n", t->retry)); freedfa(d); freedfa(d2); return REG_NOMATCH; } - mid = shortest(v, d, begin, mid+1, end, (chr **)NULL, (int *)NULL); - if (mid == NULL) { + mid = shortest(v, d, begin, mid + 1, end, (chr **) NULL, (int *) NULL); + if (mid == NULL) + { /* failed to find a new one */ MDEBUG(("%d failed midpoint\n", t->retry)); freedfa(d); @@ -890,25 +950,25 @@ crevdissect(struct vars *v, /* * cbrdissect - determine backref subexpression matches */ -static int /* regexec return code */ -cbrdissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +cbrdissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { - int i; - int n = t->subno; - size_t len; - chr *paren; - chr *p; - chr *stop; - int min = t->min; - int max = t->max; + int i; + int n = t->subno; + size_t len; + chr *paren; + chr *p; + chr *stop; + int min = t->min; + int max = t->max; assert(t != NULL); assert(t->op == 'b'); assert(n >= 0); - assert((size_t)n < v->nmatch); + assert((size_t) n < v->nmatch); MDEBUG(("cbackref n%d %d{%d-%d}\n", t->retry, n, min, max)); @@ -923,7 +983,8 @@ cbrdissect(struct vars *v, v->mem[t->retry] = 1; /* special-case zero-length string */ - if (len == 0) { + if (len == 0) + { if (begin == end) return REG_OKAY; return REG_NOMATCH; @@ -931,41 +992,44 @@ cbrdissect(struct vars *v, /* and too-short string */ assert(end >= begin); - if ((size_t)(end - begin) < len) + if ((size_t) (end - begin) < len) return REG_NOMATCH; stop = end - len; /* count occurrences */ i = 0; - for (p = begin; p <= stop && (i < max || max == INFINITY); p += len) { - if ((*v->g->compare)(paren, p, len) != 0) - break; + for (p = begin; p <= stop && (i < max || max == INFINITY); p += len) + { + if ((*v->g->compare) (paren, p, len) != 0) + break; i++; } MDEBUG(("cbackref found %d\n", i)); /* and sort it out */ - if (p != end) /* didn't consume all of it */ + if (p != end) /* didn't consume all of it */ return REG_NOMATCH; if (min <= i && (i <= max || max == INFINITY)) return REG_OKAY; - return REG_NOMATCH; /* out of range */ + return REG_NOMATCH; /* out of range */ } /* * caltdissect - determine alternative subexpression matches (w. complications) */ -static int /* regexec return code */ -caltdissect(struct vars *v, - struct subre *t, - chr *begin, /* beginning of relevant substring */ - chr *end) /* end of same */ +static int /* regexec return code */ +caltdissect(struct vars * v, + struct subre * t, + chr * begin, /* beginning of relevant substring */ + chr * end) /* end of same */ { struct dfa *d; - int er; -# define UNTRIED 0 /* not yet tried at all */ -# define TRYING 1 /* top matched, trying submatches */ -# define TRIED 2 /* top didn't match or submatches exhausted */ + int er; + +#define UNTRIED 0 /* not yet tried at all */ +#define TRYING 1 /* top matched, trying submatches */ +#define TRIED 2 /* top didn't match or submatches + * exhausted */ if (t == NULL) return REG_NOMATCH; @@ -976,11 +1040,13 @@ caltdissect(struct vars *v, MDEBUG(("calt n%d\n", t->retry)); assert(t->left != NULL); - if (v->mem[t->retry] == UNTRIED) { + if (v->mem[t->retry] == UNTRIED) + { d = newdfa(v, &t->left->cnfa, &v->g->cmap, DOMALLOC); if (ISERR()) return v->err; - if (longest(v, d, begin, end, (int *)NULL) != end) { + if (longest(v, d, begin, end, (int *) NULL) != end) + { freedfa(d); v->mem[t->retry] = TRIED; return caltdissect(v, t->right, begin, end); diff --git a/src/backend/regex/regfree.c b/src/backend/regex/regfree.c index 88f3da3228..1bb9057a91 100644 --- a/src/backend/regex/regfree.c +++ b/src/backend/regex/regfree.c @@ -1,21 +1,21 @@ /* * regfree - free an RE * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -27,7 +27,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Header: /cvsroot/pgsql/src/backend/regex/regfree.c,v 1.16 2003/02/05 17:41:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/regex/regfree.c,v 1.17 2003/08/04 00:43:21 momjian Exp $ * * * You might think that this could be incorporated into regcomp.c, and @@ -50,5 +50,5 @@ pg_regfree(regex_t *re) { if (re == NULL) return; - (*((struct fns *)re->re_fns)->free)(re); + (*((struct fns *) re->re_fns)->free) (re); } diff --git a/src/backend/rewrite/rewriteDefine.c b/src/backend/rewrite/rewriteDefine.c index e7039e8515..0c01a41cb9 100644 --- a/src/backend/rewrite/rewriteDefine.c +++ b/src/backend/rewrite/rewriteDefine.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteDefine.c,v 1.84 2003/08/01 00:15:22 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteDefine.c,v 1.85 2003/08/04 00:43:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -100,8 +100,8 @@ InsertRule(char *rulname, if (!replace) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), - errmsg("rule \"%s\" for relation \"%s\" already exists", - rulname, get_rel_name(eventrel_oid)))); + errmsg("rule \"%s\" for relation \"%s\" already exists", + rulname, get_rel_name(eventrel_oid)))); /* * When replacing, we don't need to replace every attribute @@ -253,7 +253,7 @@ DefineQueryRewrite(RuleStmt *stmt) if (length(action) == 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("INSTEAD NOTHING rules on select are not implemented"), + errmsg("INSTEAD NOTHING rules on select are not implemented"), errhint("Use views instead."))); /* @@ -344,7 +344,7 @@ DefineQueryRewrite(RuleStmt *stmt) if (i != event_relation->rd_att->natts) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("select rule's target list has too few entries"))); + errmsg("select rule's target list has too few entries"))); /* * ... there must not be another ON SELECT rule already ... @@ -358,9 +358,9 @@ DefineQueryRewrite(RuleStmt *stmt) rule = event_relation->rd_rules->rules[i]; if (rule->event == CMD_SELECT) ereport(ERROR, - (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("\"%s\" is already a view", - RelationGetRelationName(event_relation)))); + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("\"%s\" is already a view", + RelationGetRelationName(event_relation)))); } } @@ -383,8 +383,8 @@ DefineQueryRewrite(RuleStmt *stmt) NAMEDATALEN - 4 - 4) != 0) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("view rule for \"%s\" must be named \"%s\"", - event_obj->relname, ViewSelectRuleName))); + errmsg("view rule for \"%s\" must be named \"%s\"", + event_obj->relname, ViewSelectRuleName))); stmt->rulename = pstrdup(ViewSelectRuleName); } @@ -401,9 +401,9 @@ DefineQueryRewrite(RuleStmt *stmt) scanDesc = heap_beginscan(event_relation, SnapshotNow, 0, NULL); if (heap_getnext(scanDesc, ForwardScanDirection) != NULL) ereport(ERROR, - (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("cannot convert non-empty table \"%s\" to a view", - event_obj->relname))); + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot convert non-empty table \"%s\" to a view", + event_obj->relname))); heap_endscan(scanDesc); RelisBecomingView = true; diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index 440e8ba713..d7efa9e201 100644 --- a/src/backend/rewrite/rewriteHandler.c +++ b/src/backend/rewrite/rewriteHandler.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.125 2003/07/29 17:21:24 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.126 2003/08/04 00:43:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -34,10 +34,11 @@ /* We use a list of these to detect recursion in RewriteQuery */ -typedef struct rewrite_event { +typedef struct rewrite_event +{ Oid relation; /* OID of relation having rules */ CmdType event; /* type of rule being fired */ -} rewrite_event; +} rewrite_event; static Query *rewriteRuleAction(Query *parsetree, Query *rule_action, @@ -107,20 +108,21 @@ rewriteRuleAction(Query *parsetree, * Generate expanded rtable consisting of main parsetree's rtable plus * rule action's rtable; this becomes the complete rtable for the rule * action. Some of the entries may be unused after we finish - * rewriting, but if we tried to remove them we'd have a much - * harder job to adjust RT indexes in the query's Vars. It's OK to - * have unused RT entries, since planner will ignore them. + * rewriting, but if we tried to remove them we'd have a much harder + * job to adjust RT indexes in the query's Vars. It's OK to have + * unused RT entries, since planner will ignore them. * * NOTE: because planner will destructively alter rtable, we must ensure * that rule action's rtable is separate and shares no substructure * with the main rtable. Hence do a deep copy here. * * Also, we must disable write-access checking in all the RT entries - * copied from the main query. This is safe since in fact the rule action - * won't write on them, and it's necessary because the rule action may - * have a different commandType than the main query, causing - * ExecCheckRTEPerms() to make an inappropriate check. The read-access - * checks can be left enabled, although they're probably redundant. + * copied from the main query. This is safe since in fact the rule + * action won't write on them, and it's necessary because the rule + * action may have a different commandType than the main query, + * causing ExecCheckRTEPerms() to make an inappropriate check. The + * read-access checks can be left enabled, although they're probably + * redundant. */ main_rtable = (List *) copyObject(parsetree->rtable); @@ -330,12 +332,12 @@ rewriteTargetList(Query *parsetree, Relation target_relation) } /* - * Handle the two cases where we need to insert a default expression: - * it's an INSERT and there's no tlist entry for the column, or the - * tlist entry is a DEFAULT placeholder node. + * Handle the two cases where we need to insert a default + * expression: it's an INSERT and there's no tlist entry for the + * column, or the tlist entry is a DEFAULT placeholder node. */ if ((new_tle == NULL && commandType == CMD_INSERT) || - (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault))) + (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault))) { Node *new_expr; @@ -345,8 +347,9 @@ rewriteTargetList(Query *parsetree, Relation target_relation) * If there is no default (ie, default is effectively NULL), * we can omit the tlist entry in the INSERT case, since the * planner can insert a NULL for itself, and there's no point - * in spending any more rewriter cycles on the entry. But in the - * UPDATE case we've got to explicitly set the column to NULL. + * in spending any more rewriter cycles on the entry. But in + * the UPDATE case we've got to explicitly set the column to + * NULL. */ if (!new_expr) { @@ -540,13 +543,13 @@ build_column_default(Relation rel, int attrno) /* * Make sure the value is coerced to the target column type; this will * generally be true already, but there seem to be some corner cases - * involving domain defaults where it might not be true. - * This should match the parser's processing of non-defaulted expressions - * --- see updateTargetListEntry(). + * involving domain defaults where it might not be true. This should + * match the parser's processing of non-defaulted expressions --- see + * updateTargetListEntry(). */ exprtype = exprType(expr); - expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */ + expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */ expr, exprtype, atttype, atttypmod, COERCION_ASSIGNMENT, @@ -559,7 +562,7 @@ build_column_default(Relation rel, int attrno) NameStr(att_tup->attname), format_type_be(atttype), format_type_be(exprtype)), - errhint("You will need to rewrite or cast the expression."))); + errhint("You will need to rewrite or cast the expression."))); return expr; } @@ -990,7 +993,7 @@ CopyAndAddInvertedQual(Query *parsetree, * rows that the qualified action doesn't act on. (If there are multiple * qualified INSTEAD rules, we AND all the negated quals onto a single * modified original query.) We won't execute the original, unmodified - * query if we find either qualified or unqualified INSTEAD rules. If + * query if we find either qualified or unqualified INSTEAD rules. If * we find both, the modified original query is discarded too. */ static List * @@ -1009,7 +1012,7 @@ fireRules(Query *parsetree, RewriteRule *rule_lock = (RewriteRule *) lfirst(i); Node *event_qual = rule_lock->qual; List *actions = rule_lock->actions; - QuerySource qsrc; + QuerySource qsrc; List *r; /* Determine correct QuerySource value for actions */ @@ -1020,7 +1023,7 @@ fireRules(Query *parsetree, else { qsrc = QSRC_INSTEAD_RULE; - *instead_flag = true; /* report unqualified INSTEAD */ + *instead_flag = true; /* report unqualified INSTEAD */ } } else @@ -1034,14 +1037,13 @@ fireRules(Query *parsetree, * qualifications of the INSTEAD rules are added so it does * its actions only in cases where the rule quals of all * INSTEAD rules are false. Think of it as the default action - * in a case. We save this in *qual_product so - * RewriteQuery() can add it to the query list after we - * mangled it up enough. + * in a case. We save this in *qual_product so RewriteQuery() + * can add it to the query list after we mangled it up enough. * - * If we have already found an unqualified INSTEAD rule, - * then *qual_product won't be used, so don't bother building it. + * If we have already found an unqualified INSTEAD rule, then + * *qual_product won't be used, so don't bother building it. */ - if (! *instead_flag) + if (!*instead_flag) { if (*qual_product == NULL) *qual_product = parsetree; @@ -1093,8 +1095,8 @@ RewriteQuery(Query *parsetree, List *rewrite_events) * If the statement is an update, insert or delete - fire rules on it. * * SELECT rules are handled later when we have all the queries that - * should get executed. Also, utilities aren't rewritten at all - * (do we still need that check?) + * should get executed. Also, utilities aren't rewritten at all (do + * we still need that check?) */ if (event != CMD_SELECT && event != CMD_UTILITY) { @@ -1109,19 +1111,21 @@ RewriteQuery(Query *parsetree, List *rewrite_events) Assert(rt_entry->rtekind == RTE_RELATION); /* - * This may well be the first access to the result relation during the - * current statement (it will be, if this Query was extracted from a - * rule or somehow got here other than via the parser). Therefore, - * grab the appropriate lock type for a result relation, and do not - * release it until end of transaction. This protects the rewriter - * and planner against schema changes mid-query. + * This may well be the first access to the result relation during + * the current statement (it will be, if this Query was extracted + * from a rule or somehow got here other than via the parser). + * Therefore, grab the appropriate lock type for a result + * relation, and do not release it until end of transaction. This + * protects the rewriter and planner against schema changes + * mid-query. */ rt_entry_relation = heap_open(rt_entry->relid, RowExclusiveLock); /* - * If it's an INSERT or UPDATE, rewrite the targetlist into standard - * form. This will be needed by the planner anyway, and doing it now - * ensures that any references to NEW.field will behave sanely. + * If it's an INSERT or UPDATE, rewrite the targetlist into + * standard form. This will be needed by the planner anyway, and + * doing it now ensures that any references to NEW.field will + * behave sanely. */ if (event == CMD_INSERT || event == CMD_UPDATE) rewriteTargetList(parsetree, rt_entry_relation); @@ -1144,8 +1148,8 @@ RewriteQuery(Query *parsetree, List *rewrite_events) &qual_product); /* - * If we got any product queries, recursively rewrite them - * --- but first check for recursion! + * If we got any product queries, recursively rewrite them --- + * but first check for recursion! */ if (product_queries != NIL) { @@ -1158,9 +1162,9 @@ RewriteQuery(Query *parsetree, List *rewrite_events) if (rev->relation == RelationGetRelid(rt_entry_relation) && rev->event == event) ereport(ERROR, - (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("infinite recursion detected in rules for relation \"%s\"", - RelationGetRelationName(rt_entry_relation)))); + (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), + errmsg("infinite recursion detected in rules for relation \"%s\"", + RelationGetRelationName(rt_entry_relation)))); } rev = (rewrite_event *) palloc(sizeof(rewrite_event)); @@ -1179,7 +1183,7 @@ RewriteQuery(Query *parsetree, List *rewrite_events) } } - heap_close(rt_entry_relation, NoLock); /* keep lock! */ + heap_close(rt_entry_relation, NoLock); /* keep lock! */ } /* @@ -1191,9 +1195,9 @@ RewriteQuery(Query *parsetree, List *rewrite_events) * disappear so the scans for them in the rule actions cannot find * them. * - * If we found any unqualified INSTEAD, the original query is not - * done at all, in any form. Otherwise, we add the modified form - * if qualified INSTEADs were found, else the unmodified form. + * If we found any unqualified INSTEAD, the original query is not done at + * all, in any form. Otherwise, we add the modified form if qualified + * INSTEADs were found, else the unmodified form. */ if (!instead) { @@ -1299,7 +1303,8 @@ QueryRewrite(Query *parsetree) * Step 3 * * Determine which, if any, of the resulting queries is supposed to set - * the command-result tag; and update the canSetTag fields accordingly. + * the command-result tag; and update the canSetTag fields + * accordingly. * * If the original query is still in the list, it sets the command tag. * Otherwise, the last INSTEAD query of the same kind as the original @@ -1308,8 +1313,8 @@ QueryRewrite(Query *parsetree) * setting up a default tag based on the original un-rewritten query.) * * The Asserts verify that at most one query in the result list is marked - * canSetTag. If we aren't checking asserts, we can fall out of the loop - * as soon as we find the original query. + * canSetTag. If we aren't checking asserts, we can fall out of the + * loop as soon as we find the original query. */ origCmdType = parsetree->commandType; foundOriginalQuery = false; diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index f36f96c349..3f06b3f722 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteManip.c,v 1.74 2003/07/25 00:01:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteManip.c,v 1.75 2003/08/04 00:43:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -25,10 +25,10 @@ typedef struct { int sublevels_up; -} checkExprHasAggs_context; +} checkExprHasAggs_context; static bool checkExprHasAggs_walker(Node *node, - checkExprHasAggs_context *context); + checkExprHasAggs_context * context); static bool checkExprHasSubLink_walker(Node *node, void *context); static Relids offset_relid_set(Relids relids, int offset); static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); @@ -51,6 +51,7 @@ checkExprHasAggs(Node *node) checkExprHasAggs_context context; context.sublevels_up = 0; + /* * Must be prepared to start with a Query or a bare expression tree; * if it's a Query, we don't want to increment sublevels_up. @@ -62,7 +63,7 @@ checkExprHasAggs(Node *node) } static bool -checkExprHasAggs_walker(Node *node, checkExprHasAggs_context *context) +checkExprHasAggs_walker(Node *node, checkExprHasAggs_context * context) { if (node == NULL) return false; @@ -173,7 +174,7 @@ OffsetVarNodes_walker(Node *node, OffsetVarNodes_context *context) } if (IsA(node, InClauseInfo)) { - InClauseInfo *ininfo = (InClauseInfo *) node; + InClauseInfo *ininfo = (InClauseInfo *) node; if (context->sublevels_up == 0) { @@ -247,9 +248,7 @@ offset_relid_set(Relids relids, int offset) tmprelids = bms_copy(relids); while ((rtindex = bms_first_member(tmprelids)) >= 0) - { result = bms_add_member(result, rtindex + offset); - } bms_free(tmprelids); return result; } @@ -312,7 +311,7 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) } if (IsA(node, InClauseInfo)) { - InClauseInfo *ininfo = (InClauseInfo *) node; + InClauseInfo *ininfo = (InClauseInfo *) node; if (context->sublevels_up == 0) { @@ -530,7 +529,7 @@ rangeTableEntry_used_walker(Node *node, } if (IsA(node, InClauseInfo)) { - InClauseInfo *ininfo = (InClauseInfo *) node; + InClauseInfo *ininfo = (InClauseInfo *) node; if (context->sublevels_up == 0 && (bms_is_member(context->rt_index, ininfo->lefthand) || diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c index 857e9d4f4f..c1a4666907 100644 --- a/src/backend/storage/buffer/bufmgr.c +++ b/src/backend/storage/buffer/bufmgr.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/buffer/bufmgr.c,v 1.137 2003/07/24 22:04:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/buffer/bufmgr.c,v 1.138 2003/08/04 00:43:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -61,7 +61,7 @@ /* GUC variable */ -bool zero_damaged_pages = false; +bool zero_damaged_pages = false; static void WaitIO(BufferDesc *buf); @@ -232,14 +232,14 @@ ReadBufferInternal(Relation reln, BlockNumber blockNum, ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("invalid page header in block %u of \"%s\"; zeroing out page", - blockNum, RelationGetRelationName(reln)))); + blockNum, RelationGetRelationName(reln)))); MemSet((char *) MAKE_PTR(bufHdr->data), 0, BLCKSZ); } else ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), - errmsg("invalid page header in block %u of \"%s\"", - blockNum, RelationGetRelationName(reln)))); + errmsg("invalid page header in block %u of \"%s\"", + blockNum, RelationGetRelationName(reln)))); } } @@ -959,8 +959,8 @@ AtEOXact_Buffers(bool isCommit) if (isCommit) elog(WARNING, - "buffer refcount leak: [%03d] (freeNext=%d, freePrev=%d, " - "rel=%u/%u, blockNum=%u, flags=0x%x, refcount=%d %ld)", + "buffer refcount leak: [%03d] (freeNext=%d, freePrev=%d, " + "rel=%u/%u, blockNum=%u, flags=0x%x, refcount=%d %ld)", i, buf->freeNext, buf->freePrev, buf->tag.rnode.tblNode, buf->tag.rnode.relNode, buf->tag.blockNum, buf->flags, @@ -1509,10 +1509,10 @@ FlushRelationBuffers(Relation rel, BlockNumber firstDelBlock) if (status == SM_FAIL) /* disk failure ?! */ ereport(PANIC, (errcode(ERRCODE_IO_ERROR), - errmsg("could not write block %u of %u/%u", - bufHdr->tag.blockNum, - bufHdr->tag.rnode.tblNode, - bufHdr->tag.rnode.relNode))); + errmsg("could not write block %u of %u/%u", + bufHdr->tag.blockNum, + bufHdr->tag.rnode.tblNode, + bufHdr->tag.rnode.relNode))); BufferFlushCount++; diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 06606990c5..271a752a62 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/file/fd.c,v 1.99 2003/07/24 22:04:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/file/fd.c,v 1.100 2003/08/04 00:43:23 momjian Exp $ * * NOTES: * @@ -113,8 +113,8 @@ int max_files_per_process = 1000; #define FileUnknownPos (-1L) /* these are the assigned bits in fdstate below: */ -#define FD_TEMPORARY (1 << 0) /* T = delete when closed */ -#define FD_XACT_TEMPORARY (1 << 1) /* T = delete at eoXact */ +#define FD_TEMPORARY (1 << 0) /* T = delete when closed */ +#define FD_XACT_TEMPORARY (1 << 1) /* T = delete at eoXact */ typedef struct vfd { @@ -247,7 +247,7 @@ pg_fdatasync(int fd) * This is exported for use by places that really want a plain kernel FD, * but need to be proof against running out of FDs. Once an FD has been * successfully returned, it is the caller's responsibility to ensure that - * it will not be leaked on ereport()! Most users should *not* call this + * it will not be leaked on ereport()! Most users should *not* call this * routine directly, but instead use the VFD abstraction level, which * provides protection against descriptor leaks as well as management of * files that need to be open for more than a short period of time. @@ -274,7 +274,7 @@ tryAgain: ereport(LOG, (errcode(ERRCODE_INSUFFICIENT_RESOURCES), - errmsg("out of file descriptors: %m; release and retry"))); + errmsg("out of file descriptors: %m; release and retry"))); errno = 0; if (ReleaseLruFile()) goto tryAgain; @@ -1064,7 +1064,7 @@ TryAgain: ereport(LOG, (errcode(ERRCODE_INSUFFICIENT_RESOURCES), - errmsg("out of file descriptors: %m; release and retry"))); + errmsg("out of file descriptors: %m; release and retry"))); errno = 0; if (ReleaseLruFile()) goto TryAgain; @@ -1158,7 +1158,7 @@ AtProcExit_Files(void) static void CleanupTempFiles(bool isProcExit) { - Index i; + Index i; if (SizeVfdCache > 0) { diff --git a/src/backend/storage/freespace/freespace.c b/src/backend/storage/freespace/freespace.c index c7f72aafd6..5d381aa7f3 100644 --- a/src/backend/storage/freespace/freespace.c +++ b/src/backend/storage/freespace/freespace.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/freespace/freespace.c,v 1.18 2003/07/24 22:04:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/freespace/freespace.c,v 1.19 2003/08/04 00:43:24 momjian Exp $ * * * NOTES: @@ -39,7 +39,7 @@ * Actually, our space allocation is done in "chunks" of CHUNKPAGES pages, * with each relation guaranteed at least one chunk. This reduces thrashing * of the storage allocations when there are small changes in the RRFS page - * counts from one VACUUM to the next. (XXX it might also be worthwhile to + * counts from one VACUUM to the next. (XXX it might also be worthwhile to * impose some kind of moving-average smoothing on the RRFS page counts?) * * So the actual arithmetic is: for each relation compute myRequest as the @@ -72,10 +72,10 @@ /* Initial value for average-request moving average */ -#define INITIAL_AVERAGE ((Size) (BLCKSZ / 32)) +#define INITIAL_AVERAGE ((Size) (BLCKSZ / 32)) /* - * Number of pages and bytes per allocation chunk. Indexes can squeeze 50% + * Number of pages and bytes per allocation chunk. Indexes can squeeze 50% * more pages into the same space because they don't need to remember how much * free space on each page. The nominal number of pages, CHUNKPAGES, is for * regular rels, and INDEXCHUNKPAGES is for indexes. CHUNKPAGES should be @@ -83,7 +83,7 @@ */ #define CHUNKPAGES 16 #define CHUNKBYTES (CHUNKPAGES * sizeof(FSMPageData)) -#define INDEXCHUNKPAGES ((int) (CHUNKBYTES / sizeof(IndexFSMPageData))) +#define INDEXCHUNKPAGES ((int) (CHUNKBYTES / sizeof(IndexFSMPageData))) /* @@ -104,9 +104,9 @@ typedef BlockIdData IndexFSMPageData; BlockIdSet(&(ptr)->ip_blkid, pg) #define FSMPageSetSpace(ptr, sz) \ ((ptr)->ip_posid = (OffsetNumber) (sz)) -#define IndexFSMPageGetPageNum(ptr) \ +#define IndexFSMPageGetPageNum(ptr) \ BlockIdGetBlockNumber(ptr) -#define IndexFSMPageSetPageNum(ptr, pg) \ +#define IndexFSMPageSetPageNum(ptr, pg) \ BlockIdSet(ptr, pg) /*---------- @@ -144,7 +144,7 @@ typedef struct FsmCacheFileHeader uint32 endian; uint32 version; int32 numRels; -} FsmCacheFileHeader; +} FsmCacheFileHeader; /* Per-relation header */ typedef struct FsmCacheRelHeader @@ -154,7 +154,7 @@ typedef struct FsmCacheRelHeader uint32 avgRequest; /* moving average of space requests */ int32 lastPageCount; /* pages passed to RecordRelationFreeSpace */ int32 storedPages; /* # of pages stored in arena */ -} FsmCacheRelHeader; +} FsmCacheRelHeader; /* @@ -167,7 +167,7 @@ typedef struct FsmCacheRelHeader * * Each relation owns one or more chunks of per-page storage in the "arena". * The chunks for each relation are always consecutive, so that it can treat - * its page storage as a simple array. We further insist that its page data + * its page storage as a simple array. We further insist that its page data * be ordered by block number, so that binary search is possible. * * Note: we handle pointers to these items as pointers, not as SHMEM_OFFSETs. @@ -182,7 +182,7 @@ struct FSMHeader { HTAB *relHash; /* hashtable of FSMRelation entries */ FSMRelation *usageList; /* FSMRelations in usage-recency order */ - FSMRelation *usageListTail; /* tail of usage-recency list */ + FSMRelation *usageListTail; /* tail of usage-recency list */ FSMRelation *firstRel; /* FSMRelations in arena storage order */ FSMRelation *lastRel; /* tail of storage-order list */ int numRels; /* number of FSMRelations now in use */ @@ -204,7 +204,7 @@ struct FSMRelation FSMRelation *nextUsage; /* next rel in usage-recency order */ FSMRelation *priorUsage; /* prior rel in usage-recency order */ FSMRelation *nextPhysical; /* next rel in arena-storage order */ - FSMRelation *priorPhysical; /* prior rel in arena-storage order */ + FSMRelation *priorPhysical; /* prior rel in arena-storage order */ bool isIndex; /* if true, we store only page numbers */ Size avgRequest; /* moving average of space requests */ int lastPageCount; /* pages passed to RecordRelationFreeSpace */ @@ -233,13 +233,13 @@ static BlockNumber find_index_free_space(FSMRelation *fsmrel); static void fsm_record_free_space(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail); static bool lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, - int *outPageIndex); + int *outPageIndex); static void compact_fsm_storage(void); static void push_fsm_rels_after(FSMRelation *afterRel); -static void pack_incoming_pages(FSMPageData *newLocation, int newPages, - PageFreeSpaceInfo *pageSpaces, int nPages); -static void pack_existing_pages(FSMPageData *newLocation, int newPages, - FSMPageData *oldLocation, int oldPages); +static void pack_incoming_pages(FSMPageData * newLocation, int newPages, + PageFreeSpaceInfo * pageSpaces, int nPages); +static void pack_existing_pages(FSMPageData * newLocation, int newPages, + FSMPageData * oldLocation, int oldPages); static int fsm_calc_request(FSMRelation *fsmrel); static int fsm_calc_target_allocation(int myRequest); static int fsm_current_chunks(FSMRelation *fsmrel); @@ -271,7 +271,7 @@ InitFreeSpaceMap(void) if (FreeSpaceMap == NULL) ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("insufficient shared memory for free space map"))); + errmsg("insufficient shared memory for free space map"))); MemSet(FreeSpaceMap, 0, sizeof(FSMHeader)); /* Create hashtable for FSMRelations */ @@ -288,7 +288,7 @@ InitFreeSpaceMap(void) if (!FreeSpaceMap->relHash) ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("insufficient shared memory for free space map"))); + errmsg("insufficient shared memory for free space map"))); /* Allocate page-storage arena */ nchunks = (MaxFSMPages - 1) / CHUNKPAGES + 1; @@ -296,14 +296,14 @@ InitFreeSpaceMap(void) if (nchunks <= MaxFSMRelations) ereport(FATAL, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("max_fsm_pages must exceed max_fsm_relations * %d", - CHUNKPAGES))); + errmsg("max_fsm_pages must exceed max_fsm_relations * %d", + CHUNKPAGES))); FreeSpaceMap->arena = (char *) ShmemAlloc(nchunks * CHUNKBYTES); if (FreeSpaceMap->arena == NULL) ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("insufficient shared memory for free space map"))); + errmsg("insufficient shared memory for free space map"))); FreeSpaceMap->totalChunks = nchunks; FreeSpaceMap->usedChunks = 0; @@ -348,7 +348,7 @@ FreeSpaceShmemSize(void) * will turn out to have too little space available by the time the caller * gets a lock on it. In that case, the caller should report the actual * amount of free space available on that page and then try again (see - * RecordAndGetPageWithFreeSpace). If InvalidBlockNumber is returned, + * RecordAndGetPageWithFreeSpace). If InvalidBlockNumber is returned, * extend the relation. */ BlockNumber @@ -365,10 +365,10 @@ GetPageWithFreeSpace(RelFileNode *rel, Size spaceNeeded) fsmrel = create_fsm_rel(rel); /* - * Update the moving average of space requests. This code implements an - * exponential moving average with an equivalent period of about 63 - * requests. Ignore silly requests, however, to ensure that the average - * stays sane. + * Update the moving average of space requests. This code implements + * an exponential moving average with an equivalent period of about 63 + * requests. Ignore silly requests, however, to ensure that the + * average stays sane. */ if (spaceNeeded > 0 && spaceNeeded < BLCKSZ) { @@ -409,6 +409,7 @@ RecordAndGetPageWithFreeSpace(RelFileNode *rel, /* Do the Record */ fsm_record_free_space(fsmrel, oldPage, oldSpaceAvail); + /* * Update the moving average of space requests, same as in * GetPageWithFreeSpace. @@ -458,7 +459,7 @@ GetAvgFSMRequestSize(RelFileNode *rel) void RecordRelationFreeSpace(RelFileNode *rel, int nPages, - PageFreeSpaceInfo *pageSpaces) + PageFreeSpaceInfo * pageSpaces) { FSMRelation *fsmrel; @@ -469,11 +470,12 @@ RecordRelationFreeSpace(RelFileNode *rel, nPages = MaxFSMPages; LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE); + /* * Note we don't record info about a relation unless there's already * an FSM entry for it, implying someone has done GetPageWithFreeSpace - * for it. Inactive rels thus will not clutter the map simply by being - * vacuumed. + * for it. Inactive rels thus will not clutter the map simply by + * being vacuumed. */ fsmrel = lookup_fsm_rel(rel); if (fsmrel) @@ -484,6 +486,7 @@ RecordRelationFreeSpace(RelFileNode *rel, curAlloc = realloc_fsm_rel(fsmrel, nPages, false); curAllocPages = curAlloc * CHUNKPAGES; + /* * If the data fits in our current allocation, just copy it; * otherwise must compress. @@ -500,7 +503,7 @@ RecordRelationFreeSpace(RelFileNode *rel, Size avail = pageSpaces[i].avail; /* Check caller provides sorted data */ - if (i > 0 && page <= pageSpaces[i-1].blkno) + if (i > 0 && page <= pageSpaces[i - 1].blkno) elog(ERROR, "free-space data is not in page order"); FSMPageSetPageNum(newLocation, page); FSMPageSetSpace(newLocation, avail); @@ -556,10 +559,11 @@ RecordIndexFreeSpace(RelFileNode *rel, nPages = MaxFSMPages; LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE); + /* * Note we don't record info about a relation unless there's already - * an FSM entry for it, implying someone has done GetFreeIndexPage - * for it. Inactive rels thus will not clutter the map simply by being + * an FSM entry for it, implying someone has done GetFreeIndexPage for + * it. Inactive rels thus will not clutter the map simply by being * vacuumed. */ fsmrel = lookup_fsm_rel(rel); @@ -572,6 +576,7 @@ RecordIndexFreeSpace(RelFileNode *rel, curAlloc = realloc_fsm_rel(fsmrel, nPages, true); curAllocPages = curAlloc * INDEXCHUNKPAGES; + /* * If the data fits in our current allocation, just copy it; * otherwise must compress. But compression is easy: we merely @@ -587,7 +592,7 @@ RecordIndexFreeSpace(RelFileNode *rel, BlockNumber page = pages[i]; /* Check caller provides sorted data */ - if (i > 0 && page <= pages[i-1]) + if (i > 0 && page <= pages[i - 1]) elog(ERROR, "free-space data is not in page order"); IndexFSMPageSetPageNum(newLocation, page); newLocation++; @@ -660,7 +665,7 @@ FreeSpaceMapForgetDatabase(Oid dbid) LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE); for (fsmrel = FreeSpaceMap->usageList; fsmrel; fsmrel = nextrel) { - nextrel = fsmrel->nextUsage; /* in case we delete it */ + nextrel = fsmrel->nextUsage; /* in case we delete it */ if (fsmrel->key.tblNode == dbid) delete_fsm_rel(fsmrel); } @@ -670,7 +675,7 @@ FreeSpaceMapForgetDatabase(Oid dbid) /* * PrintFreeSpaceMapStatistics - print statistics about FSM contents * - * The info is sent to ereport() with the specified message level. This is + * The info is sent to ereport() with the specified message level. This is * intended for use during VACUUM. */ void @@ -687,9 +692,7 @@ PrintFreeSpaceMapStatistics(int elevel) for (fsmrel = FreeSpaceMap->firstRel; fsmrel != NULL; fsmrel = fsmrel->nextPhysical) - { storedPages += fsmrel->storedPages; - } /* Copy other stats before dropping lock */ numRels = FreeSpaceMap->numRels; sumRequests = FreeSpaceMap->sumRequests; @@ -808,7 +811,7 @@ write_failed: * forma --- if anyone else is accessing FSM yet, there's a problem. * * Notes: no complaint is issued if no cache file is found. If the file is - * found, it is deleted after reading. Thus, if we crash without a clean + * found, it is deleted after reading. Thus, if we crash without a clean * shutdown, the next cycle of life starts with no FSM data. To do otherwise, * we'd need to do significantly more validation in this routine, because of * the likelihood that what is in the dump file would be out-of-date, eg @@ -879,7 +882,7 @@ LoadFreeSpaceMap(void) len = nPages * sizeof(IndexFSMPageData); else len = nPages * sizeof(FSMPageData); - data = (char *) palloc(len + 1); /* +1 to avoid palloc(0) */ + data = (char *) palloc(len + 1); /* +1 to avoid palloc(0) */ if (fread(data, 1, len, fp) != len) { elog(LOG, "premature EOF in \"%s\"", cachefilename); @@ -888,7 +891,7 @@ LoadFreeSpaceMap(void) } /* - * Okay, create the FSM entry and insert data into it. Since the + * Okay, create the FSM entry and insert data into it. Since the * rels were stored in reverse usage order, at the end of the loop * they will be correctly usage-ordered in memory; and if * MaxFSMRelations is less than it used to be, we will correctly @@ -904,10 +907,11 @@ LoadFreeSpaceMap(void) IndexFSMPageData *newLocation; curAllocPages = curAlloc * INDEXCHUNKPAGES; + /* * If the data fits in our current allocation, just copy it; - * otherwise must compress. But compression is easy: we merely - * forget extra pages. + * otherwise must compress. But compression is easy: we + * merely forget extra pages. */ newLocation = (IndexFSMPageData *) (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES); @@ -921,6 +925,7 @@ LoadFreeSpaceMap(void) FSMPageData *newLocation; curAllocPages = curAlloc * CHUNKPAGES; + /* * If the data fits in our current allocation, just copy it; * otherwise must compress. @@ -1005,7 +1010,7 @@ create_fsm_rel(RelFileNode *rel) fsmrel->isIndex = false; /* until we learn different */ fsmrel->avgRequest = INITIAL_AVERAGE; fsmrel->lastPageCount = 0; - fsmrel->firstChunk = -1; /* no space allocated */ + fsmrel->firstChunk = -1; /* no space allocated */ fsmrel->storedPages = 0; fsmrel->nextPage = 0; @@ -1015,7 +1020,7 @@ create_fsm_rel(RelFileNode *rel) /* Add new entry at front of LRU list */ link_fsm_rel_usage(fsmrel); - fsmrel->nextPhysical = NULL; /* not in physical-storage list */ + fsmrel->nextPhysical = NULL; /* not in physical-storage list */ fsmrel->priorPhysical = NULL; FreeSpaceMap->numRels++; /* sumRequests is unchanged because request must be zero */ @@ -1076,14 +1081,15 @@ realloc_fsm_rel(FSMRelation *fsmrel, int nPages, bool isIndex) myRequest = fsm_calc_request(fsmrel); FreeSpaceMap->sumRequests += myRequest; myAlloc = fsm_calc_target_allocation(myRequest); + /* - * Need to reallocate space if (a) my target allocation is more - * than my current allocation, AND (b) my actual immediate need - * (myRequest+1 chunks) is more than my current allocation. - * Otherwise just store the new data in-place. + * Need to reallocate space if (a) my target allocation is more than + * my current allocation, AND (b) my actual immediate need + * (myRequest+1 chunks) is more than my current allocation. Otherwise + * just store the new data in-place. */ curAlloc = fsm_current_allocation(fsmrel); - if (myAlloc > curAlloc && (myRequest+1) > curAlloc && nPages > 0) + if (myAlloc > curAlloc && (myRequest + 1) > curAlloc && nPages > 0) { /* Remove entry from storage list, and compact */ unlink_fsm_rel_storage(fsmrel); @@ -1133,6 +1139,7 @@ unlink_fsm_rel_usage(FSMRelation *fsmrel) fsmrel->nextUsage->priorUsage = fsmrel->priorUsage; else FreeSpaceMap->usageListTail = fsmrel->priorUsage; + /* * We don't bother resetting fsmrel's links, since it's about to be * deleted or relinked at the head. @@ -1212,7 +1219,8 @@ find_free_space(FSMRelation *fsmrel, Size spaceNeeded) if (spaceAvail >= spaceNeeded) { /* - * Found what we want --- adjust the entry, and update nextPage. + * Found what we want --- adjust the entry, and update + * nextPage. */ FSMPageSetSpace(page, spaceAvail - spaceNeeded); fsmrel->nextPage = pageIndex + 1; @@ -1233,12 +1241,12 @@ static BlockNumber find_index_free_space(FSMRelation *fsmrel) { IndexFSMPageData *info; - BlockNumber result; + BlockNumber result; /* * If isIndex isn't set, it could be that RecordIndexFreeSpace() has - * never yet been called on this relation, and we're still looking - * at the default setting from create_fsm_rel(). If so, just act as + * never yet been called on this relation, and we're still looking at + * the default setting from create_fsm_rel(). If so, just act as * though there's no space. */ if (!fsmrel->isIndex) @@ -1247,14 +1255,15 @@ find_index_free_space(FSMRelation *fsmrel) return InvalidBlockNumber; elog(ERROR, "find_index_free_space called for a non-index relation"); } + /* - * For indexes, there's no need for the nextPage state variable; we just - * remove and return the first available page. (We could save cycles here - * by returning the last page, but it seems better to encourage re-use - * of lower-numbered pages.) + * For indexes, there's no need for the nextPage state variable; we + * just remove and return the first available page. (We could save + * cycles here by returning the last page, but it seems better to + * encourage re-use of lower-numbered pages.) */ if (fsmrel->storedPages <= 0) - return InvalidBlockNumber; /* no pages available */ + return InvalidBlockNumber; /* no pages available */ info = (IndexFSMPageData *) (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES); result = IndexFSMPageGetPageNum(info); @@ -1287,8 +1296,8 @@ fsm_record_free_space(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail) else { /* - * No existing entry; ignore the call. We used to add the page - * to the FSM --- but in practice, if the page hasn't got enough + * No existing entry; ignore the call. We used to add the page to + * the FSM --- but in practice, if the page hasn't got enough * space to satisfy the caller who's kicking it back to us, then * it's probably uninteresting to everyone else as well. */ @@ -1327,7 +1336,7 @@ lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, while (low <= high) { int middle; - BlockNumber probe; + BlockNumber probe; middle = low + (high - low) / 2; probe = IndexFSMPageGetPageNum(info + middle); @@ -1357,7 +1366,7 @@ lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, while (low <= high) { int middle; - BlockNumber probe; + BlockNumber probe; middle = low + (high - low) / 2; probe = FSMPageGetPageNum(info + middle); @@ -1391,13 +1400,13 @@ compact_fsm_storage(void) fsmrel != NULL; fsmrel = fsmrel->nextPhysical) { - int newAlloc; - int newAllocPages; - int newChunkIndex; - int oldChunkIndex; - int curChunks; - char *newLocation; - char *oldLocation; + int newAlloc; + int newAllocPages; + int newChunkIndex; + int oldChunkIndex; + int curChunks; + char *newLocation; + char *oldLocation; /* * Calculate target allocation, make sure we don't overrun due to @@ -1412,6 +1421,7 @@ compact_fsm_storage(void) newAllocPages = newAlloc * CHUNKPAGES; newChunkIndex = nextChunkIndex; nextChunkIndex += newAlloc; + /* * Determine current size, current and new locations */ @@ -1419,18 +1429,19 @@ compact_fsm_storage(void) oldChunkIndex = fsmrel->firstChunk; newLocation = FreeSpaceMap->arena + newChunkIndex * CHUNKBYTES; oldLocation = FreeSpaceMap->arena + oldChunkIndex * CHUNKBYTES; + /* * It's possible that we have to move data down, not up, if the * allocations of previous rels expanded. This should mean that * our allocation expanded too (or at least got no worse), and * ditto for later rels. So there should be room --- but we might * have to push down following rels to make it. We don't want to - * do the push more than once, so pack everything against the - * end of the arena if so. + * do the push more than once, so pack everything against the end + * of the arena if so. */ if (newChunkIndex > oldChunkIndex) { - int limitChunkIndex; + int limitChunkIndex; if (newAllocPages < fsmrel->storedPages) elog(PANIC, "can't juggle and compress too"); @@ -1455,9 +1466,9 @@ compact_fsm_storage(void) else if (newAllocPages < fsmrel->storedPages) { /* - * Need to compress the page data. For an index, "compression" - * just means dropping excess pages; otherwise we try to keep - * the ones with the most space. + * Need to compress the page data. For an index, + * "compression" just means dropping excess pages; otherwise + * we try to keep the ones with the most space. */ if (fsmrel->isIndex) { @@ -1508,11 +1519,11 @@ push_fsm_rels_after(FSMRelation *afterRel) fsmrel != NULL; fsmrel = fsmrel->priorPhysical) { - int chunkCount; - int newChunkIndex; - int oldChunkIndex; - char *newLocation; - char *oldLocation; + int chunkCount; + int newChunkIndex; + int oldChunkIndex; + char *newLocation; + char *oldLocation; if (fsmrel == afterRel) break; @@ -1549,8 +1560,8 @@ push_fsm_rels_after(FSMRelation *afterRel) #define HISTOGRAM_BINS 64 static void -pack_incoming_pages(FSMPageData *newLocation, int newPages, - PageFreeSpaceInfo *pageSpaces, int nPages) +pack_incoming_pages(FSMPageData * newLocation, int newPages, + PageFreeSpaceInfo * pageSpaces, int nPages) { int histogram[HISTOGRAM_BINS]; int above, @@ -1564,35 +1575,35 @@ pack_incoming_pages(FSMPageData *newLocation, int newPages, MemSet(histogram, 0, sizeof(histogram)); for (i = 0; i < nPages; i++) { - Size avail = pageSpaces[i].avail; + Size avail = pageSpaces[i].avail; if (avail >= BLCKSZ) elog(ERROR, "bogus freespace amount"); - avail /= (BLCKSZ/HISTOGRAM_BINS); + avail /= (BLCKSZ / HISTOGRAM_BINS); histogram[avail]++; } /* Find the breakpoint bin */ above = 0; - for (i = HISTOGRAM_BINS-1; i >= 0; i--) + for (i = HISTOGRAM_BINS - 1; i >= 0; i--) { - int sum = above + histogram[i]; + int sum = above + histogram[i]; if (sum > newPages) break; above = sum; } Assert(i >= 0); - thresholdL = i * BLCKSZ/HISTOGRAM_BINS; /* low bound of bp bin */ - thresholdU = (i+1) * BLCKSZ/HISTOGRAM_BINS; /* hi bound */ + thresholdL = i * BLCKSZ / HISTOGRAM_BINS; /* low bound of bp bin */ + thresholdU = (i + 1) * BLCKSZ / HISTOGRAM_BINS; /* hi bound */ binct = newPages - above; /* number to take from bp bin */ /* And copy the appropriate data */ for (i = 0; i < nPages; i++) { BlockNumber page = pageSpaces[i].blkno; - Size avail = pageSpaces[i].avail; + Size avail = pageSpaces[i].avail; /* Check caller provides sorted data */ - if (i > 0 && page <= pageSpaces[i-1].blkno) + if (i > 0 && page <= pageSpaces[i - 1].blkno) elog(ERROR, "free-space data is not in page order"); /* Save this page? */ if (avail >= thresholdU || @@ -1619,8 +1630,8 @@ pack_incoming_pages(FSMPageData *newLocation, int newPages, * so that we can copy data moving forward in the arrays without problem. */ static void -pack_existing_pages(FSMPageData *newLocation, int newPages, - FSMPageData *oldLocation, int oldPages) +pack_existing_pages(FSMPageData * newLocation, int newPages, + FSMPageData * oldLocation, int oldPages) { int histogram[HISTOGRAM_BINS]; int above, @@ -1634,33 +1645,33 @@ pack_existing_pages(FSMPageData *newLocation, int newPages, MemSet(histogram, 0, sizeof(histogram)); for (i = 0; i < oldPages; i++) { - Size avail = FSMPageGetSpace(oldLocation + i); + Size avail = FSMPageGetSpace(oldLocation + i); /* Shouldn't happen, but test to protect against stack clobber */ if (avail >= BLCKSZ) elog(ERROR, "bogus freespace amount"); - avail /= (BLCKSZ/HISTOGRAM_BINS); + avail /= (BLCKSZ / HISTOGRAM_BINS); histogram[avail]++; } /* Find the breakpoint bin */ above = 0; - for (i = HISTOGRAM_BINS-1; i >= 0; i--) + for (i = HISTOGRAM_BINS - 1; i >= 0; i--) { - int sum = above + histogram[i]; + int sum = above + histogram[i]; if (sum > newPages) break; above = sum; } Assert(i >= 0); - thresholdL = i * BLCKSZ/HISTOGRAM_BINS; /* low bound of bp bin */ - thresholdU = (i+1) * BLCKSZ/HISTOGRAM_BINS; /* hi bound */ + thresholdL = i * BLCKSZ / HISTOGRAM_BINS; /* low bound of bp bin */ + thresholdU = (i + 1) * BLCKSZ / HISTOGRAM_BINS; /* hi bound */ binct = newPages - above; /* number to take from bp bin */ /* And copy the appropriate data */ for (i = 0; i < oldPages; i++) { BlockNumber page = FSMPageGetPageNum(oldLocation + i); - Size avail = FSMPageGetSpace(oldLocation + i); + Size avail = FSMPageGetSpace(oldLocation + i); /* Save this page? */ if (avail >= thresholdU || @@ -1755,13 +1766,9 @@ static int fsm_current_allocation(FSMRelation *fsmrel) { if (fsmrel->nextPhysical != NULL) - { return fsmrel->nextPhysical->firstChunk - fsmrel->firstChunk; - } else if (fsmrel == FreeSpaceMap->lastRel) - { return FreeSpaceMap->usedChunks - fsmrel->firstChunk; - } else { /* it's not in the storage-order list */ diff --git a/src/backend/storage/ipc/ipc.c b/src/backend/storage/ipc/ipc.c index 5cc0f5f2cd..154e39b284 100644 --- a/src/backend/storage/ipc/ipc.c +++ b/src/backend/storage/ipc/ipc.c @@ -13,7 +13,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/ipc/ipc.c,v 1.83 2003/07/24 22:04:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/ipc.c,v 1.84 2003/08/04 00:43:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -74,8 +74,8 @@ void proc_exit(int code) { /* - * Once we set this flag, we are committed to exit. Any ereport() will - * NOT send control back to the main loop, but right back here. + * Once we set this flag, we are committed to exit. Any ereport() + * will NOT send control back to the main loop, but right back here. */ proc_exit_inprogress = true; diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c index 187b75ad55..508149bc42 100644 --- a/src/backend/storage/ipc/ipci.c +++ b/src/backend/storage/ipc/ipci.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/ipc/ipci.c,v 1.54 2003/07/24 22:04:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/ipci.c,v 1.55 2003/08/04 00:43:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -146,4 +146,3 @@ AttachSharedMemoryAndSemaphores(void) { CLOGShmemInit(); } - diff --git a/src/backend/storage/ipc/sinval.c b/src/backend/storage/ipc/sinval.c index 225436ffd9..653dbf8926 100644 --- a/src/backend/storage/ipc/sinval.c +++ b/src/backend/storage/ipc/sinval.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/ipc/sinval.c,v 1.57 2003/07/24 22:04:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/sinval.c,v 1.58 2003/08/04 00:43:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -324,11 +324,10 @@ GetSnapshotData(Snapshot snapshot, bool serializable) * lastBackend would be sufficient. But it seems better to do the * malloc while not holding the lock, so we can't look at lastBackend. * - * if (snapshot->xip != NULL) - * no need to free and reallocate xip; + * if (snapshot->xip != NULL) no need to free and reallocate xip; * - * We can reuse the old xip array, because MaxBackends does not change - * at runtime. + * We can reuse the old xip array, because MaxBackends does not change at + * runtime. */ if (snapshot->xip == NULL) { diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index 757f1df2f4..1106a76c3d 100644 --- a/src/backend/storage/lmgr/deadlock.c +++ b/src/backend/storage/lmgr/deadlock.c @@ -12,7 +12,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/deadlock.c,v 1.21 2003/07/24 22:04:13 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/deadlock.c,v 1.22 2003/08/04 00:43:24 momjian Exp $ * * Interface: * @@ -49,7 +49,7 @@ typedef struct } WAIT_ORDER; /* - * Information saved about each edge in a detected deadlock cycle. This + * Information saved about each edge in a detected deadlock cycle. This * is used to print a diagnostic message upon failure. * * Note: because we want to examine this info after releasing the LockMgrLock, @@ -61,7 +61,7 @@ typedef struct LOCKTAG locktag; /* ID of awaited lock object */ LOCKMODE lockmode; /* type of lock we're waiting for */ int pid; /* PID of blocked backend */ -} DEADLOCK_INFO; +} DEADLOCK_INFO; static bool DeadLockCheckRecurse(PGPROC *proc); @@ -147,7 +147,7 @@ InitDeadLockChecking(void) * We need to consider rearranging at most MaxBackends/2 wait queues * (since it takes at least two waiters in a queue to create a soft * edge), and the expanded form of the wait queues can't involve more - * than MaxBackends total waiters. (But avoid palloc(0) if + * than MaxBackends total waiters. (But avoid palloc(0) if * MaxBackends = 1.) */ waitOrders = (WAIT_ORDER *) @@ -221,7 +221,7 @@ DeadLockCheck(PGPROC *proc) * Call FindLockCycle one more time, to record the correct * deadlockDetails[] for the basic state with no rearrangements. */ - int nSoftEdges; + int nSoftEdges; nWaitOrders = 0; if (!FindLockCycle(proc, possibleConstraints, &nSoftEdges)) @@ -486,7 +486,7 @@ FindLockCycleRecurse(PGPROC *checkProc, lockHolders = &(lock->lockHolders); proclock = (PROCLOCK *) SHMQueueNext(lockHolders, lockHolders, - offsetof(PROCLOCK, lockLink)); + offsetof(PROCLOCK, lockLink)); while (proclock) { @@ -501,11 +501,11 @@ FindLockCycleRecurse(PGPROC *checkProc, ((1 << lm) & conflictMask) != 0) { /* This proc hard-blocks checkProc */ - if (FindLockCycleRecurse(proc, depth+1, + if (FindLockCycleRecurse(proc, depth + 1, softEdges, nSoftEdges)) { /* fill deadlockDetails[] */ - DEADLOCK_INFO *info = &deadlockDetails[depth]; + DEADLOCK_INFO *info = &deadlockDetails[depth]; info->locktag = lock->tag; info->lockmode = checkProc->waitLockMode; @@ -558,11 +558,11 @@ FindLockCycleRecurse(PGPROC *checkProc, if (((1 << proc->waitLockMode) & conflictMask) != 0) { /* This proc soft-blocks checkProc */ - if (FindLockCycleRecurse(proc, depth+1, + if (FindLockCycleRecurse(proc, depth + 1, softEdges, nSoftEdges)) { /* fill deadlockDetails[] */ - DEADLOCK_INFO *info = &deadlockDetails[depth]; + DEADLOCK_INFO *info = &deadlockDetails[depth]; info->locktag = lock->tag; info->lockmode = checkProc->waitLockMode; @@ -599,11 +599,11 @@ FindLockCycleRecurse(PGPROC *checkProc, if (((1 << proc->waitLockMode) & conflictMask) != 0) { /* This proc soft-blocks checkProc */ - if (FindLockCycleRecurse(proc, depth+1, + if (FindLockCycleRecurse(proc, depth + 1, softEdges, nSoftEdges)) { /* fill deadlockDetails[] */ - DEADLOCK_INFO *info = &deadlockDetails[depth]; + DEADLOCK_INFO *info = &deadlockDetails[depth]; info->locktag = lock->tag; info->lockmode = checkProc->waitLockMode; @@ -834,7 +834,6 @@ PrintLockQueue(LOCK *lock, const char *info) printf("\n"); fflush(stdout); } - #endif /* @@ -843,17 +842,17 @@ PrintLockQueue(LOCK *lock, const char *info) void DeadLockReport(void) { - StringInfoData buf; - int i; + StringInfoData buf; + int i; initStringInfo(&buf); for (i = 0; i < nDeadlockDetails; i++) { - DEADLOCK_INFO *info = &deadlockDetails[i]; + DEADLOCK_INFO *info = &deadlockDetails[i]; int nextpid; /* The last proc waits for the first one... */ - if (i < nDeadlockDetails-1) + if (i < nDeadlockDetails - 1) nextpid = info[1].pid; else nextpid = deadlockDetails[0].pid; @@ -900,7 +899,7 @@ RememberSimpleDeadLock(PGPROC *proc1, LOCK *lock, PGPROC *proc2) { - DEADLOCK_INFO *info = &deadlockDetails[0]; + DEADLOCK_INFO *info = &deadlockDetails[0]; info->locktag = lock->tag; info->lockmode = lockmode; diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index 2e71f40c09..9d4c52f75f 100644 --- a/src/backend/storage/lmgr/lock.c +++ b/src/backend/storage/lmgr/lock.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/lock.c,v 1.124 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/lock.c,v 1.125 2003/08/04 00:43:24 momjian Exp $ * * NOTES * Outside modules can create a lock table and acquire/release @@ -127,9 +127,9 @@ inline static void PROCLOCK_PRINT(const char *where, const PROCLOCK *proclockP) { if ( - (((PROCLOCK_LOCKMETHOD(*proclockP) == DEFAULT_LOCKMETHOD && Trace_locks) - || (PROCLOCK_LOCKMETHOD(*proclockP) == USER_LOCKMETHOD && Trace_userlocks)) - && (((LOCK *) MAKE_PTR(proclockP->tag.lock))->tag.relId >= (Oid) Trace_lock_oidmin)) + (((PROCLOCK_LOCKMETHOD(*proclockP) == DEFAULT_LOCKMETHOD && Trace_locks) + || (PROCLOCK_LOCKMETHOD(*proclockP) == USER_LOCKMETHOD && Trace_userlocks)) + && (((LOCK *) MAKE_PTR(proclockP->tag.lock))->tag.relId >= (Oid) Trace_lock_oidmin)) || (Trace_lock_table && (((LOCK *) MAKE_PTR(proclockP->tag.lock))->tag.relId == Trace_lock_table)) ) elog(LOG, @@ -137,8 +137,8 @@ PROCLOCK_PRINT(const char *where, const PROCLOCK *proclockP) where, MAKE_OFFSET(proclockP), proclockP->tag.lock, PROCLOCK_LOCKMETHOD(*(proclockP)), proclockP->tag.proc, proclockP->tag.xid, - proclockP->holding[1], proclockP->holding[2], proclockP->holding[3], - proclockP->holding[4], proclockP->holding[5], proclockP->holding[6], + proclockP->holding[1], proclockP->holding[2], proclockP->holding[3], + proclockP->holding[4], proclockP->holding[5], proclockP->holding[6], proclockP->holding[7], proclockP->nHolding); } @@ -321,10 +321,10 @@ LockMethodTableInit(char *tabName, sprintf(shmemName, "%s (proclock hash)", tabName); lockMethodTable->proclockHash = ShmemInitHash(shmemName, - init_table_size, - max_table_size, - &info, - hash_flags); + init_table_size, + max_table_size, + &info, + hash_flags); if (!lockMethodTable->proclockHash) elog(FATAL, "could not initialize lock table \"%s\"", tabName); @@ -509,8 +509,8 @@ LockAcquire(LOCKMETHOD lockmethod, LOCKTAG *locktag, /* * Create the hash key for the proclock table. */ - MemSet(&proclocktag, 0, sizeof(PROCLOCKTAG)); /* must clear padding, - * needed */ + MemSet(&proclocktag, 0, sizeof(PROCLOCKTAG)); /* must clear padding, + * needed */ proclocktag.lock = MAKE_OFFSET(lock); proclocktag.proc = MAKE_OFFSET(MyProc); TransactionIdStore(xid, &proclocktag.xid); @@ -520,8 +520,8 @@ LockAcquire(LOCKMETHOD lockmethod, LOCKTAG *locktag, */ proclockTable = lockMethodTable->proclockHash; proclock = (PROCLOCK *) hash_search(proclockTable, - (void *) &proclocktag, - HASH_ENTER, &found); + (void *) &proclocktag, + HASH_ENTER, &found); if (!proclock) { LWLockRelease(masterLock); @@ -604,8 +604,8 @@ LockAcquire(LOCKMETHOD lockmethod, LOCKTAG *locktag, } /* - * If this process (under any XID) is a proclock of the lock, also grant - * myself another one without blocking. + * If this process (under any XID) is a proclock of the lock, also + * grant myself another one without blocking. */ LockCountMyLocks(proclock->tag.lock, MyProc, myHolding); if (myHolding[lockmode] > 0) @@ -649,8 +649,8 @@ LockAcquire(LOCKMETHOD lockmethod, LOCKTAG *locktag, SHMQueueDelete(&proclock->lockLink); SHMQueueDelete(&proclock->procLink); proclock = (PROCLOCK *) hash_search(proclockTable, - (void *) proclock, - HASH_REMOVE, NULL); + (void *) proclock, + HASH_REMOVE, NULL); if (!proclock) elog(WARNING, "proclock table corrupted"); } @@ -818,7 +818,7 @@ LockCountMyLocks(SHMEM_OFFSET lockOffset, PGPROC *proc, int *myHolding) MemSet(myHolding, 0, MAX_LOCKMODES * sizeof(int)); proclock = (PROCLOCK *) SHMQueueNext(procHolders, procHolders, - offsetof(PROCLOCK, procLink)); + offsetof(PROCLOCK, procLink)); while (proclock) { @@ -908,9 +908,10 @@ WaitOnLock(LOCKMETHOD lockmethod, LOCKMODE lockmode, */ LOCK_PRINT("WaitOnLock: aborting on lock", lock, lockmode); LWLockRelease(lockMethodTable->masterLock); + /* - * Now that we aren't holding the LockMgrLock, we can give an error - * report including details about the detected deadlock. + * Now that we aren't holding the LockMgrLock, we can give an + * error report including details about the detected deadlock. */ DeadLockReport(); /* not reached */ @@ -1033,16 +1034,16 @@ LockRelease(LOCKMETHOD lockmethod, LOCKTAG *locktag, /* * Find the proclock entry for this proclock. */ - MemSet(&proclocktag, 0, sizeof(PROCLOCKTAG)); /* must clear padding, - * needed */ + MemSet(&proclocktag, 0, sizeof(PROCLOCKTAG)); /* must clear padding, + * needed */ proclocktag.lock = MAKE_OFFSET(lock); proclocktag.proc = MAKE_OFFSET(MyProc); TransactionIdStore(xid, &proclocktag.xid); proclockTable = lockMethodTable->proclockHash; proclock = (PROCLOCK *) hash_search(proclockTable, - (void *) &proclocktag, - HASH_FIND_SAVE, NULL); + (void *) &proclocktag, + HASH_FIND_SAVE, NULL); if (!proclock) { LWLockRelease(masterLock); @@ -1143,8 +1144,8 @@ LockRelease(LOCKMETHOD lockmethod, LOCKTAG *locktag, SHMQueueDelete(&proclock->lockLink); SHMQueueDelete(&proclock->procLink); proclock = (PROCLOCK *) hash_search(proclockTable, - (void *) &proclock, - HASH_REMOVE_SAVED, NULL); + (void *) &proclock, + HASH_REMOVE_SAVED, NULL); if (!proclock) { LWLockRelease(masterLock); @@ -1207,7 +1208,7 @@ LockReleaseAll(LOCKMETHOD lockmethod, PGPROC *proc, LWLockAcquire(masterLock, LW_EXCLUSIVE); proclock = (PROCLOCK *) SHMQueueNext(procHolders, procHolders, - offsetof(PROCLOCK, procLink)); + offsetof(PROCLOCK, procLink)); while (proclock) { @@ -1295,9 +1296,9 @@ LockReleaseAll(LOCKMETHOD lockmethod, PGPROC *proc, * remove the proclock entry from the hashtable */ proclock = (PROCLOCK *) hash_search(lockMethodTable->proclockHash, - (void *) proclock, - HASH_REMOVE, - NULL); + (void *) proclock, + HASH_REMOVE, + NULL); if (!proclock) { LWLockRelease(masterLock); @@ -1466,7 +1467,7 @@ DumpLocks(void) LOCK_PRINT("DumpLocks: waiting on", proc->waitLock, 0); proclock = (PROCLOCK *) SHMQueueNext(procHolders, procHolders, - offsetof(PROCLOCK, procLink)); + offsetof(PROCLOCK, procLink)); while (proclock) { diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index eebd696c2c..3bdda5924d 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/proc.c,v 1.131 2003/07/24 22:04:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/proc.c,v 1.132 2003/08/04 00:43:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -78,6 +78,7 @@ static bool waitingForSignal = false; /* Mark these volatile because they can be changed by signal handler */ static volatile bool statement_timeout_active = false; static volatile bool deadlock_timeout_active = false; + /* statement_fin_time is valid only if statement_timeout_active is true */ static struct timeval statement_fin_time; @@ -571,7 +572,8 @@ ProcSleep(LOCKMETHODTABLE *lockMethodTable, * up correctly is to call RemoveFromWaitQueue(), but * we can't do that until we are *on* the wait queue. * So, set a flag to check below, and break out of - * loop. Also, record deadlock info for later message. + * loop. Also, record deadlock info for later + * message. */ RememberSimpleDeadLock(MyProc, lockmode, lock, proc); early_deadlock = true; @@ -950,11 +952,13 @@ bool enable_sig_alarm(int delayms, bool is_statement_timeout) { #ifdef WIN32 -# warning add Win32 timer +#warning add Win32 timer #else struct timeval fin_time; + #ifndef __BEOS__ struct itimerval timeval; + #else bigtime_t time_interval; #endif @@ -984,16 +988,16 @@ enable_sig_alarm(int delayms, bool is_statement_timeout) /* * Begin deadlock timeout with statement-level timeout active * - * Here, we want to interrupt at the closer of the two timeout - * times. If fin_time >= statement_fin_time then we need not - * touch the existing timer setting; else set up to interrupt - * at the deadlock timeout time. + * Here, we want to interrupt at the closer of the two timeout times. + * If fin_time >= statement_fin_time then we need not touch the + * existing timer setting; else set up to interrupt at the + * deadlock timeout time. * * NOTE: in this case it is possible that this routine will be * interrupted by the previously-set timer alarm. This is okay - * because the signal handler will do only what it should do according - * to the state variables. The deadlock checker may get run earlier - * than normal, but that does no harm. + * because the signal handler will do only what it should do + * according to the state variables. The deadlock checker may get + * run earlier than normal, but that does no harm. */ deadlock_timeout_active = true; if (fin_time.tv_sec > statement_fin_time.tv_sec || @@ -1037,6 +1041,7 @@ disable_sig_alarm(bool is_statement_timeout) #ifdef WIN32 #warning add Win32 timer #else + /* * Always disable the interrupt if it is active; this avoids being * interrupted by the signal handler and thereby possibly getting diff --git a/src/backend/storage/page/bufpage.c b/src/backend/storage/page/bufpage.c index b8766ae6ab..2441534b46 100644 --- a/src/backend/storage/page/bufpage.c +++ b/src/backend/storage/page/bufpage.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/page/bufpage.c,v 1.53 2003/07/24 22:04:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/page/bufpage.c,v 1.54 2003/08/04 00:43:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -50,7 +50,7 @@ PageInit(Page page, Size pageSize, Size specialSize) * PageHeaderIsValid * Check that the header fields of a page appear valid. * - * This is called when a page has just been read in from disk. The idea is + * This is called when a page has just been read in from disk. The idea is * to cheaply detect trashed pages before we go nuts following bogus item * pointers, testing invalid transaction identifiers, etc. * @@ -135,7 +135,7 @@ PageAddItem(Page page, ereport(PANIC, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("corrupted page pointers: lower = %u, upper = %u, special = %u", - phdr->pd_lower, phdr->pd_upper, phdr->pd_special))); + phdr->pd_lower, phdr->pd_upper, phdr->pd_special))); /* * Select offsetNumber to place the new item at @@ -391,8 +391,8 @@ PageRepairFragmentation(Page page, OffsetNumber *unused) if (totallen > (Size) (pd_special - pd_lower)) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), - errmsg("corrupted item lengths: total %u, available space %u", - (unsigned int) totallen, pd_special - pd_lower))); + errmsg("corrupted item lengths: total %u, available space %u", + (unsigned int) totallen, pd_special - pd_lower))); /* sort itemIdSortData array into decreasing itemoff order */ qsort((char *) itemidbase, nused, sizeof(struct itemIdSortData), @@ -472,7 +472,7 @@ PageIndexTupleDelete(Page page, OffsetNumber offnum) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("corrupted page pointers: lower = %u, upper = %u, special = %u", - phdr->pd_lower, phdr->pd_upper, phdr->pd_special))); + phdr->pd_lower, phdr->pd_upper, phdr->pd_special))); nline = PageGetMaxOffsetNumber(page); if ((int) offnum <= 0 || (int) offnum > nline) @@ -533,7 +533,8 @@ PageIndexTupleDelete(Page page, OffsetNumber offnum) */ if (!PageIsEmpty(page)) { - int i; + int i; + nline--; /* there's one less than when we started */ for (i = 1; i <= nline; i++) { diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c index bd46d3dbd5..420413a510 100644 --- a/src/backend/storage/smgr/md.c +++ b/src/backend/storage/smgr/md.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/smgr/md.c,v 1.96 2003/07/28 00:09:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/smgr/md.c,v 1.97 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -571,12 +571,13 @@ mdnblocks(Relation reln) segno = 0; /* - * Skip through any segments that aren't the last one, to avoid redundant - * seeks on them. We have previously verified that these segments are - * exactly RELSEG_SIZE long, and it's useless to recheck that each time. - * (NOTE: this assumption could only be wrong if another backend has - * truncated the relation. We rely on higher code levels to handle that - * scenario by closing and re-opening the md fd.) + * Skip through any segments that aren't the last one, to avoid + * redundant seeks on them. We have previously verified that these + * segments are exactly RELSEG_SIZE long, and it's useless to recheck + * that each time. (NOTE: this assumption could only be wrong if + * another backend has truncated the relation. We rely on higher code + * levels to handle that scenario by closing and re-opening the md + * fd.) */ while (v->mdfd_chain != (MdfdVec *) NULL) { diff --git a/src/backend/tcop/dest.c b/src/backend/tcop/dest.c index 76990d34f7..7ea881e84a 100644 --- a/src/backend/tcop/dest.c +++ b/src/backend/tcop/dest.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/tcop/dest.c,v 1.59 2003/07/22 19:00:11 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/dest.c,v 1.60 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -93,7 +93,7 @@ BeginCommand(const char *commandTag, CommandDest dest) * CreateDestReceiver - return appropriate receiver function set for dest * * Note: a Portal must be specified for destinations Remote, RemoteExecute, - * and Tuplestore. It can be NULL for the others. + * and Tuplestore. It can be NULL for the others. * ---------------- */ DestReceiver * @@ -173,8 +173,9 @@ NullCommand(CommandDest dest) case RemoteExecute: /* - * tell the fe that we saw an empty query string. In protocols - * before 3.0 this has a useless empty-string message body. + * tell the fe that we saw an empty query string. In + * protocols before 3.0 this has a useless empty-string + * message body. */ if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3) pq_putemptymessage('I'); diff --git a/src/backend/tcop/fastpath.c b/src/backend/tcop/fastpath.c index b86d657ea2..7ccc3f80c6 100644 --- a/src/backend/tcop/fastpath.c +++ b/src/backend/tcop/fastpath.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/tcop/fastpath.c,v 1.66 2003/08/01 00:15:22 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/fastpath.c,v 1.67 2003/08/04 00:43:25 momjian Exp $ * * NOTES * This cruft is the server side of PQfn. @@ -53,10 +53,10 @@ struct fp_info }; -static int16 parse_fcall_arguments(StringInfo msgBuf, struct fp_info *fip, - FunctionCallInfo fcinfo); -static int16 parse_fcall_arguments_20(StringInfo msgBuf, struct fp_info *fip, - FunctionCallInfo fcinfo); +static int16 parse_fcall_arguments(StringInfo msgBuf, struct fp_info * fip, + FunctionCallInfo fcinfo); +static int16 parse_fcall_arguments_20(StringInfo msgBuf, struct fp_info * fip, + FunctionCallInfo fcinfo); /* ---------------- @@ -103,8 +103,8 @@ GetOldFunctionMessage(StringInfo buf) /* FATAL here since no hope of regaining message sync */ ereport(FATAL, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid argument size %d in function call message", - argsize))); + errmsg("invalid argument size %d in function call message", + argsize))); } /* and arg contents */ if (argsize > 0) @@ -158,8 +158,8 @@ SendFunctionResult(Datum retval, bool isnull, Oid rettype, int16 format) &typoutput, &typelem, &typisvarlena); outputstr = DatumGetCString(OidFunctionCall3(typoutput, retval, - ObjectIdGetDatum(typelem), - Int32GetDatum(-1))); + ObjectIdGetDatum(typelem), + Int32GetDatum(-1))); pq_sendcountedtext(&buf, outputstr, strlen(outputstr), false); pfree(outputstr); } @@ -174,7 +174,7 @@ SendFunctionResult(Datum retval, bool isnull, Oid rettype, int16 format) &typsend, &typelem, &typisvarlena); outputbytes = DatumGetByteaP(OidFunctionCall2(typsend, retval, - ObjectIdGetDatum(typelem))); + ObjectIdGetDatum(typelem))); /* We assume the result will not have been toasted */ pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4); pq_sendbytes(&buf, VARDATA(outputbytes), @@ -255,11 +255,11 @@ fetch_fp_info(Oid func_id, struct fp_info * fip) * and will pass it in msgBuf. * In old protocol, the passed msgBuf is empty and we must read the * message here. - * + * * RETURNS: * 0 if successful completion, EOF if frontend connection lost. * - * Note: All ordinary errors result in ereport(ERROR,...). However, + * Note: All ordinary errors result in ereport(ERROR,...). However, * if we lose the frontend connection there is no one to ereport to, * and no use in proceeding... * @@ -303,15 +303,15 @@ HandleFunctionRequest(StringInfo msgBuf) ereport(ERROR, (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION), errmsg("current transaction is aborted, " - "queries ignored until end of transaction block"))); + "queries ignored until end of transaction block"))); /* * Begin parsing the buffer contents. */ if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3) - (void) pq_getmsgstring(msgBuf); /* dummy string */ + (void) pq_getmsgstring(msgBuf); /* dummy string */ - fid = (Oid) pq_getmsgint(msgBuf, 4); /* function oid */ + fid = (Oid) pq_getmsgint(msgBuf, 4); /* function oid */ /* * There used to be a lame attempt at caching lookup info here. Now we @@ -359,7 +359,7 @@ HandleFunctionRequest(StringInfo msgBuf) callit = true; if (fip->flinfo.fn_strict) { - int i; + int i; for (i = 0; i < fcinfo.nargs; i++) { @@ -394,7 +394,7 @@ HandleFunctionRequest(StringInfo msgBuf) * is returned. */ static int16 -parse_fcall_arguments(StringInfo msgBuf, struct fp_info *fip, +parse_fcall_arguments(StringInfo msgBuf, struct fp_info * fip, FunctionCallInfo fcinfo) { int nargs; @@ -447,8 +447,8 @@ parse_fcall_arguments(StringInfo msgBuf, struct fp_info *fip, if (argsize < 0) ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid argument size %d in function call message", - argsize))); + errmsg("invalid argument size %d in function call message", + argsize))); /* Reset abuf to empty, and insert raw data into it */ abuf.len = 0; @@ -473,11 +473,11 @@ parse_fcall_arguments(StringInfo msgBuf, struct fp_info *fip, char *pstring; getTypeInputInfo(fip->argtypes[i], &typInput, &typElem); + /* - * Since stringinfo.c keeps a trailing null in - * place even for binary data, the contents of - * abuf are a valid C string. We have to do - * encoding conversion before calling the typinput + * Since stringinfo.c keeps a trailing null in place even for + * binary data, the contents of abuf are a valid C string. We + * have to do encoding conversion before calling the typinput * routine, though. */ pstring = (char *) @@ -528,7 +528,7 @@ parse_fcall_arguments(StringInfo msgBuf, struct fp_info *fip, * is returned. */ static int16 -parse_fcall_arguments_20(StringInfo msgBuf, struct fp_info *fip, +parse_fcall_arguments_20(StringInfo msgBuf, struct fp_info * fip, FunctionCallInfo fcinfo) { int nargs; @@ -570,8 +570,8 @@ parse_fcall_arguments_20(StringInfo msgBuf, struct fp_info *fip, if (argsize < 0) ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid argument size %d in function call message", - argsize))); + errmsg("invalid argument size %d in function call message", + argsize))); /* Reset abuf to empty, and insert raw data into it */ abuf.len = 0; @@ -593,8 +593,8 @@ parse_fcall_arguments_20(StringInfo msgBuf, struct fp_info *fip, if (abuf.cursor != abuf.len) ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), - errmsg("incorrect binary data format in function argument %d", - i + 1))); + errmsg("incorrect binary data format in function argument %d", + i + 1))); } /* Desired result format is always binary in protocol 2.0 */ diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index 80f2be70ed..cb835469a0 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.353 2003/07/29 00:03:18 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.354 2003/08/04 00:43:25 momjian Exp $ * * NOTES * this is the "main" module of the postgres backend and @@ -133,6 +133,7 @@ static bool EchoQuery = false; /* default don't echo */ #ifndef TCOP_DONTUSENEWLINE static int UseNewLine = 1; /* Use newlines query delimiters (the * default) */ + #else static int UseNewLine = 0; /* Use EOF as query delimiters */ #endif /* TCOP_DONTUSENEWLINE */ @@ -283,8 +284,8 @@ SocketBackend(StringInfo inBuf) /* * Validate message type code before trying to read body; if we have - * lost sync, better to say "command unknown" than to run out of memory - * because we used garbage as a length word. + * lost sync, better to say "command unknown" than to run out of + * memory because we used garbage as a length word. * * This also gives us a place to set the doing_extended_query_message * flag as soon as possible. @@ -300,7 +301,7 @@ SocketBackend(StringInfo inBuf) { ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("unexpected EOF on client connection"))); + errmsg("unexpected EOF on client connection"))); return EOF; } } @@ -327,7 +328,7 @@ SocketBackend(StringInfo inBuf) if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3) ereport(FATAL, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid frontend message type %d", qtype))); + errmsg("invalid frontend message type %d", qtype))); break; case 'S': /* sync */ @@ -339,7 +340,7 @@ SocketBackend(StringInfo inBuf) if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3) ereport(FATAL, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid frontend message type %d", qtype))); + errmsg("invalid frontend message type %d", qtype))); break; case 'd': /* copy data */ @@ -350,14 +351,15 @@ SocketBackend(StringInfo inBuf) if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3) ereport(FATAL, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid frontend message type %d", qtype))); + errmsg("invalid frontend message type %d", qtype))); break; default: + /* - * Otherwise we got garbage from the frontend. We treat this - * as fatal because we have probably lost message boundary sync, - * and there's no good way to recover. + * Otherwise we got garbage from the frontend. We treat this + * as fatal because we have probably lost message boundary + * sync, and there's no good way to recover. */ ereport(FATAL, (errcode(ERRCODE_PROTOCOL_VIOLATION), @@ -409,9 +411,9 @@ ReadCommand(StringInfo inBuf) * but it is still needed for parsing of SQL function bodies. */ List * -pg_parse_and_rewrite(const char *query_string, /* string to execute */ +pg_parse_and_rewrite(const char *query_string, /* string to execute */ Oid *paramTypes, /* parameter types */ - int numParams) /* number of parameters */ + int numParams) /* number of parameters */ { List *raw_parsetree_list; List *querytree_list; @@ -518,8 +520,8 @@ pg_rewrite_queries(List *querytree_list) ResetUsage(); /* - * rewritten queries are collected in new_list. Note there may be more - * or fewer than in the original list. + * rewritten queries are collected in new_list. Note there may be + * more or fewer than in the original list. */ foreach(list_item, querytree_list) { @@ -558,7 +560,7 @@ pg_rewrite_queries(List *querytree_list) /* This checks both copyObject() and the equal() routines... */ if (!equal(new_list, querytree_list)) ereport(WARNING, - (errmsg("copyObject failed to produce an equal parse tree"))); + (errmsg("copyObject failed to produce an equal parse tree"))); else querytree_list = new_list; #endif @@ -603,7 +605,7 @@ pg_plan_query(Query *querytree) /* This checks both copyObject() and the equal() routines... */ if (!equal(new_plan, plan)) ereport(WARNING, - (errmsg("copyObject failed to produce an equal plan tree"))); + (errmsg("copyObject failed to produce an equal plan tree"))); else #endif plan = new_plan; @@ -671,7 +673,7 @@ pg_plan_queries(List *querytrees, bool needSnapshot) static void exec_simple_query(const char *query_string) { - CommandDest dest = whereToSendOutput; + CommandDest dest = whereToSendOutput; MemoryContext oldcontext; List *parsetree_list, *parsetree_item; @@ -689,10 +691,10 @@ exec_simple_query(const char *query_string) pgstat_report_activity(query_string); /* - * We use save_log_* so "SET log_duration = true" and - * "SET log_min_duration_statement = true" don't report incorrect - * time because gettimeofday() wasn't called. - * Similarly, log_statement_stats has to be captured once. + * We use save_log_* so "SET log_duration = true" and "SET + * log_min_duration_statement = true" don't report incorrect time + * because gettimeofday() wasn't called. Similarly, + * log_statement_stats has to be captured once. */ if (save_log_duration || save_log_min_duration_statement > 0) gettimeofday(&start_t, NULL); @@ -710,10 +712,10 @@ exec_simple_query(const char *query_string) start_xact_command(); /* - * Zap any pre-existing unnamed statement. (While not strictly - * necessary, it seems best to define simple-Query mode as if it - * used the unnamed statement and portal; this ensures we recover - * any storage used by prior unnamed operations.) + * Zap any pre-existing unnamed statement. (While not strictly + * necessary, it seems best to define simple-Query mode as if it used + * the unnamed statement and portal; this ensures we recover any + * storage used by prior unnamed operations.) */ unnamed_stmt_pstmt = NULL; if (unnamed_stmt_context) @@ -756,10 +758,10 @@ exec_simple_query(const char *query_string) int16 format; /* - * Get the command name for use in status display (it also becomes the - * default completion tag, down inside PortalRun). Set ps_status and - * do any special start-of-SQL-command processing needed by the - * destination. + * Get the command name for use in status display (it also becomes + * the default completion tag, down inside PortalRun). Set + * ps_status and do any special start-of-SQL-command processing + * needed by the destination. */ commandTag = CreateCommandTag(parsetree); @@ -817,8 +819,8 @@ exec_simple_query(const char *query_string) CHECK_FOR_INTERRUPTS(); /* - * Create unnamed portal to run the query or queries in. - * If there already is one, silently drop it. + * Create unnamed portal to run the query or queries in. If there + * already is one, silently drop it. */ portal = CreatePortal("", true, true); @@ -836,9 +838,9 @@ exec_simple_query(const char *query_string) /* * Select the appropriate output format: text unless we are doing - * a FETCH from a binary cursor. (Pretty grotty to have to do this - * here --- but it avoids grottiness in other places. Ah, the joys - * of backward compatibility...) + * a FETCH from a binary cursor. (Pretty grotty to have to do + * this here --- but it avoids grottiness in other places. Ah, + * the joys of backward compatibility...) */ format = 0; /* TEXT is default */ if (IsA(parsetree, FetchStmt)) @@ -851,7 +853,7 @@ exec_simple_query(const char *query_string) if (PortalIsValid(fportal) && (fportal->cursorOptions & CURSOR_OPT_BINARY)) - format = 1; /* BINARY */ + format = 1; /* BINARY */ } } PortalSetResultFormat(portal, 1, &format); @@ -867,7 +869,8 @@ exec_simple_query(const char *query_string) MemoryContextSwitchTo(oldcontext); /* - * Run the portal to completion, and then drop it (and the receiver). + * Run the portal to completion, and then drop it (and the + * receiver). */ (void) PortalRun(portal, FETCH_ALL, @@ -882,30 +885,32 @@ exec_simple_query(const char *query_string) if (IsA(parsetree, TransactionStmt)) { /* - * If this was a transaction control statement, commit it. - * We will start a new xact command for the next command (if any). + * If this was a transaction control statement, commit it. We + * will start a new xact command for the next command (if + * any). */ finish_xact_command(); } else if (lnext(parsetree_item) == NIL) { /* - * If this is the last parsetree of the query string, close down - * transaction statement before reporting command-complete. This - * is so that any end-of-transaction errors are reported before - * the command-complete message is issued, to avoid confusing - * clients who will expect either a command-complete message or an - * error, not one and then the other. But for compatibility with - * historical Postgres behavior, we do not force a transaction - * boundary between queries appearing in a single query string. + * If this is the last parsetree of the query string, close + * down transaction statement before reporting + * command-complete. This is so that any end-of-transaction + * errors are reported before the command-complete message is + * issued, to avoid confusing clients who will expect either a + * command-complete message or an error, not one and then the + * other. But for compatibility with historical Postgres + * behavior, we do not force a transaction boundary between + * queries appearing in a single query string. */ finish_xact_command(); } else { /* - * We need a CommandCounterIncrement after every query, - * except those that start or end a transaction block. + * We need a CommandCounterIncrement after every query, except + * those that start or end a transaction block. */ CommandCounterIncrement(); } @@ -934,12 +939,13 @@ exec_simple_query(const char *query_string) QueryContext = NULL; /* - * Combine processing here as we need to calculate the query - * duration in both instances. + * Combine processing here as we need to calculate the query duration + * in both instances. */ if (save_log_duration || save_log_min_duration_statement > 0) { - long usecs; + long usecs; + gettimeofday(&stop_t, NULL); if (stop_t.tv_usec < start_t.tv_usec) { @@ -948,9 +954,9 @@ exec_simple_query(const char *query_string) } usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 + (long) (stop_t.tv_usec - start_t.tv_usec); - /* - * Output a duration_query to the log if the query has exceeded the - * min duration. + /* + * Output a duration_query to the log if the query has exceeded + * the min duration. */ if (usecs >= save_log_min_duration_statement * 1000) ereport(LOG, @@ -959,7 +965,7 @@ exec_simple_query(const char *query_string) (long) (stop_t.tv_usec - start_t.tv_usec), query_string))); - /* + /* * If the user is requesting logging of all durations, then log * that as well. */ @@ -984,8 +990,8 @@ exec_simple_query(const char *query_string) static void exec_parse_message(const char *query_string, /* string to execute */ const char *stmt_name, /* name for prepared stmt */ - Oid *paramTypes, /* parameter types */ - int numParams) /* number of parameters */ + Oid *paramTypes, /* parameter types */ + int numParams) /* number of parameters */ { MemoryContext oldcontext; List *parsetree_list; @@ -1018,16 +1024,16 @@ exec_parse_message(const char *query_string, /* string to execute */ /* * Switch to appropriate context for constructing parsetrees. * - * We have two strategies depending on whether the prepared statement - * is named or not. For a named prepared statement, we do parsing - * in MessageContext and copy the finished trees into the prepared - * statement's private context; then the reset of MessageContext releases - * temporary space used by parsing and planning. For an unnamed prepared - * statement, we assume the statement isn't going to hang around long, - * so getting rid of temp space quickly is probably not worth the costs - * of copying parse/plan trees. So in this case, we set up a special - * context for the unnamed statement, and do all the parsing/planning - * therein. + * We have two strategies depending on whether the prepared statement is + * named or not. For a named prepared statement, we do parsing in + * MessageContext and copy the finished trees into the prepared + * statement's private context; then the reset of MessageContext + * releases temporary space used by parsing and planning. For an + * unnamed prepared statement, we assume the statement isn't going to + * hang around long, so getting rid of temp space quickly is probably + * not worth the costs of copying parse/plan trees. So in this case, + * we set up a special context for the unnamed statement, and do all + * the parsing/planning therein. */ is_named = (stmt_name[0] != '\0'); if (is_named) @@ -1064,9 +1070,9 @@ exec_parse_message(const char *query_string, /* string to execute */ parsetree_list = pg_parse_query(query_string); /* - * We only allow a single user statement in a prepared statement. - * This is mainly to keep the protocol simple --- otherwise we'd need - * to worry about multiple result tupdescs and things like that. + * We only allow a single user statement in a prepared statement. This + * is mainly to keep the protocol simple --- otherwise we'd need to + * worry about multiple result tupdescs and things like that. */ if (length(parsetree_list) > 1) ereport(ERROR, @@ -1075,8 +1081,8 @@ exec_parse_message(const char *query_string, /* string to execute */ if (parsetree_list != NIL) { - Node *parsetree = (Node *) lfirst(parsetree_list); - int i; + Node *parsetree = (Node *) lfirst(parsetree_list); + int i; /* * Get the command name for possible use in status display. @@ -1085,10 +1091,10 @@ exec_parse_message(const char *query_string, /* string to execute */ /* * If we are in an aborted transaction, reject all commands except - * COMMIT/ROLLBACK. It is important that this test occur before we - * try to do parse analysis, rewrite, or planning, since all those - * phases try to do database accesses, which may fail in abort - * state. (It might be safe to allow some additional utility + * COMMIT/ROLLBACK. It is important that this test occur before + * we try to do parse analysis, rewrite, or planning, since all + * those phases try to do database accesses, which may fail in + * abort state. (It might be safe to allow some additional utility * commands in this state, but not many...) */ if (IsAbortedTransactionBlockState()) @@ -1130,13 +1136,13 @@ exec_parse_message(const char *query_string, /* string to execute */ param_list = NIL; for (i = 0; i < numParams; i++) { - Oid ptype = paramTypes[i]; + Oid ptype = paramTypes[i]; if (ptype == InvalidOid || ptype == UNKNOWNOID) ereport(ERROR, (errcode(ERRCODE_INDETERMINATE_DATATYPE), - errmsg("could not determine datatype of parameter $%d", - i + 1))); + errmsg("could not determine datatype of parameter $%d", + i + 1))); param_list = lappendo(param_list, ptype); } @@ -1149,7 +1155,7 @@ exec_parse_message(const char *query_string, /* string to execute */ } else { - /* Empty input string. This is legal. */ + /* Empty input string. This is legal. */ commandTag = NULL; querytree_list = NIL; plantree_list = NIL; @@ -1193,9 +1199,10 @@ exec_parse_message(const char *query_string, /* string to execute */ QueryContext = NULL; /* - * We do NOT close the open transaction command here; that only happens - * when the client sends Sync. Instead, do CommandCounterIncrement just - * in case something happened during parse/plan. + * We do NOT close the open transaction command here; that only + * happens when the client sends Sync. Instead, do + * CommandCounterIncrement just in case something happened during + * parse/plan. */ CommandCounterIncrement(); @@ -1236,9 +1243,9 @@ exec_bind_message(StringInfo input_message) set_ps_display("BIND"); /* - * Start up a transaction command so we can call functions etc. - * (Note that this will normally change current memory context.) - * Nothing happens if we are already in one. + * Start up a transaction command so we can call functions etc. (Note + * that this will normally change current memory context.) Nothing + * happens if we are already in one. */ start_xact_command(); @@ -1264,8 +1271,8 @@ exec_bind_message(StringInfo input_message) if (numPFormats > 1 && numPFormats != numParams) ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("bind message has %d parameter formats but %d parameters", - numPFormats, numParams))); + errmsg("bind message has %d parameter formats but %d parameters", + numPFormats, numParams))); /* Find prepared statement */ if (stmt_name[0] != '\0') @@ -1277,14 +1284,14 @@ exec_bind_message(StringInfo input_message) if (!pstmt) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_PSTATEMENT), - errmsg("unnamed prepared statement does not exist"))); + errmsg("unnamed prepared statement does not exist"))); } if (numParams != length(pstmt->argtype_list)) ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d", - numParams, stmt_name, length(pstmt->argtype_list)))); + numParams, stmt_name, length(pstmt->argtype_list)))); /* * Create the portal. Allow silent replacement of an existing portal @@ -1305,13 +1312,14 @@ exec_bind_message(StringInfo input_message) /* * Fetch parameters, if any, and store in the portal's memory context. * - * In an aborted transaction, we can't risk calling user-defined functions, - * but we can't fail to Bind either, so bind all parameters to null values. + * In an aborted transaction, we can't risk calling user-defined + * functions, but we can't fail to Bind either, so bind all parameters + * to null values. */ if (numParams > 0) { - bool isaborted = IsAbortedTransactionBlockState(); - List *l; + bool isaborted = IsAbortedTransactionBlockState(); + List *l; MemoryContext oldContext; oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal)); @@ -1340,25 +1348,25 @@ exec_bind_message(StringInfo input_message) } else { - int16 pformat; + int16 pformat; StringInfoData pbuf; - char csave; + char csave; if (numPFormats > 1) pformat = pformats[i]; else if (numPFormats > 0) pformat = pformats[0]; else - pformat = 0; /* default = text */ + pformat = 0; /* default = text */ /* - * Rather than copying data around, we just set up a phony - * StringInfo pointing to the correct portion of the - * message buffer. We assume we can scribble on the - * message buffer so as to maintain the convention that - * StringInfos have a trailing null. This is grotty but - * is a big win when dealing with very large parameter - * strings. + * Rather than copying data around, we just set up a + * phony StringInfo pointing to the correct portion of + * the message buffer. We assume we can scribble on + * the message buffer so as to maintain the convention + * that StringInfos have a trailing null. This is + * grotty but is a big win when dealing with very + * large parameter strings. */ pbuf.data = (char *) pvalue; pbuf.maxlen = plength + 1; @@ -1375,9 +1383,10 @@ exec_bind_message(StringInfo input_message) char *pstring; getTypeInputInfo(ptype, &typInput, &typElem); + /* - * We have to do encoding conversion before calling - * the typinput routine. + * We have to do encoding conversion before + * calling the typinput routine. */ pstring = (char *) pg_client_to_server((unsigned char *) pbuf.data, @@ -1396,7 +1405,10 @@ exec_bind_message(StringInfo input_message) Oid typReceive; Oid typElem; - /* Call the parameter type's binary input converter */ + /* + * Call the parameter type's binary input + * converter + */ getTypeBinaryInputInfo(ptype, &typReceive, &typElem); params[i].value = @@ -1409,7 +1421,7 @@ exec_bind_message(StringInfo input_message) ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), errmsg("incorrect binary data format in bind parameter %d", - i + 1))); + i + 1))); } else { @@ -1474,7 +1486,7 @@ exec_bind_message(StringInfo input_message) static void exec_execute_message(const char *portal_name, long max_rows) { - CommandDest dest; + CommandDest dest; DestReceiver *receiver; Portal portal; bool is_trans_stmt = false; @@ -1494,7 +1506,8 @@ exec_execute_message(const char *portal_name, long max_rows) errmsg("portal \"%s\" does not exist", portal_name))); /* - * If the original query was a null string, just return EmptyQueryResponse. + * If the original query was a null string, just return + * EmptyQueryResponse. */ if (portal->commandTag == NULL) { @@ -1521,7 +1534,7 @@ exec_execute_message(const char *portal_name, long max_rows) /* Check for transaction-control commands */ if (length(portal->parseTrees) == 1) { - Query *query = (Query *) lfirst(portal->parseTrees); + Query *query = (Query *) lfirst(portal->parseTrees); if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL && @@ -1537,14 +1550,15 @@ exec_execute_message(const char *portal_name, long max_rows) } /* - * Create dest receiver in MessageContext (we don't want it in transaction - * context, because that may get deleted if portal contains VACUUM). + * Create dest receiver in MessageContext (we don't want it in + * transaction context, because that may get deleted if portal + * contains VACUUM). */ receiver = CreateDestReceiver(dest, portal); /* - * Ensure we are in a transaction command (this should normally be - * the case already due to prior BIND). + * Ensure we are in a transaction command (this should normally be the + * case already due to prior BIND). */ start_xact_command(); @@ -1558,7 +1572,7 @@ exec_execute_message(const char *portal_name, long max_rows) ereport(ERROR, (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION), errmsg("current transaction is aborted, " - "queries ignored until end of transaction block"))); + "queries ignored until end of transaction block"))); } /* Check for cancel signal before we start execution */ @@ -1583,16 +1597,17 @@ exec_execute_message(const char *portal_name, long max_rows) if (is_trans_stmt) { /* - * If this was a transaction control statement, commit it. We will - * start a new xact command for the next command (if any). + * If this was a transaction control statement, commit it. We + * will start a new xact command for the next command (if + * any). */ finish_xact_command(); } else { /* - * We need a CommandCounterIncrement after every query, - * except those that start or end a transaction block. + * We need a CommandCounterIncrement after every query, except + * those that start or end a transaction block. */ CommandCounterIncrement(); } @@ -1633,7 +1648,7 @@ exec_describe_statement_message(const char *stmt_name) if (!pstmt) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_PSTATEMENT), - errmsg("unnamed prepared statement does not exist"))); + errmsg("unnamed prepared statement does not exist"))); } if (whereToSendOutput != Remote) @@ -1642,7 +1657,7 @@ exec_describe_statement_message(const char *stmt_name) /* * First describe the parameters... */ - pq_beginmessage(&buf, 't'); /* parameter description message type */ + pq_beginmessage(&buf, 't'); /* parameter description message type */ pq_sendint(&buf, length(pstmt->argtype_list), 2); foreach(l, pstmt->argtype_list) @@ -1659,7 +1674,7 @@ exec_describe_statement_message(const char *stmt_name) tupdesc = FetchPreparedStatementResultDesc(pstmt); if (tupdesc) { - List *targetlist; + List *targetlist; if (ChoosePortalStrategy(pstmt->query_list) == PORTAL_ONE_SELECT) targetlist = ((Query *) lfirst(pstmt->query_list))->targetList; @@ -1693,7 +1708,7 @@ exec_describe_portal_message(const char *portal_name) if (portal->tupDesc) { - List *targetlist; + List *targetlist; if (portal->strategy == PORTAL_ONE_SELECT) targetlist = ((Query *) lfirst(portal->parseTrees))->targetList; @@ -1768,19 +1783,21 @@ void quickdie(SIGNAL_ARGS) { PG_SETMASK(&BlockSig); + /* - * Ideally this should be ereport(FATAL), but then we'd not get control - * back (perhaps could fix by doing local sigsetjmp?) + * Ideally this should be ereport(FATAL), but then we'd not get + * control back (perhaps could fix by doing local sigsetjmp?) */ ereport(WARNING, (errcode(ERRCODE_CRASH_SHUTDOWN), - errmsg("terminating connection due to crash of another backend"), - errdetail("The postmaster has commanded this backend to roll back" - " the current transaction and exit, because another" - " backend exited abnormally and possibly corrupted" - " shared memory."), + errmsg("terminating connection due to crash of another backend"), + errdetail("The postmaster has commanded this backend to roll back" + " the current transaction and exit, because another" + " backend exited abnormally and possibly corrupted" + " shared memory."), errhint("In a moment you should be able to reconnect to the" " database and repeat your query."))); + /* * DO NOT proc_exit() -- we're here because shared memory may be * corrupted, so we don't want to try to clean up our transaction. @@ -1894,9 +1911,9 @@ FloatExceptionHandler(SIGNAL_ARGS) ereport(ERROR, (errcode(ERRCODE_FLOATING_POINT_EXCEPTION), errmsg("floating-point exception"), - errdetail("An invalid floating-point operation was signaled. " - "This probably means an out-of-range result or an " - "invalid operation, such as division by zero."))); + errdetail("An invalid floating-point operation was signaled. " + "This probably means an out-of-range result or an " + "invalid operation, such as division by zero."))); } /* SIGHUP: set flag to re-read config file at next convenient time */ @@ -1929,7 +1946,7 @@ ProcessInterrupts(void) DisableNotifyInterrupt(); ereport(FATAL, (errcode(ERRCODE_ADMIN_SHUTDOWN), - errmsg("terminating connection due to administrator command"))); + errmsg("terminating connection due to administrator command"))); } if (QueryCancelPending) { @@ -1999,7 +2016,8 @@ PostgresMain(int argc, char *argv[], const char *username) bool secure; int errs = 0; int debug_flag = 0; - GucContext ctx, debug_context; + GucContext ctx, + debug_context; GucSource gucsource; char *tmp; int firstchar; @@ -2049,7 +2067,7 @@ PostgresMain(int argc, char *argv[], const char *username) Noversion = false; EchoQuery = false; - if (!IsUnderPostmaster /* when exec || ExecBackend*/) + if (!IsUnderPostmaster /* when exec || ExecBackend */ ) { InitializeGUCOptions(); potential_DataDir = getenv("PGDATA"); @@ -2114,29 +2132,33 @@ PostgresMain(int argc, char *argv[], const char *username) case 'd': /* debug level */ { /* - * Client option can't decrease debug level. - * We have to do the test here because we group priv and client - * set GUC calls below, after we know the final debug value. - */ + * Client option can't decrease debug level. We have + * to do the test here because we group priv and + * client set GUC calls below, after we know the final + * debug value. + */ if (ctx != PGC_BACKEND || atoi(optarg) > debug_flag) { debug_flag = atoi(optarg); - debug_context = ctx; /* save context for use below */ + debug_context = ctx; /* save context for use + * below */ /* Set server debugging level. */ if (debug_flag != 0) { char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1); - + sprintf(debugstr, "debug%s", optarg); SetConfigOption("log_min_messages", debugstr, ctx, gucsource); pfree(debugstr); - + } else + /* * -d0 allows user to prevent postmaster debug - * from propagating to backend. It would be nice - * to set it to the postgresql.conf value here. + * from propagating to backend. It would be + * nice to set it to the postgresql.conf value + * here. */ SetConfigOption("log_min_messages", "notice", ctx, gucsource); @@ -2245,17 +2267,19 @@ PostgresMain(int argc, char *argv[], const char *username) if (secure) { #ifdef EXEC_BACKEND - char *p; - int i; - int PMcanAcceptConnections; /* will eventually be global or static, when fork */ - + char *p; + int i; + int PMcanAcceptConnections; /* will eventually be + * global or static, + * when fork */ + sscanf(optarg, "%d,%d,%d,%p,", &MyProcPort->sock, &PMcanAcceptConnections, - &UsedShmemSegID, &UsedShmemSegAddr); + &UsedShmemSegID, &UsedShmemSegAddr); /* Grab dbname as last param */ - for (i = 0, p = optarg-1; i < 4 && p; i++) - p = strchr(p+1, ','); + for (i = 0, p = optarg - 1; i < 4 && p; i++) + p = strchr(p + 1, ','); if (i == 4 && p) - dbname = strdup(p+1); + dbname = strdup(p + 1); #else dbname = strdup(optarg); #endif @@ -2411,11 +2435,12 @@ PostgresMain(int argc, char *argv[], const char *username) SetConfigOption("debug_print_rewritten", "true", debug_context, gucsource); /* - * Process any additional GUC variable settings passed in startup packet. + * Process any additional GUC variable settings passed in startup + * packet. */ if (MyProcPort != NULL) { - List *gucopts = MyProcPort->guc_options; + List *gucopts = MyProcPort->guc_options; while (gucopts) { @@ -2481,7 +2506,7 @@ PostgresMain(int argc, char *argv[], const char *username) pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */ pqsignal(SIGTERM, die); /* cancel current query and exit */ pqsignal(SIGQUIT, quickdie); /* hard crash time */ - pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */ + pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */ /* * Ignore failure to write to frontend. Note: if frontend closes @@ -2626,7 +2651,7 @@ PostgresMain(int argc, char *argv[], const char *username) if (!IsUnderPostmaster) { puts("\nPOSTGRES backend interactive interface "); - puts("$Revision: 1.353 $ $Date: 2003/07/29 00:03:18 $\n"); + puts("$Revision: 1.354 $ $Date: 2003/08/04 00:43:25 $\n"); } /* @@ -2664,15 +2689,15 @@ PostgresMain(int argc, char *argv[], const char *username) * * Make sure we're not interrupted while cleaning up. Also forget * any pending QueryCancel request, since we're aborting anyway. - * Force InterruptHoldoffCount to a known state in case we ereport'd - * from inside a holdoff section. + * Force InterruptHoldoffCount to a known state in case we + * ereport'd from inside a holdoff section. */ ImmediateInterruptOK = false; QueryCancelPending = false; InterruptHoldoffCount = 1; CritSectionCount = 0; /* should be unnecessary, but... */ disable_sig_alarm(true); - QueryCancelPending = false; /* again in case timeout occurred */ + QueryCancelPending = false; /* again in case timeout occurred */ DisableNotifyInterrupt(); debug_query_string = NULL; @@ -2706,8 +2731,8 @@ PostgresMain(int argc, char *argv[], const char *username) /* * If we were handling an extended-query-protocol message, - * initiate skip till next Sync. This also causes us not - * to issue ReadyForQuery (until we get Sync). + * initiate skip till next Sync. This also causes us not to issue + * ReadyForQuery (until we get Sync). */ if (doing_extended_query_message) ignore_till_sync = true; @@ -2732,8 +2757,8 @@ PostgresMain(int argc, char *argv[], const char *username) for (;;) { /* - * At top of loop, reset extended-query-message flag, so that - * any errors encountered in "idle" state don't provoke skip. + * At top of loop, reset extended-query-message flag, so that any + * errors encountered in "idle" state don't provoke skip. */ doing_extended_query_message = false; @@ -2815,7 +2840,8 @@ PostgresMain(int argc, char *argv[], const char *username) } /* - * (6) process the command. But ignore it if we're skipping till Sync. + * (6) process the command. But ignore it if we're skipping till + * Sync. */ if (ignore_till_sync && firstchar != EOF) continue; @@ -2847,7 +2873,7 @@ PostgresMain(int argc, char *argv[], const char *username) numParams = pq_getmsgint(input_message, 2); if (numParams > 0) { - int i; + int i; paramTypes = (Oid *) palloc(numParams * sizeof(Oid)); for (i = 0; i < numParams; i++) @@ -2861,9 +2887,10 @@ PostgresMain(int argc, char *argv[], const char *username) break; case 'B': /* bind */ + /* - * this message is complex enough that it seems best to put - * the field extraction out-of-line + * this message is complex enough that it seems best to + * put the field extraction out-of-line */ exec_bind_message(input_message); break; @@ -2871,7 +2898,7 @@ PostgresMain(int argc, char *argv[], const char *username) case 'E': /* execute */ { const char *portal_name; - int max_rows; + int max_rows; portal_name = pq_getmsgstring(input_message); max_rows = pq_getmsgint(input_message, 4); @@ -2911,9 +2938,9 @@ PostgresMain(int argc, char *argv[], const char *username) send_rfq = true; break; - case 'C': /* close */ + case 'C': /* close */ { - int close_type; + int close_type; const char *close_target; close_type = pq_getmsgbyte(input_message); @@ -2949,19 +2976,19 @@ PostgresMain(int argc, char *argv[], const char *username) default: ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid CLOSE message subtype %d", - close_type))); + errmsg("invalid CLOSE message subtype %d", + close_type))); break; } if (whereToSendOutput == Remote) - pq_putemptymessage('3'); /* CloseComplete */ + pq_putemptymessage('3'); /* CloseComplete */ } break; case 'D': /* describe */ { - int describe_type; + int describe_type; const char *describe_target; describe_type = pq_getmsgbyte(input_message); @@ -2979,20 +3006,20 @@ PostgresMain(int argc, char *argv[], const char *username) default: ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid DESCRIBE message subtype %d", - describe_type))); + errmsg("invalid DESCRIBE message subtype %d", + describe_type))); break; } } break; - case 'H': /* flush */ + case 'H': /* flush */ pq_getmsgend(input_message); if (whereToSendOutput == Remote) pq_flush(); break; - case 'S': /* sync */ + case 'S': /* sync */ pq_getmsgend(input_message); finish_xact_command(); send_rfq = true; @@ -3007,8 +3034,8 @@ PostgresMain(int argc, char *argv[], const char *username) case EOF: /* - * Reset whereToSendOutput to prevent ereport from attempting - * to send any more messages to client. + * Reset whereToSendOutput to prevent ereport from + * attempting to send any more messages to client. */ if (whereToSendOutput == Remote) whereToSendOutput = None; @@ -3022,12 +3049,13 @@ PostgresMain(int argc, char *argv[], const char *username) */ proc_exit(0); - case 'd': /* copy data */ - case 'c': /* copy done */ - case 'f': /* copy fail */ + case 'd': /* copy data */ + case 'c': /* copy done */ + case 'f': /* copy fail */ + /* - * Accept but ignore these messages, per protocol spec; - * we probably got here because a COPY failed, and the + * Accept but ignore these messages, per protocol spec; we + * probably got here because a COPY failed, and the * frontend is still sending data. */ break; @@ -3119,9 +3147,9 @@ ShowUsage(const char *title) (long) (elapse_t.tv_sec - Save_t.tv_sec), (long) (elapse_t.tv_usec - Save_t.tv_usec), (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec), - (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec), + (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec), (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec), - (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec)); + (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec)); appendStringInfo(&str, "!\t[%ld.%06ld user %ld.%06ld sys total]\n", (long) user.tv_sec, diff --git a/src/backend/tcop/pquery.c b/src/backend/tcop/pquery.c index 2f6ed0eda1..0626ac5e8f 100644 --- a/src/backend/tcop/pquery.c +++ b/src/backend/tcop/pquery.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/tcop/pquery.c,v 1.68 2003/08/01 17:57:42 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/pquery.c,v 1.69 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -24,18 +24,18 @@ static uint32 RunFromStore(Portal portal, ScanDirection direction, long count, - DestReceiver *dest); + DestReceiver *dest); static long PortalRunSelect(Portal portal, bool forward, long count, - DestReceiver *dest); + DestReceiver *dest); static void PortalRunUtility(Portal portal, Query *query, - DestReceiver *dest, char *completionTag); + DestReceiver *dest, char *completionTag); static void PortalRunMulti(Portal portal, - DestReceiver *dest, DestReceiver *altdest, - char *completionTag); + DestReceiver *dest, DestReceiver *altdest, + char *completionTag); static long DoPortalRunFetch(Portal portal, - FetchDirection fdirection, - long count, - DestReceiver *dest); + FetchDirection fdirection, + long count, + DestReceiver *dest); static void DoPortalRewind(Portal portal); @@ -56,7 +56,7 @@ CreateQueryDesc(Query *parsetree, qd->plantree = plantree; /* plan */ qd->dest = dest; /* output dest */ qd->params = params; /* parameter values passed into query */ - qd->doInstrument = doInstrument; /* instrumentation wanted? */ + qd->doInstrument = doInstrument; /* instrumentation wanted? */ /* null these fields until set by ExecutorStart */ qd->tupDesc = NULL; @@ -156,7 +156,7 @@ ProcessQuery(Query *parsetree, else lastOid = InvalidOid; snprintf(completionTag, COMPLETION_TAG_BUFSIZE, - "INSERT %u %u", lastOid, queryDesc->estate->es_processed); + "INSERT %u %u", lastOid, queryDesc->estate->es_processed); break; case CMD_UPDATE: snprintf(completionTag, COMPLETION_TAG_BUFSIZE, @@ -195,14 +195,12 @@ ChoosePortalStrategy(List *parseTrees) if (length(parseTrees) == 1) { - Query *query = (Query *) lfirst(parseTrees); + Query *query = (Query *) lfirst(parseTrees); if (query->commandType == CMD_SELECT && query->canSetTag && query->into == NULL) - { strategy = PORTAL_ONE_SELECT; - } else if (query->commandType == CMD_UTILITY && query->canSetTag && query->utilityStmt != NULL) @@ -233,8 +231,8 @@ PortalStart(Portal portal, ParamListInfo params) QueryDesc *queryDesc; AssertArg(PortalIsValid(portal)); - AssertState(portal->queryContext != NULL); /* query defined? */ - AssertState(!portal->portalReady); /* else extra PortalStart */ + AssertState(portal->queryContext != NULL); /* query defined? */ + AssertState(!portal->portalReady); /* else extra PortalStart */ oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal)); @@ -252,31 +250,37 @@ PortalStart(Portal portal, ParamListInfo params) switch (portal->strategy) { case PORTAL_ONE_SELECT: + /* * Must set query snapshot before starting executor. */ SetQuerySnapshot(); + /* * Create QueryDesc in portal's context; for the moment, set * the destination to None. */ queryDesc = CreateQueryDesc((Query *) lfirst(portal->parseTrees), - (Plan *) lfirst(portal->planTrees), + (Plan *) lfirst(portal->planTrees), None_Receiver, params, false); + /* * Call ExecStart to prepare the plan for execution */ ExecutorStart(queryDesc, false); + /* * This tells PortalCleanup to shut down the executor */ portal->queryDesc = queryDesc; + /* * Remember tuple descriptor (computed by ExecutorStart) */ portal->tupDesc = queryDesc->tupDesc; + /* * Reset cursor position data to "start of query" */ @@ -287,12 +291,14 @@ PortalStart(Portal portal, ParamListInfo params) break; case PORTAL_UTIL_SELECT: + /* * We don't set query snapshot here, because PortalRunUtility * will take care of it. */ portal->tupDesc = UtilityTupleDescriptor(((Query *) lfirst(portal->parseTrees))->utilityStmt); + /* * Reset cursor position data to "start of query" */ @@ -346,7 +352,8 @@ PortalSetResultFormat(Portal portal, int nFormats, int16 *formats) errmsg("bind message has %d result formats but query has %d columns", nFormats, natts))); memcpy(portal->formats, formats, natts * sizeof(int16)); - } else if (nFormats > 0) + } + else if (nFormats > 0) { /* single format specified, use for all columns */ int16 format1 = formats[0]; @@ -393,7 +400,7 @@ PortalRun(Portal portal, long count, MemoryContext oldContext; AssertArg(PortalIsValid(portal)); - AssertState(portal->portalReady); /* else no PortalStart */ + AssertState(portal->portalReady); /* else no PortalStart */ /* Initialize completion tag to empty string */ if (completionTag) @@ -405,7 +412,7 @@ PortalRun(Portal portal, long count, if (portal->portalDone) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("portal \"%s\" cannot be run anymore", portal->name))); + errmsg("portal \"%s\" cannot be run anymore", portal->name))); if (portal->portalActive) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), @@ -429,6 +436,7 @@ PortalRun(Portal portal, long count, /* we know the query is supposed to set the tag */ if (completionTag && portal->commandTag) strcpy(completionTag, portal->commandTag); + /* * Since it's a forward fetch, say DONE iff atEnd is now true. */ @@ -436,6 +444,7 @@ PortalRun(Portal portal, long count, break; case PORTAL_UTIL_SELECT: + /* * If we have not yet run the utility statement, do so, * storing its results in the portal's tuplestore. @@ -451,16 +460,19 @@ PortalRun(Portal portal, long count, (*treceiver->destroy) (treceiver); portal->portalUtilReady = true; } + /* * Now fetch desired portion of results. */ (void) PortalRunSelect(portal, true, count, dest); + /* * We know the query is supposed to set the tag; we assume * only the default tag is needed. */ if (completionTag && portal->commandTag) strcpy(completionTag, portal->commandTag); + /* * Since it's a forward fetch, say DONE iff atEnd is now true. */ @@ -518,8 +530,8 @@ PortalRunSelect(Portal portal, uint32 nprocessed; /* - * NB: queryDesc will be NULL if we are fetching from a held cursor - * or a completed utility query; can't use it in that path. + * NB: queryDesc will be NULL if we are fetching from a held cursor or + * a completed utility query; can't use it in that path. */ queryDesc = PortalGetQueryDesc(portal); @@ -527,7 +539,7 @@ PortalRunSelect(Portal portal, Assert(queryDesc || portal->holdStore); /* - * Force the queryDesc destination to the right thing. This supports + * Force the queryDesc destination to the right thing. This supports * MOVE, for example, which will pass in dest = None. This is okay to * change as long as we do it on every fetch. (The Executor must not * assume that dest never changes.) @@ -567,13 +579,13 @@ PortalRunSelect(Portal portal, if (direction != NoMovementScanDirection) { - long oldPos; + long oldPos; if (nprocessed > 0) - portal->atStart = false; /* OK to go backward now */ + portal->atStart = false; /* OK to go backward now */ if (count == 0 || (unsigned long) nprocessed < (unsigned long) count) - portal->atEnd = true; /* we retrieved 'em all */ + portal->atEnd = true; /* we retrieved 'em all */ oldPos = portal->portalPos; portal->portalPos += nprocessed; /* portalPos doesn't advance when we fall off the end */ @@ -610,19 +622,19 @@ PortalRunSelect(Portal portal, { if (nprocessed > 0 && portal->atEnd) { - portal->atEnd = false; /* OK to go forward now */ - portal->portalPos++; /* adjust for endpoint case */ + portal->atEnd = false; /* OK to go forward now */ + portal->portalPos++; /* adjust for endpoint case */ } if (count == 0 || (unsigned long) nprocessed < (unsigned long) count) { - portal->atStart = true; /* we retrieved 'em all */ + portal->atStart = true; /* we retrieved 'em all */ portal->portalPos = 0; portal->posOverflow = false; } else { - long oldPos; + long oldPos; oldPos = portal->portalPos; portal->portalPos -= nprocessed; @@ -662,13 +674,13 @@ RunFromStore(Portal portal, ScanDirection direction, long count, } else { - bool forward = (direction == ForwardScanDirection); + bool forward = (direction == ForwardScanDirection); for (;;) { MemoryContext oldcontext; - HeapTuple tup; - bool should_free; + HeapTuple tup; + bool should_free; oldcontext = MemoryContextSwitchTo(portal->holdContext); @@ -686,9 +698,9 @@ RunFromStore(Portal portal, ScanDirection direction, long count, pfree(tup); /* - * check our tuple count.. if we've processed the proper number - * then quit, else loop again and process more tuples. Zero - * count means no limit. + * check our tuple count.. if we've processed the proper + * number then quit, else loop again and process more tuples. + * Zero count means no limit. */ current_tuple_count++; if (count && count == current_tuple_count) @@ -709,35 +721,34 @@ static void PortalRunUtility(Portal portal, Query *query, DestReceiver *dest, char *completionTag) { - Node *utilityStmt = query->utilityStmt; + Node *utilityStmt = query->utilityStmt; elog(DEBUG3, "ProcessUtility"); /* - * Set snapshot if utility stmt needs one. Most reliable - * way to do this seems to be to enumerate those that do not - * need one; this is a short list. Transaction control, - * LOCK, and SET must *not* set a snapshot since they need - * to be executable at the start of a serializable transaction - * without freezing a snapshot. By extension we allow SHOW - * not to set a snapshot. The other stmts listed are just - * efficiency hacks. Beware of listing anything that can - * modify the database --- if, say, it has to update an - * index with expressions that invoke user-defined functions, - * then it had better have a snapshot. + * Set snapshot if utility stmt needs one. Most reliable way to do + * this seems to be to enumerate those that do not need one; this is a + * short list. Transaction control, LOCK, and SET must *not* set a + * snapshot since they need to be executable at the start of a + * serializable transaction without freezing a snapshot. By extension + * we allow SHOW not to set a snapshot. The other stmts listed are + * just efficiency hacks. Beware of listing anything that can modify + * the database --- if, say, it has to update an index with + * expressions that invoke user-defined functions, then it had better + * have a snapshot. */ - if (! (IsA(utilityStmt, TransactionStmt) || - IsA(utilityStmt, LockStmt) || - IsA(utilityStmt, VariableSetStmt) || - IsA(utilityStmt, VariableShowStmt) || - IsA(utilityStmt, VariableResetStmt) || - IsA(utilityStmt, ConstraintsSetStmt) || - /* efficiency hacks from here down */ - IsA(utilityStmt, FetchStmt) || - IsA(utilityStmt, ListenStmt) || - IsA(utilityStmt, NotifyStmt) || - IsA(utilityStmt, UnlistenStmt) || - IsA(utilityStmt, CheckPointStmt))) + if (!(IsA(utilityStmt, TransactionStmt) || + IsA(utilityStmt, LockStmt) || + IsA(utilityStmt, VariableSetStmt) || + IsA(utilityStmt, VariableShowStmt) || + IsA(utilityStmt, VariableResetStmt) || + IsA(utilityStmt, ConstraintsSetStmt) || + /* efficiency hacks from here down */ + IsA(utilityStmt, FetchStmt) || + IsA(utilityStmt, ListenStmt) || + IsA(utilityStmt, NotifyStmt) || + IsA(utilityStmt, UnlistenStmt) || + IsA(utilityStmt, CheckPointStmt))) SetQuerySnapshot(); if (query->canSetTag) @@ -745,7 +756,7 @@ PortalRunUtility(Portal portal, Query *query, /* utility statement can override default tag string */ ProcessUtility(utilityStmt, dest, completionTag); if (completionTag && completionTag[0] == '\0' && portal->commandTag) - strcpy(completionTag, portal->commandTag); /* use the default */ + strcpy(completionTag, portal->commandTag); /* use the default */ } else { @@ -770,14 +781,14 @@ PortalRunMulti(Portal portal, List *querylist_item; /* - * If the destination is RemoteExecute, change to None. The reason - * is that the client won't be expecting any tuples, and indeed has no + * If the destination is RemoteExecute, change to None. The reason is + * that the client won't be expecting any tuples, and indeed has no * way to know what they are, since there is no provision for Describe - * to send a RowDescription message when this portal execution strategy - * is in effect. This presently will only affect SELECT commands added - * to non-SELECT queries by rewrite rules: such commands will be executed, - * but the results will be discarded unless you use "simple Query" - * protocol. + * to send a RowDescription message when this portal execution + * strategy is in effect. This presently will only affect SELECT + * commands added to non-SELECT queries by rewrite rules: such + * commands will be executed, but the results will be discarded unless + * you use "simple Query" protocol. */ if (dest->mydest == RemoteExecute) dest = None_Receiver; @@ -785,8 +796,8 @@ PortalRunMulti(Portal portal, altdest = None_Receiver; /* - * Loop to handle the individual queries generated from a - * single parsetree by analysis and rewrite. + * Loop to handle the individual queries generated from a single + * parsetree by analysis and rewrite. */ foreach(querylist_item, portal->parseTrees) { @@ -862,12 +873,12 @@ PortalRunMulti(Portal portal, } /* - * If a command completion tag was supplied, use it. Otherwise - * use the portal's commandTag as the default completion tag. + * If a command completion tag was supplied, use it. Otherwise use + * the portal's commandTag as the default completion tag. * - * Exception: clients will expect INSERT/UPDATE/DELETE tags to - * have counts, so fake something up if necessary. (This could - * happen if the original query was replaced by a DO INSTEAD rule.) + * Exception: clients will expect INSERT/UPDATE/DELETE tags to have + * counts, so fake something up if necessary. (This could happen if + * the original query was replaced by a DO INSTEAD rule.) */ if (completionTag && completionTag[0] == '\0') { @@ -903,7 +914,7 @@ PortalRunFetch(Portal portal, MemoryContext oldContext; AssertArg(PortalIsValid(portal)); - AssertState(portal->portalReady); /* else no PortalStart */ + AssertState(portal->portalReady); /* else no PortalStart */ /* * Check for improper portal use, and mark portal active. @@ -911,7 +922,7 @@ PortalRunFetch(Portal portal, if (portal->portalDone) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("portal \"%s\" cannot be run anymore", portal->name))); + errmsg("portal \"%s\" cannot be run anymore", portal->name))); if (portal->portalActive) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), @@ -989,18 +1000,18 @@ DoPortalRunFetch(Portal portal, if (count > 0) { /* - * Definition: Rewind to start, advance count-1 rows, return - * next row (if any). In practice, if the goal is less than - * halfway back to the start, it's better to scan from where - * we are. In any case, we arrange to fetch the target row - * going forwards. + * Definition: Rewind to start, advance count-1 rows, + * return next row (if any). In practice, if the goal is + * less than halfway back to the start, it's better to + * scan from where we are. In any case, we arrange to + * fetch the target row going forwards. */ if (portal->posOverflow || portal->portalPos == LONG_MAX || - count-1 <= portal->portalPos / 2) + count - 1 <= portal->portalPos / 2) { DoPortalRewind(portal); if (count > 1) - PortalRunSelect(portal, true, count-1, + PortalRunSelect(portal, true, count - 1, None_Receiver); } else @@ -1010,10 +1021,10 @@ DoPortalRunFetch(Portal portal, if (portal->atEnd) pos++; /* need one extra fetch if off end */ if (count <= pos) - PortalRunSelect(portal, false, pos-count+1, + PortalRunSelect(portal, false, pos - count + 1, None_Receiver); - else if (count > pos+1) - PortalRunSelect(portal, true, count-pos-1, + else if (count > pos + 1) + PortalRunSelect(portal, true, count - pos - 1, None_Receiver); } return PortalRunSelect(portal, true, 1L, dest); @@ -1022,17 +1033,19 @@ DoPortalRunFetch(Portal portal, { /* * Definition: Advance to end, back up abs(count)-1 rows, - * return prior row (if any). We could optimize this if we - * knew in advance where the end was, but typically we won't. - * (Is it worth considering case where count > half of size - * of query? We could rewind once we know the size ...) + * return prior row (if any). We could optimize this if + * we knew in advance where the end was, but typically we + * won't. (Is it worth considering case where count > half + * of size of query? We could rewind once we know the + * size ...) */ PortalRunSelect(portal, true, FETCH_ALL, None_Receiver); if (count < -1) - PortalRunSelect(portal, false, -count-1, None_Receiver); + PortalRunSelect(portal, false, -count - 1, None_Receiver); return PortalRunSelect(portal, false, 1L, dest); } - else /* count == 0 */ + else +/* count == 0 */ { /* Rewind to start, return zero rows */ DoPortalRewind(portal); @@ -1043,10 +1056,11 @@ DoPortalRunFetch(Portal portal, if (count > 0) { /* - * Definition: advance count-1 rows, return next row (if any). + * Definition: advance count-1 rows, return next row (if + * any). */ if (count > 1) - PortalRunSelect(portal, true, count-1, None_Receiver); + PortalRunSelect(portal, true, count - 1, None_Receiver); return PortalRunSelect(portal, true, 1L, dest); } else if (count < 0) @@ -1056,10 +1070,11 @@ DoPortalRunFetch(Portal portal, * (if any). */ if (count < -1) - PortalRunSelect(portal, false, -count-1, None_Receiver); + PortalRunSelect(portal, false, -count - 1, None_Receiver); return PortalRunSelect(portal, false, 1L, dest); } - else /* count == 0 */ + else +/* count == 0 */ { /* Same as FETCH FORWARD 0, so fall out of switch */ fdirection = FETCH_FORWARD; @@ -1071,8 +1086,8 @@ DoPortalRunFetch(Portal portal, } /* - * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, - * and count >= 0. + * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and + * count >= 0. */ forward = (fdirection == FETCH_FORWARD); @@ -1081,7 +1096,7 @@ DoPortalRunFetch(Portal portal, */ if (count == 0) { - bool on_row; + bool on_row; /* Are we sitting on a row? */ on_row = (!portal->atStart && !portal->atEnd); @@ -1094,11 +1109,11 @@ DoPortalRunFetch(Portal portal, else { /* - * If we are sitting on a row, back up one so we can re-fetch it. - * If we are not sitting on a row, we still have to start up and - * shut down the executor so that the destination is initialized - * and shut down correctly; so keep going. To PortalRunSelect, - * count == 0 means we will retrieve no row. + * If we are sitting on a row, back up one so we can re-fetch + * it. If we are not sitting on a row, we still have to start + * up and shut down the executor so that the destination is + * initialized and shut down correctly; so keep going. To + * PortalRunSelect, count == 0 means we will retrieve no row. */ if (on_row) { @@ -1115,7 +1130,7 @@ DoPortalRunFetch(Portal portal, */ if (!forward && count == FETCH_ALL && dest->mydest == None) { - long result = portal->portalPos; + long result = portal->portalPos; if (result > 0 && !portal->atEnd) result--; @@ -1142,9 +1157,7 @@ DoPortalRewind(Portal portal) MemoryContextSwitchTo(oldcontext); } if (PortalGetQueryDesc(portal)) - { ExecutorRewind(PortalGetQueryDesc(portal)); - } portal->atStart = true; portal->atEnd = false; diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c index ec9e7a4cec..f0206bd14f 100644 --- a/src/backend/tcop/utility.c +++ b/src/backend/tcop/utility.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/tcop/utility.c,v 1.203 2003/08/01 00:15:23 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/utility.c,v 1.204 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -70,32 +70,32 @@ struct msgstrings }; static const struct msgstrings msgstringarray[] = { - { RELKIND_RELATION, - ERRCODE_UNDEFINED_TABLE, - gettext_noop("table \"%s\" does not exist"), - gettext_noop("\"%s\" is not a table"), - gettext_noop("Use DROP TABLE to remove a table.") }, - { RELKIND_SEQUENCE, - ERRCODE_UNDEFINED_TABLE, - gettext_noop("sequence \"%s\" does not exist"), - gettext_noop("\"%s\" is not a sequence"), - gettext_noop("Use DROP SEQUENCE to remove a sequence.") }, - { RELKIND_VIEW, - ERRCODE_UNDEFINED_TABLE, - gettext_noop("view \"%s\" does not exist"), - gettext_noop("\"%s\" is not a view"), - gettext_noop("Use DROP VIEW to remove a view.") }, - { RELKIND_INDEX, - ERRCODE_UNDEFINED_OBJECT, - gettext_noop("index \"%s\" does not exist"), - gettext_noop("\"%s\" is not an index"), - gettext_noop("Use DROP INDEX to remove an index.") }, - { RELKIND_COMPOSITE_TYPE, - ERRCODE_UNDEFINED_OBJECT, - gettext_noop("type \"%s\" does not exist"), - gettext_noop("\"%s\" is not a type"), - gettext_noop("Use DROP TYPE to remove a type.") }, - { '\0', 0, NULL, NULL, NULL } + {RELKIND_RELATION, + ERRCODE_UNDEFINED_TABLE, + gettext_noop("table \"%s\" does not exist"), + gettext_noop("\"%s\" is not a table"), + gettext_noop("Use DROP TABLE to remove a table.")}, + {RELKIND_SEQUENCE, + ERRCODE_UNDEFINED_TABLE, + gettext_noop("sequence \"%s\" does not exist"), + gettext_noop("\"%s\" is not a sequence"), + gettext_noop("Use DROP SEQUENCE to remove a sequence.")}, + {RELKIND_VIEW, + ERRCODE_UNDEFINED_TABLE, + gettext_noop("view \"%s\" does not exist"), + gettext_noop("\"%s\" is not a view"), + gettext_noop("Use DROP VIEW to remove a view.")}, + {RELKIND_INDEX, + ERRCODE_UNDEFINED_OBJECT, + gettext_noop("index \"%s\" does not exist"), + gettext_noop("\"%s\" is not an index"), + gettext_noop("Use DROP INDEX to remove an index.")}, + {RELKIND_COMPOSITE_TYPE, + ERRCODE_UNDEFINED_OBJECT, + gettext_noop("type \"%s\" does not exist"), + gettext_noop("\"%s\" is not a type"), + gettext_noop("Use DROP TYPE to remove a type.")}, + {'\0', 0, NULL, NULL, NULL} }; @@ -181,7 +181,7 @@ CheckRelationOwnership(RangeVar *rel, bool noCatalogs) tuple = SearchSysCache(RELOID, ObjectIdGetDatum(relOid), 0, 0, 0); - if (!HeapTupleIsValid(tuple)) /* should not happen */ + if (!HeapTupleIsValid(tuple)) /* should not happen */ elog(ERROR, "cache lookup failed for relation %u", relOid); if (!pg_class_ownercheck(relOid, GetUserId())) @@ -194,8 +194,8 @@ CheckRelationOwnership(RangeVar *rel, bool noCatalogs) IsSystemClass((Form_pg_class) GETSTRUCT(tuple))) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied: \"%s\" is a system catalog", - rel->relname))); + errmsg("permission denied: \"%s\" is a system catalog", + rel->relname))); } ReleaseSysCache(tuple); @@ -316,18 +316,18 @@ ProcessUtility(Node *parsetree, if (stmt->options) { - List *head; + List *head; foreach(head, stmt->options) { - DefElem *item = (DefElem *) lfirst(head); + DefElem *item = (DefElem *) lfirst(head); - if (strcmp(item->defname, "transaction_isolation")==0) + if (strcmp(item->defname, "transaction_isolation") == 0) SetPGVariable("transaction_isolation", - makeList1(item->arg), false); - else if (strcmp(item->defname, "transaction_read_only")==0) + makeList1(item->arg), false); + else if (strcmp(item->defname, "transaction_read_only") == 0) SetPGVariable("transaction_read_only", - makeList1(item->arg), false); + makeList1(item->arg), false); } } } @@ -429,7 +429,11 @@ ProcessUtility(Node *parsetree, break; case OBJECT_DOMAIN: - /* RemoveDomain does its own permissions checks */ + + /* + * RemoveDomain does its own permissions + * checks + */ RemoveDomain(names, stmt->behavior); break; @@ -438,7 +442,11 @@ ProcessUtility(Node *parsetree, break; case OBJECT_SCHEMA: - /* RemoveSchema does its own permissions checks */ + + /* + * RemoveSchema does its own permissions + * checks + */ RemoveSchema(names, stmt->behavior); break; @@ -590,8 +598,8 @@ ProcessUtility(Node *parsetree, /* check that we are the superuser */ if (!superuser()) ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to alter owner"))); + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("must be superuser to alter owner"))); /* get_usesysid raises an error if no such user */ AlterTableOwner(relid, get_usesysid(stmt->name)); @@ -599,9 +607,9 @@ ProcessUtility(Node *parsetree, case 'L': /* CLUSTER ON */ AlterTableClusterOn(relid, stmt->name); break; - case 'o': /* ADD OIDS */ + case 'o': /* ADD OIDS */ AlterTableAlterOids(relid, - interpretInhOption(stmt->relation->inhOpt), + interpretInhOption(stmt->relation->inhOpt), false); break; default: /* oops */ @@ -652,8 +660,8 @@ ProcessUtility(Node *parsetree, /* check that we are the superuser */ if (!superuser()) ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("must be superuser to alter owner"))); + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("must be superuser to alter owner"))); /* get_usesysid raises an error if no such user */ AlterTypeOwner(stmt->typename, get_usesysid(stmt->name)); @@ -828,40 +836,39 @@ ProcessUtility(Node *parsetree, VariableSetStmt *n = (VariableSetStmt *) parsetree; /* - * Special cases for special SQL syntax that - * effectively sets more than one variable per - * statement. + * Special cases for special SQL syntax that effectively + * sets more than one variable per statement. */ - if (strcmp(n->name, "TRANSACTION")==0) + if (strcmp(n->name, "TRANSACTION") == 0) { - List *head; + List *head; foreach(head, n->args) { - DefElem *item = (DefElem *) lfirst(head); + DefElem *item = (DefElem *) lfirst(head); - if (strcmp(item->defname, "transaction_isolation")==0) + if (strcmp(item->defname, "transaction_isolation") == 0) SetPGVariable("transaction_isolation", - makeList1(item->arg), n->is_local); - else if (strcmp(item->defname, "transaction_read_only")==0) + makeList1(item->arg), n->is_local); + else if (strcmp(item->defname, "transaction_read_only") == 0) SetPGVariable("transaction_read_only", - makeList1(item->arg), n->is_local); + makeList1(item->arg), n->is_local); } } - else if (strcmp(n->name, "SESSION CHARACTERISTICS")==0) + else if (strcmp(n->name, "SESSION CHARACTERISTICS") == 0) { - List *head; + List *head; foreach(head, n->args) { - DefElem *item = (DefElem *) lfirst(head); + DefElem *item = (DefElem *) lfirst(head); - if (strcmp(item->defname, "transaction_isolation")==0) + if (strcmp(item->defname, "transaction_isolation") == 0) SetPGVariable("default_transaction_isolation", - makeList1(item->arg), n->is_local); - else if (strcmp(item->defname, "transaction_read_only")==0) + makeList1(item->arg), n->is_local); + else if (strcmp(item->defname, "transaction_read_only") == 0) SetPGVariable("default_transaction_read_only", - makeList1(item->arg), n->is_local); + makeList1(item->arg), n->is_local); } } else @@ -1046,14 +1053,14 @@ UtilityReturnsTuples(Node *parsetree) { case T_FetchStmt: { - FetchStmt *stmt = (FetchStmt *) parsetree; - Portal portal; + FetchStmt *stmt = (FetchStmt *) parsetree; + Portal portal; if (stmt->ismove) return false; portal = GetPortalByName(stmt->portalname); if (!PortalIsValid(portal)) - return false; /* not our business to raise error */ + return false; /* not our business to raise error */ return portal->tupDesc ? true : false; } @@ -1066,7 +1073,7 @@ UtilityReturnsTuples(Node *parsetree) return false; entry = FetchPreparedStatement(stmt->name, false); if (!entry) - return false; /* not our business to raise error */ + return false; /* not our business to raise error */ switch (ChoosePortalStrategy(entry->query_list)) { case PORTAL_ONE_SELECT: @@ -1106,14 +1113,14 @@ UtilityTupleDescriptor(Node *parsetree) { case T_FetchStmt: { - FetchStmt *stmt = (FetchStmt *) parsetree; - Portal portal; + FetchStmt *stmt = (FetchStmt *) parsetree; + Portal portal; if (stmt->ismove) return NULL; portal = GetPortalByName(stmt->portalname); if (!PortalIsValid(portal)) - return NULL; /* not our business to raise error */ + return NULL; /* not our business to raise error */ return CreateTupleDescCopy(portal->tupDesc); } @@ -1126,7 +1133,7 @@ UtilityTupleDescriptor(Node *parsetree) return NULL; entry = FetchPreparedStatement(stmt->name, false); if (!entry) - return NULL; /* not our business to raise error */ + return NULL; /* not our business to raise error */ return FetchPreparedStatementResultDesc(entry); } diff --git a/src/backend/utils/adt/acl.c b/src/backend/utils/adt/acl.c index 8c5f64a8ed..57a3db1dd2 100644 --- a/src/backend/utils/adt/acl.c +++ b/src/backend/utils/adt/acl.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/acl.c,v 1.92 2003/07/27 04:53:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/acl.c,v 1.93 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -36,7 +36,7 @@ static Acl *allocacl(int n); static const char *aclparse(const char *s, AclItem *aip); static bool aclitem_match(const AclItem *a1, const AclItem *a2); static Acl *recursive_revoke(Acl *acl, AclId grantee, - AclMode revoke_privs, DropBehavior behavior); + AclMode revoke_privs, DropBehavior behavior); static AclMode convert_priv_string(text *priv_type_text); @@ -77,24 +77,22 @@ getid(const char *s, char *n) /* This test had better match what putid() does, below */ for (; *s != '\0' && - (isalnum((unsigned char) *s) || - *s == '_' || - *s == '"' || - in_quotes); + (isalnum((unsigned char) *s) || + *s == '_' || + *s == '"' || + in_quotes); s++) { if (*s == '"') - { in_quotes = !in_quotes; - } else { - if (len >= NAMEDATALEN-1) + if (len >= NAMEDATALEN - 1) ereport(ERROR, (errcode(ERRCODE_NAME_TOO_LONG), errmsg("identifier too long"), - errdetail("Identifier must be less than %d characters.", - NAMEDATALEN))); + errdetail("Identifier must be less than %d characters.", + NAMEDATALEN))); n[len++] = *s; } @@ -107,13 +105,13 @@ getid(const char *s, char *n) /* * Write a user or group Name at *p, surrounding it with double quotes if - * needed. There must be at least NAMEDATALEN+2 bytes available at *p. + * needed. There must be at least NAMEDATALEN+2 bytes available at *p. */ static void putid(char *p, const char *s) { const char *src; - bool safe = true; + bool safe = true; for (src = s; *src; src++) { @@ -153,7 +151,9 @@ putid(char *p, const char *s) static const char * aclparse(const char *s, AclItem *aip) { - AclMode privs, goption, read; + AclMode privs, + goption, + read; uint32 idtype; char name[NAMEDATALEN]; char name2[NAMEDATALEN]; @@ -174,13 +174,13 @@ aclparse(const char *s, AclItem *aip) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("unrecognized keyword: \"%s\"", name), - errhint("ACL keyword must be \"group\" or \"user\"."))); + errhint("ACL keyword must be \"group\" or \"user\"."))); s = getid(s, name); /* move s to the name beyond the keyword */ if (name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("missing name"), - errhint("A name must follow the [group|user] keyword."))); + errhint("A name must follow the [group|user] keyword."))); } if (name[0] == '\0') idtype = ACL_IDTYPE_WORLD; @@ -192,7 +192,7 @@ aclparse(const char *s, AclItem *aip) privs = goption = ACL_NO_RIGHTS; - for (++s, read=0; isalpha((unsigned char) *s) || *s == '*'; s++) + for (++s, read = 0; isalpha((unsigned char) *s) || *s == '*'; s++) { switch (*s) { @@ -235,8 +235,8 @@ aclparse(const char *s, AclItem *aip) default: ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid mode character: must be one of \"%s\"", - ACL_ALL_RIGHTS_STR))); + errmsg("invalid mode character: must be one of \"%s\"", + ACL_ALL_RIGHTS_STR))); } privs |= read; @@ -255,8 +255,10 @@ aclparse(const char *s, AclItem *aip) break; } - /* XXX Allow a degree of backward compatibility by defaulting the - * grantor to the superuser. */ + /* + * XXX Allow a degree of backward compatibility by defaulting the + * grantor to the superuser. + */ if (*s == '/') { s = getid(s + 1, name2); @@ -331,7 +333,7 @@ aclitemin(PG_FUNCTION_ARGS) if (*s) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("extra garbage at the end of the ACL specification"))); + errmsg("extra garbage at the end of the ACL specification"))); PG_RETURN_ACLITEM_P(aip); } @@ -356,7 +358,7 @@ aclitemout(PG_FUNCTION_ARGS) out = palloc(strlen("group =/") + 2 * N_ACL_RIGHTS + - 2 * (NAMEDATALEN+2) + + 2 * (NAMEDATALEN + 2) + 1); p = out; @@ -454,8 +456,8 @@ aclitem_match(const AclItem *a1, const AclItem *a2) Datum aclitem_eq(PG_FUNCTION_ARGS) { - AclItem *a1 = PG_GETARG_ACLITEM_P(0); - AclItem *a2 = PG_GETARG_ACLITEM_P(1); + AclItem *a1 = PG_GETARG_ACLITEM_P(0); + AclItem *a2 = PG_GETARG_ACLITEM_P(1); bool result; result = a1->ai_privs == a2->ai_privs && @@ -510,7 +512,7 @@ acldefault(GrantObjectType objtype, AclId ownerid) } acl = allocacl((world_default != ACL_NO_RIGHTS ? 1 : 0) - + (ownerid ? 1 : 0)); + + (ownerid ? 1 : 0)); aip = ACL_DAT(acl); if (world_default != ACL_NO_RIGHTS) @@ -522,7 +524,7 @@ acldefault(GrantObjectType objtype, AclId ownerid) if (ownerid) { - int index = (world_default != ACL_NO_RIGHTS ? 1: 0); + int index = (world_default != ACL_NO_RIGHTS ? 1 : 0); aip[index].ai_grantee = ownerid; aip[index].ai_grantor = ownerid; @@ -563,10 +565,10 @@ aclinsert3(const Acl *old_acl, const AclItem *mod_aip, unsigned modechg, DropBeh old_aip = ACL_DAT(old_acl); /* - * Search the ACL for an existing entry for this grantee and - * grantor. If one exists, just modify the entry in-place (well, - * in the same position, since we actually return a copy); - * otherwise, insert the new entry at the end. + * Search the ACL for an existing entry for this grantee and grantor. + * If one exists, just modify the entry in-place (well, in the same + * position, since we actually return a copy); otherwise, insert the + * new entry at the end. */ for (dst = 0; dst < num; ++dst) @@ -652,17 +654,17 @@ recursive_revoke(Acl *acl, AclMode revoke_privs, DropBehavior behavior) { - int i; + int i; restart: for (i = 0; i < ACL_NUM(acl); i++) { - AclItem *aip = ACL_DAT(acl); + AclItem *aip = ACL_DAT(acl); if (aip[i].ai_grantor == grantee && (ACLITEM_GET_PRIVS(aip[i]) & revoke_privs) != 0) { - AclItem mod_acl; + AclItem mod_acl; if (behavior == DROP_RESTRICT) ereport(ERROR, @@ -727,7 +729,7 @@ aclremove(PG_FUNCTION_ARGS) for (dst = 0; dst < old_num && !aclitem_match(mod_aip, old_aip + dst); ++dst) - /* continue */ ; + /* continue */ ; if (dst >= old_num) { @@ -797,15 +799,17 @@ makeaclitem(PG_FUNCTION_ARGS) int32 grantor = PG_GETARG_INT32(2); text *privtext = PG_GETARG_TEXT_P(3); bool goption = PG_GETARG_BOOL(4); - AclItem *aclitem; + AclItem *aclitem; AclMode priv; priv = convert_priv_string(privtext); aclitem = (AclItem *) palloc(sizeof(*aclitem)); + if (u_grantee == 0 && g_grantee == 0) { - aclitem->ai_grantee = 0; + aclitem ->ai_grantee = 0; + ACLITEM_SET_IDTYPE(*aclitem, ACL_IDTYPE_WORLD); } else if (u_grantee != 0 && g_grantee != 0) @@ -816,16 +820,19 @@ makeaclitem(PG_FUNCTION_ARGS) } else if (u_grantee != 0) { - aclitem->ai_grantee = u_grantee; + aclitem ->ai_grantee = u_grantee; + ACLITEM_SET_IDTYPE(*aclitem, ACL_IDTYPE_UID); } else if (g_grantee != 0) { - aclitem->ai_grantee = g_grantee; + aclitem ->ai_grantee = g_grantee; + ACLITEM_SET_IDTYPE(*aclitem, ACL_IDTYPE_GID); } - aclitem->ai_grantor = grantor; + aclitem ->ai_grantor = grantor; + ACLITEM_SET_PRIVS(*aclitem, priv); if (goption) ACLITEM_SET_GOPTIONS(*aclitem, priv); @@ -841,7 +848,7 @@ convert_priv_string(text *priv_type_text) char *priv_type; priv_type = DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(priv_type_text))); + PointerGetDatum(priv_type_text))); if (strcasecmp(priv_type, "SELECT") == 0) return ACL_SELECT; diff --git a/src/backend/utils/adt/array_userfuncs.c b/src/backend/utils/adt/array_userfuncs.c index 7a9e89088a..a32ea871b5 100644 --- a/src/backend/utils/adt/array_userfuncs.c +++ b/src/backend/utils/adt/array_userfuncs.c @@ -6,7 +6,7 @@ * Copyright (c) 2003, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/array_userfuncs.c,v 1.6 2003/07/27 04:53:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/array_userfuncs.c,v 1.7 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -81,7 +81,8 @@ array_push(PG_FUNCTION_ARGS) if (arg0_elemid != InvalidOid) { /* append newelem */ - int ub = dimv[0] + lb[0] - 1; + int ub = dimv[0] + lb[0] - 1; + indx = ub + 1; } else @@ -105,7 +106,7 @@ array_push(PG_FUNCTION_ARGS) if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = InvalidOid; } @@ -138,11 +139,23 @@ array_push(PG_FUNCTION_ARGS) Datum array_cat(PG_FUNCTION_ARGS) { - ArrayType *v1, *v2; - int *dims, *lbs, ndims, ndatabytes, nbytes; - int *dims1, *lbs1, ndims1, ndatabytes1; - int *dims2, *lbs2, ndims2, ndatabytes2; - char *dat1, *dat2; + ArrayType *v1, + *v2; + int *dims, + *lbs, + ndims, + ndatabytes, + nbytes; + int *dims1, + *lbs1, + ndims1, + ndatabytes1; + int *dims2, + *lbs2, + ndims2, + ndatabytes2; + char *dat1, + *dat2; Oid element_type; Oid element_type1; Oid element_type2; @@ -152,12 +165,10 @@ array_cat(PG_FUNCTION_ARGS) v2 = PG_GETARG_ARRAYTYPE_P(1); /* - * We must have one of the following combinations of inputs: - * 1) one empty array, and one non-empty array - * 2) both arrays empty - * 3) two arrays with ndims1 == ndims2 - * 4) ndims1 == ndims2 - 1 - * 5) ndims1 == ndims2 + 1 + * We must have one of the following combinations of inputs: 1) one + * empty array, and one non-empty array 2) both arrays empty 3) two + * arrays with ndims1 == ndims2 4) ndims1 == ndims2 - 1 5) ndims1 == + * ndims2 + 1 */ ndims1 = ARR_NDIM(v1); ndims2 = ARR_NDIM(v2); @@ -180,8 +191,8 @@ array_cat(PG_FUNCTION_ARGS) (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("cannot concatenate incompatible arrays"), errdetail("Arrays of %d and %d dimensions are not " - "compatible for concatenation.", - ndims1, ndims2))); + "compatible for concatenation.", + ndims1, ndims2))); element_type1 = ARR_ELEMTYPE(v1); element_type2 = ARR_ELEMTYPE(v2); @@ -192,7 +203,7 @@ array_cat(PG_FUNCTION_ARGS) (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("cannot concatenate incompatible arrays"), errdetail("Arrays with element types %s and %s are not " - "compatible for concatenation.", + "compatible for concatenation.", format_type_be(element_type1), format_type_be(element_type2)))); @@ -215,14 +226,14 @@ array_cat(PG_FUNCTION_ARGS) * resulting array has two element outer array made up of input * argument arrays */ - int i; + int i; ndims = ndims1 + 1; dims = (int *) palloc(ndims * sizeof(int)); lbs = (int *) palloc(ndims * sizeof(int)); - dims[0] = 2; /* outer array made up of two input arrays */ - lbs[0] = 1; /* start lower bound at 1 */ + dims[0] = 2; /* outer array made up of two input arrays */ + lbs[0] = 1; /* start lower bound at 1 */ for (i = 0; i < ndims1; i++) { @@ -230,8 +241,8 @@ array_cat(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("cannot concatenate incompatible arrays"), - errdetail("Arrays with differing dimensions are not " - "compatible for concatenation."))); + errdetail("Arrays with differing dimensions are not " + "compatible for concatenation."))); dims[i + 1] = dims1[i]; lbs[i + 1] = lbs1[i]; @@ -244,7 +255,7 @@ array_cat(PG_FUNCTION_ARGS) * with the first argument appended to the front of the outer * dimension */ - int i; + int i; ndims = ndims2; dims = dims2; @@ -260,18 +271,18 @@ array_cat(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("cannot concatenate incompatible arrays"), - errdetail("Arrays with differing dimensions are not " - "compatible for concatenation."))); + errdetail("Arrays with differing dimensions are not " + "compatible for concatenation."))); } } - else /* (ndims1 == ndims2 + 1) */ + else +/* (ndims1 == ndims2 + 1) */ { /* - * resulting array has the first argument as the outer array, - * with the second argument appended to the end of the outer - * dimension + * resulting array has the first argument as the outer array, with + * the second argument appended to the end of the outer dimension */ - int i; + int i; ndims = ndims1; dims = dims1; @@ -287,8 +298,8 @@ array_cat(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("cannot concatenate incompatible arrays"), - errdetail("Arrays with differing dimensions are not " - "compatible for concatenation."))); + errdetail("Arrays with differing dimensions are not " + "compatible for concatenation."))); } } @@ -320,13 +331,13 @@ create_singleton_array(FunctionCallInfo fcinfo, Datum element, int ndims) { - Datum dvalues[1]; - int16 typlen; - bool typbyval; - char typalign; - int dims[MAXDIM]; - int lbs[MAXDIM]; - int i; + Datum dvalues[1]; + int16 typlen; + bool typbyval; + char typalign; + int dims[MAXDIM]; + int lbs[MAXDIM]; + int i; ArrayMetaState *my_extra; if (element_type == 0) @@ -359,7 +370,7 @@ create_singleton_array(FunctionCallInfo fcinfo, if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = InvalidOid; } diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index 04e7f0f251..128a69f9d3 100644 --- a/src/backend/utils/adt/arrayfuncs.c +++ b/src/backend/utils/adt/arrayfuncs.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/arrayfuncs.c,v 1.94 2003/07/27 04:53:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/arrayfuncs.c,v 1.95 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -79,9 +79,9 @@ static Datum *ReadArrayStr(char *arrayStr, int nitems, int ndim, int *dim, int typlen, bool typbyval, char typalign, int *nbytes); static Datum *ReadArrayBinary(StringInfo buf, int nitems, - FmgrInfo *receiveproc, Oid typelem, - int typlen, bool typbyval, char typalign, - int *nbytes); + FmgrInfo *receiveproc, Oid typelem, + int typlen, bool typbyval, char typalign, + int *nbytes); static void CopyArrayEls(char *p, Datum *values, int nitems, int typlen, bool typbyval, char typalign, bool freedata); @@ -107,7 +107,7 @@ static void array_insert_slice(int ndim, int *dim, int *lb, char *destPtr, int *st, int *endp, char *srcPtr, int typlen, bool typbyval, char typalign); -static int array_cmp(FunctionCallInfo fcinfo); +static int array_cmp(FunctionCallInfo fcinfo); /*--------------------------------------------------------------------- * array_in : @@ -144,21 +144,24 @@ array_in(PG_FUNCTION_ARGS) /* * We arrange to look up info about element type, including its input - * conversion proc, only once per series of calls, assuming the element - * type doesn't change underneath us. + * conversion proc, only once per series of calls, assuming the + * element type doesn't change underneath us. */ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = InvalidOid; } if (my_extra->element_type != element_type) { - /* Get info about element type, including its input conversion proc */ + /* + * Get info about element type, including its input conversion + * proc + */ get_type_io_data(element_type, IOFunc_input, &my_extra->typlen, &my_extra->typbyval, &my_extra->typalign, &my_extra->typdelim, @@ -242,7 +245,7 @@ array_in(PG_FUNCTION_ARGS) if (ub < lBound[ndim]) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), - errmsg("upper bound cannot be less than lower bound"))); + errmsg("upper bound cannot be less than lower bound"))); dim[ndim] = ub - lBound[ndim] + 1; ndim++; @@ -351,7 +354,7 @@ ArrayCount(char *str, int *dim, char typdelim) /* Signal a premature end of the string */ ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", str))); + errmsg("malformed array literal: \"%s\"", str))); break; case '\\': /* skip the escaped character */ @@ -359,8 +362,8 @@ ArrayCount(char *str, int *dim, char typdelim) ptr++; else ereport(ERROR, - (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", str))); + (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), + errmsg("malformed array literal: \"%s\"", str))); break; case '\"': scanning_string = !scanning_string; @@ -370,9 +373,9 @@ ArrayCount(char *str, int *dim, char typdelim) { if (nest_level >= MAXDIM) ereport(ERROR, - (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), - errmsg("number of array dimensions exceeds the maximum allowed, %d", - MAXDIM))); + (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), + errmsg("number of array dimensions exceeds the maximum allowed, %d", + MAXDIM))); temp[nest_level] = 0; nest_level++; if (ndim < nest_level) @@ -384,8 +387,8 @@ ArrayCount(char *str, int *dim, char typdelim) { if (nest_level == 0) ereport(ERROR, - (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", str))); + (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), + errmsg("malformed array literal: \"%s\"", str))); nest_level--; if (nest_level == 0) eoArray = itemdone = true; @@ -479,7 +482,7 @@ ReadArrayStr(char *arrayStr, /* Signal a premature end of the string */ ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", arrayStr))); + errmsg("malformed array literal: \"%s\"", arrayStr))); break; case '\\': { @@ -490,8 +493,8 @@ ReadArrayStr(char *arrayStr, *cptr = *(cptr + 1); if (*ptr == '\0') ereport(ERROR, - (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", arrayStr))); + (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), + errmsg("malformed array literal: \"%s\"", arrayStr))); break; } case '\"': @@ -511,8 +514,8 @@ ReadArrayStr(char *arrayStr, { if (nest_level >= ndim) ereport(ERROR, - (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", arrayStr))); + (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), + errmsg("malformed array literal: \"%s\"", arrayStr))); nest_level++; indx[nest_level - 1] = 0; /* skip leading whitespace */ @@ -526,8 +529,8 @@ ReadArrayStr(char *arrayStr, { if (nest_level == 0) ereport(ERROR, - (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", arrayStr))); + (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), + errmsg("malformed array literal: \"%s\"", arrayStr))); if (i == -1) i = ArrayGetOffset0(ndim, indx, prod); indx[nest_level - 1] = 0; @@ -565,7 +568,7 @@ ReadArrayStr(char *arrayStr, if (i < 0 || i >= nitems) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("malformed array literal: \"%s\"", arrayStr))); + errmsg("malformed array literal: \"%s\"", arrayStr))); values[i] = FunctionCall3(inputproc, CStringGetDatum(itemstart), @@ -693,21 +696,24 @@ array_out(PG_FUNCTION_ARGS) /* * We arrange to look up info about element type, including its output - * conversion proc, only once per series of calls, assuming the element - * type doesn't change underneath us. + * conversion proc, only once per series of calls, assuming the + * element type doesn't change underneath us. */ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = InvalidOid; } if (my_extra->element_type != element_type) { - /* Get info about element type, including its output conversion proc */ + /* + * Get info about element type, including its output conversion + * proc + */ get_type_io_data(element_type, IOFunc_output, &my_extra->typlen, &my_extra->typbyval, &my_extra->typalign, &my_extra->typdelim, @@ -922,15 +928,15 @@ array_recv(PG_FUNCTION_ARGS) } /* - * We arrange to look up info about element type, including its receive - * conversion proc, only once per series of calls, assuming the element - * type doesn't change underneath us. + * We arrange to look up info about element type, including its + * receive conversion proc, only once per series of calls, assuming + * the element type doesn't change underneath us. */ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = InvalidOid; } @@ -945,8 +951,8 @@ array_recv(PG_FUNCTION_ARGS) if (!OidIsValid(my_extra->typiofunc)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("no binary input function available for type %s", - format_type_be(element_type)))); + errmsg("no binary input function available for type %s", + format_type_be(element_type)))); fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc, fcinfo->flinfo->fn_mcxt); my_extra->element_type = element_type; @@ -1004,9 +1010,9 @@ ReadArrayBinary(StringInfo buf, for (i = 0; i < nitems; i++) { - int itemlen; + int itemlen; StringInfoData elem_buf; - char csave; + char csave; /* Get and check the item length */ itemlen = pq_getmsgint(buf, 4); @@ -1017,10 +1023,9 @@ ReadArrayBinary(StringInfo buf, /* * Rather than copying data around, we just set up a phony - * StringInfo pointing to the correct portion of the input - * buffer. We assume we can scribble on the input buffer - * so as to maintain the convention that StringInfos have - * a trailing null. + * StringInfo pointing to the correct portion of the input buffer. + * We assume we can scribble on the input buffer so as to maintain + * the convention that StringInfos have a trailing null. */ elem_buf.data = &buf->data[buf->cursor]; elem_buf.maxlen = itemlen + 1; @@ -1042,7 +1047,7 @@ ReadArrayBinary(StringInfo buf, ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), errmsg("improper binary format in array element %d", - i + 1))); + i + 1))); buf->data[buf->cursor] = csave; } @@ -1051,9 +1056,7 @@ ReadArrayBinary(StringInfo buf, * Compute total data space needed */ if (typlen > 0) - { *nbytes = nitems * att_align(typlen, typalign); - } else { Assert(!typbyval); @@ -1100,14 +1103,14 @@ array_send(PG_FUNCTION_ARGS) /* * We arrange to look up info about element type, including its send - * conversion proc, only once per series of calls, assuming the element - * type doesn't change underneath us. + * conversion proc, only once per series of calls, assuming the + * element type doesn't change underneath us. */ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = InvalidOid; } @@ -1122,8 +1125,8 @@ array_send(PG_FUNCTION_ARGS) if (!OidIsValid(my_extra->typiofunc)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("no binary output function available for type %s", - format_type_be(element_type)))); + errmsg("no binary output function available for type %s", + format_type_be(element_type)))); fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc, fcinfo->flinfo->fn_mcxt); my_extra->element_type = element_type; @@ -1160,7 +1163,7 @@ array_send(PG_FUNCTION_ARGS) outputbytes = DatumGetByteaP(FunctionCall2(&my_extra->proc, itemvalue, - ObjectIdGetDatum(typelem))); + ObjectIdGetDatum(typelem))); /* We assume the result will not have been toasted */ pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4); pq_sendbytes(&buf, VARDATA(outputbytes), @@ -1187,10 +1190,11 @@ array_length_coerce(PG_FUNCTION_ARGS) int32 len = PG_GETARG_INT32(1); bool isExplicit = PG_GETARG_BOOL(2); FmgrInfo *fmgr_info = fcinfo->flinfo; - typedef struct { + typedef struct + { Oid elemtype; FmgrInfo coerce_finfo; - } alc_extra; + } alc_extra; alc_extra *my_extra; FunctionCallInfoData locfcinfo; @@ -1471,7 +1475,7 @@ array_get_slice(ArrayType *array, */ ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("slices of fixed-length arrays not implemented"))); + errmsg("slices of fixed-length arrays not implemented"))); /* * fixed-length arrays -- these are assumed to be 1-d, 0-based XXX @@ -1634,12 +1638,12 @@ array_set(ArrayType *array, /* * if number of dims is zero, i.e. an empty array, create an array - * with nSubscripts dimensions, and set the lower bounds to the supplied - * subscripts + * with nSubscripts dimensions, and set the lower bounds to the + * supplied subscripts */ if (ndim == 0) { - Oid elmtype = ARR_ELEMTYPE(array); + Oid elmtype = ARR_ELEMTYPE(array); for (i = 0; i < nSubscripts; i++) { @@ -1648,7 +1652,7 @@ array_set(ArrayType *array, } return construct_md_array(&dataValue, nSubscripts, dim, lb, elmtype, - elmlen, elmbyval, elmalign); + elmlen, elmbyval, elmalign); } if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM) @@ -1818,17 +1822,17 @@ array_set_slice(ArrayType *array, /* * if number of dims is zero, i.e. an empty array, create an array - * with nSubscripts dimensions, and set the upper and lower bounds - * to the supplied subscripts + * with nSubscripts dimensions, and set the upper and lower bounds to + * the supplied subscripts */ if (ndim == 0) { - Datum *dvalues; - int nelems; - Oid elmtype = ARR_ELEMTYPE(array); + Datum *dvalues; + int nelems; + Oid elmtype = ARR_ELEMTYPE(array); deconstruct_array(srcArray, elmtype, elmlen, elmbyval, elmalign, - &dvalues, &nelems); + &dvalues, &nelems); for (i = 0; i < nSubscripts; i++) { @@ -1837,7 +1841,7 @@ array_set_slice(ArrayType *array, } return construct_md_array(dvalues, nSubscripts, dim, lb, elmtype, - elmlen, elmbyval, elmalign); + elmlen, elmbyval, elmalign); } if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM) @@ -2028,11 +2032,12 @@ array_map(FunctionCallInfo fcinfo, Oid inpType, Oid retType) bool typbyval; char typalign; char *s; - typedef struct { + typedef struct + { ArrayMetaState inp_extra; ArrayMetaState ret_extra; - } am_extra; - am_extra *my_extra; + } am_extra; + am_extra *my_extra; ArrayMetaState *inp_extra; ArrayMetaState *ret_extra; @@ -2054,9 +2059,9 @@ array_map(FunctionCallInfo fcinfo, Oid inpType, Oid retType) PG_RETURN_ARRAYTYPE_P(v); /* - * We arrange to look up info about input and return element types only - * once per series of calls, assuming the element type doesn't change - * underneath us. + * We arrange to look up info about input and return element types + * only once per series of calls, assuming the element type doesn't + * change underneath us. */ my_extra = (am_extra *) fcinfo->flinfo->fn_extra; if (my_extra == NULL) @@ -2179,8 +2184,8 @@ construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign) { - int dims[1]; - int lbs[1]; + int dims[1]; + int lbs[1]; dims[0] = nelems; lbs[0] = 1; @@ -2364,7 +2369,7 @@ array_eq(PG_FUNCTION_ARGS) if (element_type != ARR_ELEMTYPE(array2)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("cannot compare arrays of different element types"))); + errmsg("cannot compare arrays of different element types"))); /* fast path if the arrays do not have the same number of elements */ if (nitems1 != nitems2) @@ -2372,21 +2377,22 @@ array_eq(PG_FUNCTION_ARGS) else { /* - * We arrange to look up the equality function only once per series of - * calls, assuming the element type doesn't change underneath us. + * We arrange to look up the equality function only once per + * series of calls, assuming the element type doesn't change + * underneath us. */ my_extra = (ArrayMetaState *) ae_fmgr_info->fn_extra; if (my_extra == NULL) { ae_fmgr_info->fn_extra = MemoryContextAlloc(ae_fmgr_info->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) ae_fmgr_info->fn_extra; my_extra->element_type = InvalidOid; } if (my_extra->element_type != element_type) { - Oid opfuncid = equality_oper_funcid(element_type); + Oid opfuncid = equality_oper_funcid(element_type); get_typlenbyvalalign(element_type, &my_extra->typlen, @@ -2410,9 +2416,9 @@ array_eq(PG_FUNCTION_ARGS) /* Loop over source data */ for (i = 0; i < nitems1; i++) { - Datum elt1; - Datum elt2; - bool oprresult; + Datum elt1; + Datum elt2; + bool oprresult; /* Get element pair */ elt1 = fetch_att(p1, typbyval, typlen); @@ -2519,20 +2525,20 @@ array_cmp(FunctionCallInfo fcinfo) int i; typedef struct { - Oid element_type; - int16 typlen; - bool typbyval; - char typalign; - FmgrInfo eqproc; - FmgrInfo ordproc; - } ac_extra; - ac_extra *my_extra; + Oid element_type; + int16 typlen; + bool typbyval; + char typalign; + FmgrInfo eqproc; + FmgrInfo ordproc; + } ac_extra; + ac_extra *my_extra; element_type = ARR_ELEMTYPE(array1); if (element_type != ARR_ELEMTYPE(array2)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("cannot compare arrays of different element types"))); + errmsg("cannot compare arrays of different element types"))); /* * We arrange to look up the element type info and related functions @@ -2550,8 +2556,8 @@ array_cmp(FunctionCallInfo fcinfo) if (my_extra->element_type != element_type) { - Oid eqfuncid = equality_oper_funcid(element_type); - Oid ordfuncid = ordering_oper_funcid(element_type); + Oid eqfuncid = equality_oper_funcid(element_type); + Oid ordfuncid = ordering_oper_funcid(element_type); get_typlenbyvalalign(element_type, &my_extra->typlen, @@ -2569,10 +2575,10 @@ array_cmp(FunctionCallInfo fcinfo) /* extract a C array of arg array datums */ deconstruct_array(array1, element_type, typlen, typbyval, typalign, - &dvalues1, &nelems1); + &dvalues1, &nelems1); deconstruct_array(array2, element_type, typlen, typbyval, typalign, - &dvalues2, &nelems2); + &dvalues2, &nelems2); min_nelems = Min(nelems1, nelems2); for (i = 0; i < min_nelems; i++) @@ -2875,7 +2881,7 @@ array_insert_slice(int ndim, /* * array_type_coerce -- allow explicit or assignment coercion from * one array type to another. - * + * * Caller should have already verified that the source element type can be * coerced into the target element type. */ @@ -2885,11 +2891,12 @@ array_type_coerce(PG_FUNCTION_ARGS) ArrayType *src = PG_GETARG_ARRAYTYPE_P(0); Oid src_elem_type = ARR_ELEMTYPE(src); FmgrInfo *fmgr_info = fcinfo->flinfo; - typedef struct { + typedef struct + { Oid srctype; Oid desttype; FmgrInfo coerce_finfo; - } atc_extra; + } atc_extra; atc_extra *my_extra; FunctionCallInfoData locfcinfo; @@ -2925,12 +2932,11 @@ array_type_coerce(PG_FUNCTION_ARGS) errmsg("target type is not an array"))); /* - * We don't deal with domain constraints yet, so bail out. - * This isn't currently a problem, because we also don't - * support arrays of domain type elements either. But in the - * future we might. At that point consideration should be given - * to removing the check below and adding a domain constraints - * check to the coercion. + * We don't deal with domain constraints yet, so bail out. This + * isn't currently a problem, because we also don't support arrays + * of domain type elements either. But in the future we might. At + * that point consideration should be given to removing the check + * below and adding a domain constraints check to the coercion. */ if (getBaseType(tgt_elem_type) != tgt_elem_type) ereport(ERROR, @@ -2943,7 +2949,7 @@ array_type_coerce(PG_FUNCTION_ARGS) { /* should never happen, but check anyway */ elog(ERROR, "no conversion function from %s to %s", - format_type_be(src_elem_type), format_type_be(tgt_elem_type)); + format_type_be(src_elem_type), format_type_be(tgt_elem_type)); } if (OidIsValid(funcId)) fmgr_info_cxt(funcId, &my_extra->coerce_finfo, fmgr_info->fn_mcxt); @@ -2954,13 +2960,13 @@ array_type_coerce(PG_FUNCTION_ARGS) } /* - * If it's binary-compatible, modify the element type in the array header, - * but otherwise leave the array as we received it. + * If it's binary-compatible, modify the element type in the array + * header, but otherwise leave the array as we received it. */ if (my_extra->coerce_finfo.fn_oid == InvalidOid) { ArrayType *result = DatumGetArrayTypePCopy(PG_GETARG_DATUM(0)); - + ARR_ELEMTYPE(result) = my_extra->desttype; PG_RETURN_ARRAYTYPE_P(result); } @@ -2983,13 +2989,13 @@ array_type_coerce(PG_FUNCTION_ARGS) * rcontext is where to keep working state */ ArrayBuildState * -accumArrayResult(ArrayBuildState *astate, +accumArrayResult(ArrayBuildState * astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext) { MemoryContext arr_context, - oldcontext; + oldcontext; if (astate == NULL) { @@ -3021,7 +3027,7 @@ accumArrayResult(ArrayBuildState *astate, if ((astate->nelems % ARRAY_ELEMS_CHUNKSIZE) == 0) astate->dvalues = (Datum *) repalloc(astate->dvalues, - (astate->nelems + ARRAY_ELEMS_CHUNKSIZE) * sizeof(Datum)); + (astate->nelems + ARRAY_ELEMS_CHUNKSIZE) * sizeof(Datum)); } if (disnull) @@ -3045,7 +3051,7 @@ accumArrayResult(ArrayBuildState *astate, * rcontext is where to construct result */ Datum -makeArrayResult(ArrayBuildState *astate, +makeArrayResult(ArrayBuildState * astate, MemoryContext rcontext) { int dims[1]; @@ -3067,7 +3073,7 @@ makeArrayResult(ArrayBuildState *astate, * rcontext is where to construct result */ Datum -makeMdArrayResult(ArrayBuildState *astate, +makeMdArrayResult(ArrayBuildState * astate, int ndims, int *dims, int *lbs, diff --git a/src/backend/utils/adt/ascii.c b/src/backend/utils/adt/ascii.c index fe7d6ba74f..adb03d3d0e 100644 --- a/src/backend/utils/adt/ascii.c +++ b/src/backend/utils/adt/ascii.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1999-2002, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/ascii.c,v 1.16 2003/07/27 04:53:03 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/ascii.c,v 1.17 2003/08/04 00:43:25 momjian Exp $ * *----------------------------------------------------------------------- */ @@ -16,7 +16,7 @@ #include "utils/ascii.h" static void pg_to_ascii(unsigned char *src, unsigned char *src_end, - unsigned char *dest, int enc); + unsigned char *dest, int enc); static text *encode_to_ascii(text *data, int enc); @@ -65,8 +65,8 @@ pg_to_ascii(unsigned char *src, unsigned char *src_end, unsigned char *dest, int { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("unsupported encoding conversion from %s to ASCII", - pg_encoding_to_char(enc)))); + errmsg("unsupported encoding conversion from %s to ASCII", + pg_encoding_to_char(enc)))); return; /* keep compiler quiet */ } @@ -95,7 +95,7 @@ static text * encode_to_ascii(text *data, int enc) { pg_to_ascii((unsigned char *) VARDATA(data), /* src */ - (unsigned char *) (data) + VARSIZE(data), /* src end */ + (unsigned char *) (data) + VARSIZE(data), /* src end */ (unsigned char *) VARDATA(data), /* dest */ enc); /* encoding */ @@ -109,8 +109,8 @@ encode_to_ascii(text *data, int enc) Datum to_ascii_encname(PG_FUNCTION_ARGS) { - text *data = PG_GETARG_TEXT_P_COPY(0); - int enc = pg_char_to_encoding(NameStr(*PG_GETARG_NAME(1))); + text *data = PG_GETARG_TEXT_P_COPY(0); + int enc = pg_char_to_encoding(NameStr(*PG_GETARG_NAME(1))); PG_RETURN_TEXT_P(encode_to_ascii(data, enc)); } @@ -122,8 +122,8 @@ to_ascii_encname(PG_FUNCTION_ARGS) Datum to_ascii_enc(PG_FUNCTION_ARGS) { - text *data = PG_GETARG_TEXT_P_COPY(0); - int enc = PG_GETARG_INT32(1); + text *data = PG_GETARG_TEXT_P_COPY(0); + int enc = PG_GETARG_INT32(1); PG_RETURN_TEXT_P(encode_to_ascii(data, enc)); } @@ -135,8 +135,8 @@ to_ascii_enc(PG_FUNCTION_ARGS) Datum to_ascii_default(PG_FUNCTION_ARGS) { - text *data = PG_GETARG_TEXT_P_COPY(0); - int enc = GetDatabaseEncoding(); + text *data = PG_GETARG_TEXT_P_COPY(0); + int enc = GetDatabaseEncoding(); PG_RETURN_TEXT_P(encode_to_ascii(data, enc)); } diff --git a/src/backend/utils/adt/char.c b/src/backend/utils/adt/char.c index 5bf3a025d1..78a702a13e 100644 --- a/src/backend/utils/adt/char.c +++ b/src/backend/utils/adt/char.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/char.c,v 1.36 2003/07/27 04:53:04 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/char.c,v 1.37 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -57,7 +57,7 @@ charout(PG_FUNCTION_ARGS) * charrecv - converts external binary format to char * * The external representation is one byte, with no character set - * conversion. This is somewhat dubious, perhaps, but in many + * conversion. This is somewhat dubious, perhaps, but in many * cases people use char for a 1-byte binary type. */ Datum diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c index ed449e524d..b6d1b83d79 100644 --- a/src/backend/utils/adt/date.c +++ b/src/backend/utils/adt/date.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/date.c,v 1.87 2003/07/27 04:53:04 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/date.c,v 1.88 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -97,7 +97,7 @@ date_in(PG_FUNCTION_ARGS) default: ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for date: \"%s\"", str))); + errmsg("invalid input syntax for date: \"%s\"", str))); } date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE; @@ -465,7 +465,7 @@ abstime_date(PG_FUNCTION_ARGS) case NOEND_ABSTIME: ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot convert reserved abstime value to date"))); + errmsg("cannot convert reserved abstime value to date"))); /* * pretend to drop through to make compiler think that result @@ -527,7 +527,7 @@ text_date(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("invalid input syntax for date: \"%s\"", - VARDATA(str)))); + VARDATA(str)))); sp = VARDATA(str); dp = dstr; @@ -570,7 +570,7 @@ time_in(PG_FUNCTION_ARGS) errmsg("invalid input syntax for time: \"%s\"", str))); if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0) - || (DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0)) + || (DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0)) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("invalid input syntax for time: \"%s\"", str))); @@ -749,9 +749,9 @@ AdjustTimeForTypmod(TimeADT *time, int32 typmod) /* * Note: this round-to-nearest code is not completely consistent * about rounding values that are exactly halfway between integral - * values. On most platforms, rint() will implement round-to-nearest-even, - * but the integer code always rounds up (away from zero). Is it - * worth trying to be consistent? + * values. On most platforms, rint() will implement + * round-to-nearest-even, but the integer code always rounds up + * (away from zero). Is it worth trying to be consistent? */ #ifdef HAVE_INT64_TIMESTAMP if (*time >= INT64CONST(0)) @@ -761,8 +761,8 @@ AdjustTimeForTypmod(TimeADT *time, int32 typmod) } else { - *time = - ((((- *time) + TimeOffsets[typmod]) / TimeScales[typmod]) - * TimeScales[typmod]); + *time = -((((-*time) + TimeOffsets[typmod]) / TimeScales[typmod]) + * TimeScales[typmod]); } #else *time = (rint(((double) *time) * TimeScales[typmod]) @@ -1093,7 +1093,7 @@ time_interval(PG_FUNCTION_ARGS) * Convert interval to time data type. * * This is defined as producing the fractional-day portion of the interval. - * Therefore, we can just ignore the months field. It is not real clear + * Therefore, we can just ignore the months field. It is not real clear * what to do with negative intervals, but we choose to subtract the floor, * so that, say, '-2 hours' becomes '22:00:00'. */ @@ -1114,7 +1114,7 @@ interval_time(PG_FUNCTION_ARGS) } else if (result < 0) { - days = (-result + INT64CONST(86400000000-1)) / INT64CONST(86400000000); + days = (-result + INT64CONST(86400000000 - 1)) / INT64CONST(86400000000); result += days * INT64CONST(86400000000); } #else @@ -1256,7 +1256,7 @@ text_time(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("invalid input syntax for time: \"%s\"", - VARDATA(str)))); + VARDATA(str)))); sp = VARDATA(str); dp = dstr; @@ -1290,8 +1290,8 @@ time_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("TIME units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; @@ -1360,8 +1360,8 @@ time_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("TIME units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); result = 0; } @@ -1379,8 +1379,8 @@ time_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("TIME units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); result = 0; } @@ -1432,15 +1432,15 @@ timetz_in(PG_FUNCTION_ARGS) if (strlen(str) >= sizeof(lowstr)) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for time with time zone: \"%s\"", - str))); + errmsg("invalid input syntax for time with time zone: \"%s\"", + str))); if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0) || (DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0)) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for time with time zone: \"%s\"", - str))); + errmsg("invalid input syntax for time with time zone: \"%s\"", + str))); result = (TimeTzADT *) palloc(sizeof(TimeTzADT)); tm2timetz(tm, fsec, tz, result); @@ -2019,8 +2019,8 @@ text_timetz(PG_FUNCTION_ARGS) if (VARSIZE(str) - VARHDRSZ > MAXDATELEN) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for time with time zone: \"%s\"", - VARDATA(str)))); + errmsg("invalid input syntax for time with time zone: \"%s\"", + VARDATA(str)))); sp = VARDATA(str); dp = dstr; @@ -2054,8 +2054,8 @@ timetz_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("TIMETZ units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; @@ -2138,8 +2138,8 @@ timetz_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("TIMETZ units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); result = 0; } @@ -2157,8 +2157,8 @@ timetz_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("TIMETZ units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); result = 0; } @@ -2187,8 +2187,8 @@ timetz_zone(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("time zone \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(zone)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(zone)))))); up = VARDATA(zone); lp = lowzone; @@ -2246,8 +2246,8 @@ timetz_izone(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("INTERVAL time zone \"%s\" not legal", - DatumGetCString(DirectFunctionCall1(interval_out, - PointerGetDatum(zone)))))); + DatumGetCString(DirectFunctionCall1(interval_out, + PointerGetDatum(zone)))))); #ifdef HAVE_INT64_TIMESTAMP tz = -(zone->time / INT64CONST(1000000)); diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c index f053c9ebb2..1b1fd98a1f 100644 --- a/src/backend/utils/adt/datetime.c +++ b/src/backend/utils/adt/datetime.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/datetime.c,v 1.108 2003/07/29 00:03:18 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/datetime.c,v 1.109 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -575,9 +575,9 @@ static datetkn deltatktbl[] = { static unsigned int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0]; -static datetkn *datecache[MAXDATEFIELDS] = {NULL}; +static datetkn *datecache[MAXDATEFIELDS] = {NULL}; -static datetkn *deltacache[MAXDATEFIELDS] = {NULL}; +static datetkn *deltacache[MAXDATEFIELDS] = {NULL}; /* @@ -593,7 +593,7 @@ static datetkn *deltacache[MAXDATEFIELDS] = {NULL}; * * Rewritten to eliminate overflow problems. This now allows the * routines to work correctly for all Julian day counts from - * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming + * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming * a 32-bit integer. Longer types should also work to the limits * of their precision. */ @@ -604,18 +604,21 @@ date2j(int y, int m, int d) int julian; int century; - if (m > 2) { + if (m > 2) + { m += 1; y += 4800; - } else { + } + else + { m += 13; y += 4799; } - century = y/100; - julian = y*365 - 32167; - julian += y/4 - century + century/4; - julian += 7834*m/256 + d; + century = y / 100; + julian = y * 365 - 32167; + julian += y / 4 - century + century / 4; + julian += 7834 * m / 256 + d; return julian; } /* date2j() */ @@ -623,25 +626,25 @@ date2j(int y, int m, int d) void j2date(int jd, int *year, int *month, int *day) { - unsigned int julian; - unsigned int quad; - unsigned int extra; + unsigned int julian; + unsigned int quad; + unsigned int extra; int y; julian = jd; julian += 32044; - quad = julian/146097; - extra = (julian - quad*146097)*4 + 3; - julian += 60 + quad*3 + extra/146097; - quad = julian/1461; - julian -= quad*1461; + quad = julian / 146097; + extra = (julian - quad * 146097) * 4 + 3; + julian += 60 + quad * 3 + extra / 146097; + quad = julian / 1461; + julian -= quad * 1461; y = julian * 4 / 1461; julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366)) + 123; - y += quad*4; + y += quad * 4; *year = y - 4800; quad = julian * 2141 / 65536; - *day = julian - 7834*quad/256; + *day = julian - 7834 * quad / 256; *month = (quad + 10) % 12 + 1; return; @@ -652,7 +655,7 @@ j2date(int jd, int *year, int *month, int *day) * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat) * * Note: various places use the locution j2day(date - 1) to produce a - * result according to the convention 0..6 = Mon..Sun. This is a bit of + * result according to the convention 0..6 = Mon..Sun. This is a bit of * a crock, but will work as long as the computation here is just a modulo. */ int @@ -1252,8 +1255,8 @@ DecodeDateTime(char **field, int *ftype, int nf, { case DTK_CURRENT: ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("\"current\" is no longer supported"))); + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("\"current\" is no longer supported"))); return -1; break; @@ -1269,7 +1272,7 @@ DecodeDateTime(char **field, int *ftype, int nf, *dtype = DTK_DATE; GetCurrentDateTime(tm); j2date((date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1), - &tm->tm_year, &tm->tm_mon, &tm->tm_mday); + &tm->tm_year, &tm->tm_mon, &tm->tm_mday); tm->tm_hour = 0; tm->tm_min = 0; tm->tm_sec = 0; @@ -1289,7 +1292,7 @@ DecodeDateTime(char **field, int *ftype, int nf, *dtype = DTK_DATE; GetCurrentDateTime(tm); j2date((date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1), - &tm->tm_year, &tm->tm_mon, &tm->tm_mday); + &tm->tm_year, &tm->tm_mon, &tm->tm_mday); tm->tm_hour = 0; tm->tm_min = 0; tm->tm_sec = 0; @@ -1435,8 +1438,8 @@ DecodeDateTime(char **field, int *ftype, int nf, else ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("inconsistent use of year %04d and \"BC\"", - tm->tm_year))); + errmsg("inconsistent use of year %04d and \"BC\"", + tm->tm_year))); } else if (is2digits) { @@ -1994,8 +1997,8 @@ DecodeTimeOnly(char **field, int *ftype, int nf, { case DTK_CURRENT: ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("\"current\" is no longer supported"))); + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("\"current\" is no longer supported"))); return -1; break; @@ -2423,6 +2426,7 @@ DecodeNumber(int flen, char *str, int fmask, switch (fmask & DTK_DATE_M) { case 0: + /* * Nothing so far; make a decision about what we think the * input is. There used to be lots of heuristics here, but @@ -2487,9 +2491,7 @@ DecodeNumber(int flen, char *str, int fmask, * exactly two digits. */ if (*tmask == DTK_M(YEAR)) - { *is2digits = (flen == 2); - } return 0; } @@ -3300,8 +3302,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -3350,8 +3352,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -3396,8 +3398,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -3450,8 +3452,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha sprintf((str + 10), " %02d:%02d", tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -3746,7 +3748,7 @@ ClearDateCache(bool newval, bool doit, bool interactive) /* * We've been burnt by stupid errors in the ordering of the datetkn tables - * once too often. Arrange to check them during postmaster start. + * once too often. Arrange to check them during postmaster start. */ static bool CheckDateTokenTable(const char *tablename, datetkn *base, unsigned int nel) @@ -3756,11 +3758,11 @@ CheckDateTokenTable(const char *tablename, datetkn *base, unsigned int nel) for (i = 1; i < nel; i++) { - if (strncmp(base[i-1].token, base[i].token, TOKMAXLEN) >= 0) + if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0) { elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"", tablename, - TOKMAXLEN, base[i-1].token, + TOKMAXLEN, base[i - 1].token, TOKMAXLEN, base[i].token); ok = false; } diff --git a/src/backend/utils/adt/float.c b/src/backend/utils/adt/float.c index 9ef2e80da7..2bcd2ac68a 100644 --- a/src/backend/utils/adt/float.c +++ b/src/backend/utils/adt/float.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/float.c,v 1.91 2003/07/30 19:48:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/float.c,v 1.92 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -104,13 +104,13 @@ static double cbrt(double x); /* Configurable GUC parameter */ -int extra_float_digits = 0; /* Added to DBL_DIG or FLT_DIG */ +int extra_float_digits = 0; /* Added to DBL_DIG or FLT_DIG */ static void CheckFloat4Val(double val); static void CheckFloat8Val(double val); -static int float4_cmp_internal(float4 a, float4 b); -static int float8_cmp_internal(float8 a, float8 b); +static int float4_cmp_internal(float4 a, float4 b); +static int float8_cmp_internal(float8 a, float8 b); /* @@ -198,7 +198,7 @@ float4in(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for float4: \"%s\"", - num))); + num))); } else { diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c index 1df3593ee9..717b350beb 100644 --- a/src/backend/utils/adt/formatting.c +++ b/src/backend/utils/adt/formatting.c @@ -1,7 +1,7 @@ /* ----------------------------------------------------------------------- * formatting.c * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/formatting.c,v 1.64 2003/07/27 04:53:05 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/formatting.c,v 1.65 2003/08/04 00:43:25 momjian Exp $ * * * Portions Copyright (c) 1999-2002, PostgreSQL Global Development Group @@ -279,15 +279,15 @@ typedef struct #define NUM_F_DECIMAL (1 << 1) #define NUM_F_LDECIMAL (1 << 2) #define NUM_F_ZERO (1 << 3) -#define NUM_F_BLANK (1 << 4) +#define NUM_F_BLANK (1 << 4) #define NUM_F_FILLMODE (1 << 5) -#define NUM_F_LSIGN (1 << 6) +#define NUM_F_LSIGN (1 << 6) #define NUM_F_BRACKET (1 << 7) -#define NUM_F_MINUS (1 << 8) +#define NUM_F_MINUS (1 << 8) #define NUM_F_PLUS (1 << 9) -#define NUM_F_ROMAN (1 << 10) +#define NUM_F_ROMAN (1 << 10) #define NUM_F_MULTI (1 << 11) -#define NUM_F_PLUS_POST (1 << 12) +#define NUM_F_PLUS_POST (1 << 12) #define NUM_F_MINUS_POST (1 << 13) #define NUM_LSIGN_PRE -1 @@ -1018,7 +1018,7 @@ NUMDesc_prepare(NUMDesc *num, FormatNode *n) NUM_cache_remove(last_NUMCacheEntry); ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("cannot use \"V\" and decimal point together"))); + errmsg("cannot use \"V\" and decimal point together"))); } num->flag |= NUM_F_DECIMAL; break; @@ -1123,7 +1123,7 @@ NUMDesc_prepare(NUMDesc *num, FormatNode *n) NUM_cache_remove(last_NUMCacheEntry); ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), - errmsg("cannot use \"V\" and decimal point together"))); + errmsg("cannot use \"V\" and decimal point together"))); } num->flag |= NUM_F_MULTI; break; @@ -3072,7 +3072,7 @@ to_timestamp(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("inconsistent use of year %04d and \"BC\"", - tm.tm_year))); + tm.tm_year))); } if (tmfc.j) @@ -3106,7 +3106,7 @@ to_timestamp(PG_FUNCTION_ARGS) if (!tm.tm_year) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("cannot convert yday without year information"))); + errmsg("cannot convert yday without year information"))); y = ysum[isleap(tm.tm_year)]; @@ -3600,7 +3600,7 @@ NUM_numpart_from_char(NUMProc *Np, int id, int plen) * simple + - < > */ if (*Np->inout_p == '-' || (IS_BRACKET(Np->Num) && - *Np->inout_p == '<')) + *Np->inout_p == '<')) { *Np->number = '-'; /* set - */ @@ -3678,7 +3678,7 @@ NUM_numpart_from_char(NUMProc *Np, int id, int plen) (IS_ZERO((_n)->Num)==FALSE && \ (_n)->number == (_n)->number_p && \ *(_n)->number == '0' && \ - (_n)->Num->post != 0) + (_n)->Num->post != 0) /* ---------- * Add digit or sign to number-string @@ -3687,8 +3687,8 @@ NUM_numpart_from_char(NUMProc *Np, int id, int plen) static void NUM_numpart_to_char(NUMProc *Np, int id) { - int end; - + int end; + if (IS_ROMAN(Np->Num)) return; @@ -3710,13 +3710,13 @@ NUM_numpart_to_char(NUMProc *Np, int id) Np->num_in = FALSE; /* - * Write sign if real number will write to output - * Note: IS_PREDEC_SPACE() handle "9.9" --> " .1" + * Write sign if real number will write to output Note: + * IS_PREDEC_SPACE() handle "9.9" --> " .1" */ - if (Np->sign_wrote == FALSE && - (Np->num_curr >= Np->num_pre || (IS_ZERO(Np->Num) && Np->Num->zero_start == Np->num_curr )) && - (IS_PREDEC_SPACE(Np)==FALSE || (Np->last_relevant && *Np->last_relevant == '.'))) - { + if (Np->sign_wrote == FALSE && + (Np->num_curr >= Np->num_pre || (IS_ZERO(Np->Num) && Np->Num->zero_start == Np->num_curr)) && + (IS_PREDEC_SPACE(Np) == FALSE || (Np->last_relevant && *Np->last_relevant == '.'))) + { if (IS_LSIGN(Np->Num)) { if (Np->Num->lsign == NUM_LSIGN_PRE) @@ -3739,7 +3739,7 @@ NUM_numpart_to_char(NUMProc *Np, int id) { if (!IS_FILLMODE(Np->Num)) { - *Np->inout_p = ' '; /* Write + */ + *Np->inout_p = ' '; /* Write + */ ++Np->inout_p; } Np->sign_wrote = TRUE; @@ -3751,8 +3751,8 @@ NUM_numpart_to_char(NUMProc *Np, int id) Np->sign_wrote = TRUE; } } - - + + /* * digits / FM / Zero / Dec. point */ @@ -3796,10 +3796,11 @@ NUM_numpart_to_char(NUMProc *Np, int id) strcpy(Np->inout_p, Np->decimal); /* Write DEC/D */ Np->inout_p += strlen(Np->inout_p); } + /* * Ora 'n' -- FM9.9 --> 'n.' */ - else if (IS_FILLMODE(Np->Num) && + else if (IS_FILLMODE(Np->Num) && Np->last_relevant && *Np->last_relevant == '.') { @@ -3816,6 +3817,7 @@ NUM_numpart_to_char(NUMProc *Np, int id) if (Np->last_relevant && Np->number_p > Np->last_relevant && id != NUM_0) ; + /* * '0.1' -- 9.9 --> ' .1' */ @@ -3826,6 +3828,7 @@ NUM_numpart_to_char(NUMProc *Np, int id) *Np->inout_p = ' '; ++Np->inout_p; } + /* * '0' -- FM9.9 --> '0.' */ @@ -3846,11 +3849,11 @@ NUM_numpart_to_char(NUMProc *Np, int id) } end = Np->num_count + (Np->num_pre ? 1 : 0) + (IS_DECIMAL(Np->Num) ? 1 : 0); - + if (Np->last_relevant && Np->last_relevant == Np->number_p) end = Np->num_curr; - - if (Np->num_curr+1 == end) + + if (Np->num_curr + 1 == end) { if (Np->sign_wrote == TRUE && IS_BRACKET(Np->Num)) { @@ -3895,7 +3898,7 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, if (Np->Num->zero_start) --Np->Num->zero_start; - + /* * Roman correction */ @@ -3923,20 +3926,18 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, * Sign */ if (type == FROM_CHAR) - { Np->sign = FALSE; - } else { Np->sign = sign; - + /* MI/PL/SG - write sign itself and not in number */ if (IS_PLUS(Np->Num) || IS_MINUS(Np->Num)) { - if (IS_PLUS(Np->Num) && IS_MINUS(Np->Num)==FALSE) - Np->sign_wrote = FALSE; /* need sign */ + if (IS_PLUS(Np->Num) && IS_MINUS(Np->Num) == FALSE) + Np->sign_wrote = FALSE; /* need sign */ else - Np->sign_wrote = TRUE; /* needn't sign */ + Np->sign_wrote = TRUE; /* needn't sign */ } else { @@ -3950,10 +3951,10 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, else if (Np->sign != '+' && IS_PLUS(Np->Num)) Np->Num->flag &= ~NUM_F_PLUS; - if (Np->sign == '+' && IS_FILLMODE(Np->Num) && IS_LSIGN(Np->Num)==FALSE) - Np->sign_wrote = TRUE; /* needn't sign */ + if (Np->sign == '+' && IS_FILLMODE(Np->Num) && IS_LSIGN(Np->Num) == FALSE) + Np->sign_wrote = TRUE; /* needn't sign */ else - Np->sign_wrote = FALSE; /* need sign */ + Np->sign_wrote = FALSE; /* need sign */ if (Np->Num->lsign == NUM_LSIGN_PRE && Np->Num->pre == Np->Num->pre_lsign_num) Np->Num->lsign = NUM_LSIGN_POST; @@ -3973,12 +3974,12 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, { if (IS_DECIMAL(Np->Num)) Np->last_relevant = get_last_relevant_decnum( - Np->number + + Np->number + ((Np->Num->zero_end - Np->num_pre > 0) ? Np->Num->zero_end - Np->num_pre : 0)); } - if (Np->sign_wrote==FALSE && Np->num_pre == 0) + if (Np->sign_wrote == FALSE && Np->num_pre == 0) ++Np->num_count; } else @@ -4010,7 +4011,7 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, IS_MINUS(Np->Num) ? "Yes" : "No", IS_FILLMODE(Np->Num) ? "Yes" : "No", IS_ROMAN(Np->Num) ? "Yes" : "No" - ); + ); #endif /* diff --git a/src/backend/utils/adt/geo_ops.c b/src/backend/utils/adt/geo_ops.c index 9934d6a3e0..6567dafc95 100644 --- a/src/backend/utils/adt/geo_ops.c +++ b/src/backend/utils/adt/geo_ops.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/geo_ops.c,v 1.78 2003/07/27 04:53:05 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/geo_ops.c,v 1.79 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -140,7 +140,7 @@ single_decode(char *str, float8 *x, char **s) static int single_encode(float8 x, char *str) { - int ndig = DBL_DIG + extra_float_digits; + int ndig = DBL_DIG + extra_float_digits; if (ndig < 1) ndig = 1; @@ -196,7 +196,7 @@ pair_decode(char *str, float8 *x, float8 *y, char **s) static int pair_encode(float8 x, float8 y, char *str) { - int ndig = DBL_DIG + extra_float_digits; + int ndig = DBL_DIG + extra_float_digits; if (ndig < 1) ndig = 1; @@ -3363,7 +3363,7 @@ poly_in(PG_FUNCTION_ARGS) if ((npts = pair_count(str, ',')) <= 0) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for polygon: \"%s\"", str))); + errmsg("invalid input syntax for polygon: \"%s\"", str))); size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts; poly = (POLYGON *) palloc0(size); /* zero any holes */ @@ -3375,7 +3375,7 @@ poly_in(PG_FUNCTION_ARGS) || (*s != '\0')) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for polygon: \"%s\"", str))); + errmsg("invalid input syntax for polygon: \"%s\"", str))); make_bound_box(poly); @@ -3406,7 +3406,7 @@ Datum poly_recv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); - POLYGON *poly; + POLYGON *poly; int32 npts; int32 i; int size; @@ -3440,7 +3440,7 @@ poly_recv(PG_FUNCTION_ARGS) Datum poly_send(PG_FUNCTION_ARGS) { - POLYGON *poly = PG_GETARG_POLYGON_P(0); + POLYGON *poly = PG_GETARG_POLYGON_P(0); StringInfoData buf; int32 i; @@ -4246,7 +4246,7 @@ circle_in(PG_FUNCTION_ARGS) else ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for circle: \"%s\"", str))); + errmsg("invalid input syntax for circle: \"%s\"", str))); } if (*s != '\0') diff --git a/src/backend/utils/adt/inet_net_ntop.c b/src/backend/utils/adt/inet_net_ntop.c index 0287fec27f..7a38c53556 100644 --- a/src/backend/utils/adt/inet_net_ntop.c +++ b/src/backend/utils/adt/inet_net_ntop.c @@ -16,7 +16,7 @@ */ #if defined(LIBC_SCCS) && !defined(lint) -static const char rcsid[] = "$Id: inet_net_ntop.c,v 1.15 2003/06/25 01:08:13 momjian Exp $"; +static const char rcsid[] = "$Id: inet_net_ntop.c,v 1.16 2003/08/04 00:43:25 momjian Exp $"; #endif #include "postgres.h" @@ -40,13 +40,13 @@ static const char rcsid[] = "$Id: inet_net_ntop.c,v 1.15 2003/06/25 01:08:13 mom #endif static char *inet_net_ntop_ipv4(const u_char *src, int bits, - char *dst, size_t size); + char *dst, size_t size); static char *inet_cidr_ntop_ipv4(const u_char *src, int bits, - char *dst, size_t size); + char *dst, size_t size); static char *inet_net_ntop_ipv6(const u_char *src, int bits, - char *dst, size_t size); + char *dst, size_t size); static char *inet_cidr_ntop_ipv6(const u_char *src, int bits, - char *dst, size_t size); + char *dst, size_t size); /* * char * @@ -160,26 +160,30 @@ emsgsize: * 0x11110000 in its fourth octet. * author: * Vadim Kogan (UCB), June 2001 - * Original version (IPv4) by Paul Vixie (ISC), July 1996 + * Original version (IPv4) by Paul Vixie (ISC), July 1996 */ static char * inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) { - u_int m; - int b; - int p; - int zero_s, zero_l, tmp_zero_s, tmp_zero_l; - int i; - int is_ipv4 = 0; - int double_colon = 0; + u_int m; + int b; + int p; + int zero_s, + zero_l, + tmp_zero_s, + tmp_zero_l; + int i; + int is_ipv4 = 0; + int double_colon = 0; unsigned char inbuf[16]; - char outbuf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")]; - char *cp; - int words; - u_char *s; + char outbuf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")]; + char *cp; + int words; + u_char *s; - if (bits < 0 || bits > 128) { + if (bits < 0 || bits > 128) + { errno = EINVAL; return (NULL); } @@ -187,20 +191,24 @@ inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) cp = outbuf; double_colon = 0; - if (bits == 0) { + if (bits == 0) + { *cp++ = ':'; *cp++ = ':'; *cp = '\0'; double_colon = 1; - } else { - /* Copy src to private buffer. Zero host part. */ + } + else + { + /* Copy src to private buffer. Zero host part. */ p = (bits + 7) / 8; memcpy(inbuf, src, p); memset(inbuf + p, 0, 16 - p); b = bits % 8; - if (b != 0) { + if (b != 0) + { m = ~0 << (8 - b); - inbuf[p-1] &= m; + inbuf[p - 1] &= m; } s = inbuf; @@ -212,13 +220,18 @@ inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) /* Find the longest substring of zero's */ zero_s = zero_l = tmp_zero_s = tmp_zero_l = 0; - for (i = 0; i < (words * 2); i += 2) { - if ((s[i] | s[i+1]) == 0) { + for (i = 0; i < (words * 2); i += 2) + { + if ((s[i] | s[i + 1]) == 0) + { if (tmp_zero_l == 0) tmp_zero_s = i / 2; tmp_zero_l++; - } else { - if (tmp_zero_l && zero_l < tmp_zero_l) { + } + else + { + if (tmp_zero_l && zero_l < tmp_zero_l) + { zero_s = tmp_zero_s; zero_l = tmp_zero_l; tmp_zero_l = 0; @@ -226,23 +239,27 @@ inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) } } - if (tmp_zero_l && zero_l < tmp_zero_l) { + if (tmp_zero_l && zero_l < tmp_zero_l) + { zero_s = tmp_zero_s; zero_l = tmp_zero_l; } if (zero_l != words && zero_s == 0 && ((zero_l == 6) || - ((zero_l == 5 && s[10] == 0xff && s[11] == 0xff) || - ((zero_l == 7 && s[14] != 0 && s[15] != 1))))) + ((zero_l == 5 && s[10] == 0xff && s[11] == 0xff) || + ((zero_l == 7 && s[14] != 0 && s[15] != 1))))) is_ipv4 = 1; /* Format whole words. */ - for (p = 0; p < words; p++) { - if (zero_l != 0 && p >= zero_s && p < zero_s + zero_l) { + for (p = 0; p < words; p++) + { + if (zero_l != 0 && p >= zero_s && p < zero_s + zero_l) + { /* Time to skip some zeros */ if (p == zero_s) *cp++ = ':'; - if (p == words - 1) { + if (p == words - 1) + { *cp++ = ':'; double_colon = 1; } @@ -251,15 +268,19 @@ inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) continue; } - if (is_ipv4 && p > 5 ) { + if (is_ipv4 && p > 5) + { *cp++ = (p == 6) ? ':' : '.'; cp += SPRINTF((cp, "%u", *s++)); /* we can potentially drop the last octet */ - if (p != 7 || bits > 120) { + if (p != 7 || bits > 120) + { *cp++ = '.'; cp += SPRINTF((cp, "%u", *s++)); } - } else { + } + else + { if (cp != outbuf) *cp++ = ':'; cp += SPRINTF((cp, "%x", *s * 256 + s[1])); @@ -268,7 +289,8 @@ inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) } } - if (!double_colon) { + if (!double_colon) + { if (bits < 128 - 32) cp += SPRINTF((cp, "::")); else if (bits < 128 - 16) @@ -281,7 +303,7 @@ inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) if (strlen(outbuf) + 1 > size) goto emsgsize; strcpy(dst, outbuf); - + return (dst); emsgsize: @@ -373,21 +395,24 @@ emsgsize: } static int -decoct(const u_char *src, int bytes, char *dst, size_t size) { - char *odst = dst; - char *t; - int b; +decoct(const u_char *src, int bytes, char *dst, size_t size) +{ + char *odst = dst; + char *t; + int b; - for (b = 1; b <= bytes; b++) { + for (b = 1; b <= bytes; b++) + { if (size < sizeof "255.") return (0); t = dst; dst += SPRINTF((dst, "%u", *src++)); - if (b != bytes) { + if (b != bytes) + { *dst++ = '.'; *dst = '\0'; } - size -= (size_t)(dst - t); + size -= (size_t) (dst - t); } return (dst - odst); } @@ -402,42 +427,52 @@ inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) * Keep this in mind if you think this function should have been coded * to use pointer overlays. All the world's not a VAX. */ - char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255/128"]; - char *tp; - struct { int base, len; } best, cur; - u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; - int i; + char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255/128"]; + char *tp; + struct + { + int base, + len; + } best, cur; + u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; + int i; - if ((bits < -1) || (bits > 128)) { + if ((bits < -1) || (bits > 128)) + { errno = EINVAL; return (NULL); } /* - * Preprocess: - * Copy the input (bytewise) array into a wordwise array. - * Find the longest run of 0x00's in src[] for :: shorthanding. + * Preprocess: Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. */ memset(words, '\0', sizeof words); for (i = 0; i < NS_IN6ADDRSZ; i++) words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); best.base = -1; cur.base = -1; - for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { - if (words[i] == 0) { + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) + { + if (words[i] == 0) + { if (cur.base == -1) cur.base = i, cur.len = 1; else cur.len++; - } else { - if (cur.base != -1) { + } + else + { + if (cur.base != -1) + { if (best.base == -1 || cur.len > best.len) best = cur; cur.base = -1; } } } - if (cur.base != -1) { + if (cur.base != -1) + { if (best.base == -1 || cur.len > best.len) best = cur; } @@ -448,10 +483,12 @@ inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) * Format the result. */ tp = tmp; - for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) + { /* Are we inside the best run of 0x00's? */ if (best.base != -1 && i >= best.base && - i < (best.base + best.len)) { + i < (best.base + best.len)) + { if (i == best.base) *tp++ = ':'; continue; @@ -461,12 +498,14 @@ inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) *tp++ = ':'; /* Is this address an encapsulated IPv4? */ if (i == 6 && best.base == 0 && (best.len == 6 || - (best.len == 7 && words[7] != 0x0001) || - (best.len == 5 && words[5] == 0xffff))) { - int n; + (best.len == 7 && words[7] != 0x0001) || + (best.len == 5 && words[5] == 0xffff))) + { + int n; - n = decoct(src+12, 4, tp, sizeof tmp - (tp - tmp)); - if (n == 0) { + n = decoct(src + 12, 4, tp, sizeof tmp - (tp - tmp)); + if (n == 0) + { errno = EMSGSIZE; return (NULL); } @@ -477,8 +516,8 @@ inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) } /* Was it a trailing run of 0x00's? */ - if (best.base != -1 && (best.base + best.len) == - (NS_IN6ADDRSZ / NS_INT16SZ)) + if (best.base != -1 && (best.base + best.len) == + (NS_IN6ADDRSZ / NS_INT16SZ)) *tp++ = ':'; *tp = '\0'; @@ -488,7 +527,8 @@ inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) /* * Check for overflow, copy, and we're done. */ - if ((size_t)(tp - tmp) > size) { + if ((size_t) (tp - tmp) > size) + { errno = EMSGSIZE; return (NULL); } diff --git a/src/backend/utils/adt/inet_net_pton.c b/src/backend/utils/adt/inet_net_pton.c index 4c7ca9d618..b1b4bb6987 100644 --- a/src/backend/utils/adt/inet_net_pton.c +++ b/src/backend/utils/adt/inet_net_pton.c @@ -16,7 +16,7 @@ */ #if defined(LIBC_SCCS) && !defined(lint) -static const char rcsid[] = "$Id: inet_net_pton.c,v 1.15 2003/06/24 22:21:22 momjian Exp $"; +static const char rcsid[] = "$Id: inet_net_pton.c,v 1.16 2003/08/04 00:43:25 momjian Exp $"; #endif #include "postgres.h" @@ -35,8 +35,8 @@ static const char rcsid[] = "$Id: inet_net_pton.c,v 1.15 2003/06/24 22:21:22 mom static int inet_net_pton_ipv4(const char *src, u_char *dst); static int inet_cidr_pton_ipv4(const char *src, u_char *dst, size_t size); -static int inet_net_pton_ipv6(const char *src, u_char *dst); -static int inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size); +static int inet_net_pton_ipv6(const char *src, u_char *dst); +static int inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size); /* * static int @@ -339,24 +339,27 @@ emsgsize: } static int -getbits(const char *src, int *bitsp) { +getbits(const char *src, int *bitsp) +{ static const char digits[] = "0123456789"; - int n; - int val; - char ch; + int n; + int val; + char ch; val = 0; n = 0; - while ((ch = *src++) != '\0') { + while ((ch = *src++) != '\0') + { const char *pch; pch = strchr(digits, ch); - if (pch != NULL) { + if (pch != NULL) + { if (n++ != 0 && val == 0) /* no leading zeros */ return (0); val *= 10; val += (pch - digits); - if (val > 128) /* range */ + if (val > 128) /* range */ return (0); continue; } @@ -369,30 +372,34 @@ getbits(const char *src, int *bitsp) { } static int -getv4(const char *src, u_char *dst, int *bitsp) { +getv4(const char *src, u_char *dst, int *bitsp) +{ static const char digits[] = "0123456789"; - u_char *odst = dst; - int n; - u_int val; - char ch; + u_char *odst = dst; + int n; + u_int val; + char ch; val = 0; n = 0; - while ((ch = *src++) != '\0') { + while ((ch = *src++) != '\0') + { const char *pch; pch = strchr(digits, ch); - if (pch != NULL) { + if (pch != NULL) + { if (n++ != 0 && val == 0) /* no leading zeros */ return (0); val *= 10; val += (pch - digits); - if (val > 255) /* range */ + if (val > 255) /* range */ return (0); continue; } - if (ch == '.' || ch == '/') { - if (dst - odst > 3) /* too many octets? */ + if (ch == '.' || ch == '/') + { + if (dst - odst > 3) /* too many octets? */ return (0); *dst++ = val; if (ch == '/') @@ -405,7 +412,7 @@ getv4(const char *src, u_char *dst, int *bitsp) { } if (n == 0) return (0); - if (dst - odst > 3) /* too many octets? */ + if (dst - odst > 3) /* too many octets? */ return (0); *dst++ = val; return (1); @@ -422,15 +429,21 @@ inet_net_pton_ipv6(const char *src, u_char *dst) #define NS_INADDRSZ 4 static int -inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size) { +inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size) +{ static const char xdigits_l[] = "0123456789abcdef", - xdigits_u[] = "0123456789ABCDEF"; - u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; - const char *xdigits, *curtok; - int ch, saw_xdigit; - u_int val; - int digits; - int bits; + xdigits_u[] = "0123456789ABCDEF"; + u_char tmp[NS_IN6ADDRSZ], + *tp, + *endp, + *colonp; + const char *xdigits, + *curtok; + int ch, + saw_xdigit; + u_int val; + int digits; + int bits; if (size < NS_IN6ADDRSZ) goto emsgsize; @@ -447,12 +460,14 @@ inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size) { val = 0; digits = 0; bits = -1; - while ((ch = *src++) != '\0') { + while ((ch = *src++) != '\0') + { const char *pch; if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) pch = strchr((xdigits = xdigits_u), ch); - if (pch != NULL) { + if (pch != NULL) + { val <<= 4; val |= (pch - xdigits); if (++digits > 4) @@ -460,14 +475,17 @@ inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size) { saw_xdigit = 1; continue; } - if (ch == ':') { + if (ch == ':') + { curtok = src; - if (!saw_xdigit) { + if (!saw_xdigit) + { if (colonp) goto enoent; colonp = tp; continue; - } else if (*src == '\0') + } + else if (*src == '\0') goto enoent; if (tp + NS_INT16SZ > endp) return (0); @@ -479,16 +497,18 @@ inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size) { continue; } if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && - getv4(curtok, tp, &bits) > 0) { + getv4(curtok, tp, &bits) > 0) + { tp += NS_INADDRSZ; saw_xdigit = 0; - break; /* '\0' was seen by inet_pton4(). */ + break; /* '\0' was seen by inet_pton4(). */ } if (ch == '/' && getbits(src, &bits) > 0) break; goto enoent; } - if (saw_xdigit) { + if (saw_xdigit) + { if (tp + NS_INT16SZ > endp) goto enoent; *tp++ = (u_char) (val >> 8) & 0xff; @@ -497,20 +517,22 @@ inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size) { if (bits == -1) bits = 128; - endp = tmp + 16; + endp = tmp + 16; - if (colonp != NULL) { + if (colonp != NULL) + { /* - * Since some memmove()'s erroneously fail to handle - * overlapping regions, we'll do the shift by hand. + * Since some memmove()'s erroneously fail to handle overlapping + * regions, we'll do the shift by hand. */ - const int n = tp - colonp; - int i; + const int n = tp - colonp; + int i; if (tp == endp) goto enoent; - for (i = 1; i <= n; i++) { - endp[- i] = colonp[n - i]; + for (i = 1; i <= n; i++) + { + endp[-i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; @@ -525,11 +547,11 @@ inet_cidr_pton_ipv6(const char *src, u_char *dst, size_t size) { return (bits); - enoent: +enoent: errno = ENOENT; return (-1); - emsgsize: +emsgsize: errno = EMSGSIZE; return (-1); } diff --git a/src/backend/utils/adt/int.c b/src/backend/utils/adt/int.c index 1c25df0956..c7e31ebcad 100644 --- a/src/backend/utils/adt/int.c +++ b/src/backend/utils/adt/int.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/int.c,v 1.55 2003/07/27 04:53:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/int.c,v 1.56 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -173,9 +173,7 @@ int2vectorrecv(PG_FUNCTION_ARGS) int slot; for (slot = 0; slot < INDEX_MAX_KEYS; slot++) - { result[slot] = (int16) pq_getmsgint(buf, sizeof(int16)); - } PG_RETURN_POINTER(result); } @@ -191,9 +189,7 @@ int2vectorsend(PG_FUNCTION_ARGS) pq_begintypsend(&buf); for (slot = 0; slot < INDEX_MAX_KEYS; slot++) - { pq_sendint(&buf, int2Array[slot], sizeof(int16)); - } PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); } diff --git a/src/backend/utils/adt/int8.c b/src/backend/utils/adt/int8.c index 123c5e7225..3be22ba527 100644 --- a/src/backend/utils/adt/int8.c +++ b/src/backend/utils/adt/int8.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/int8.c,v 1.45 2003/07/27 04:53:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/int8.c,v 1.46 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -85,7 +85,7 @@ scanint8(const char *str, bool errorOK, int64 *result) else ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for int8: \"%s\"", str))); + errmsg("invalid input syntax for int8: \"%s\"", str))); } /* process digits */ @@ -113,7 +113,7 @@ scanint8(const char *str, bool errorOK, int64 *result) else ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for int8: \"%s\"", str))); + errmsg("invalid input syntax for int8: \"%s\"", str))); } *result = (sign < 0) ? -tmp : tmp; diff --git a/src/backend/utils/adt/like.c b/src/backend/utils/adt/like.c index 0f832aa6e1..4cffc0d018 100644 --- a/src/backend/utils/adt/like.c +++ b/src/backend/utils/adt/like.c @@ -11,7 +11,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/like.c,v 1.54 2003/07/27 04:53:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/like.c,v 1.55 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -451,7 +451,7 @@ like_escape_bytea(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE), errmsg("invalid escape string"), - errhint("Escape string must be empty or one character."))); + errhint("Escape string must be empty or one character."))); e = VARDATA(esc); diff --git a/src/backend/utils/adt/like_match.c b/src/backend/utils/adt/like_match.c index 9530873ae3..ebe2ce75f3 100644 --- a/src/backend/utils/adt/like_match.c +++ b/src/backend/utils/adt/like_match.c @@ -19,7 +19,7 @@ * Copyright (c) 1996-2002, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/like_match.c,v 1.5 2003/07/27 04:53:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/like_match.c,v 1.6 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -289,7 +289,7 @@ do_like_escape(text *pat, text *esc) ereport(ERROR, (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE), errmsg("invalid escape string"), - errhint("Escape string must be empty or one character."))); + errhint("Escape string must be empty or one character."))); e = VARDATA(esc); diff --git a/src/backend/utils/adt/mac.c b/src/backend/utils/adt/mac.c index 36ae41f9c7..4bef89a71b 100644 --- a/src/backend/utils/adt/mac.c +++ b/src/backend/utils/adt/mac.c @@ -1,7 +1,7 @@ /* * PostgreSQL type definitions for MAC addresses. * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/mac.c,v 1.29 2003/07/27 04:53:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/mac.c,v 1.30 2003/08/04 00:43:25 momjian Exp $ */ #include "postgres.h" @@ -62,7 +62,7 @@ macaddr_in(PG_FUNCTION_ARGS) if (count != 6) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for macaddr: \"%s\"", str))); + errmsg("invalid input syntax for macaddr: \"%s\"", str))); if ((a < 0) || (a > 255) || (b < 0) || (b > 255) || (c < 0) || (c > 255) || (d < 0) || (d > 255) || @@ -110,7 +110,7 @@ Datum macaddr_recv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); - macaddr *addr; + macaddr *addr; addr = (macaddr *) palloc(sizeof(macaddr)); @@ -130,7 +130,7 @@ macaddr_recv(PG_FUNCTION_ARGS) Datum macaddr_send(PG_FUNCTION_ARGS) { - macaddr *addr = PG_GETARG_MACADDR_P(0); + macaddr *addr = PG_GETARG_MACADDR_P(0); StringInfoData buf; pq_begintypsend(&buf); diff --git a/src/backend/utils/adt/nabstime.c b/src/backend/utils/adt/nabstime.c index 4f1234e35a..0e84ad652f 100644 --- a/src/backend/utils/adt/nabstime.c +++ b/src/backend/utils/adt/nabstime.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/nabstime.c,v 1.111 2003/07/28 00:09:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/nabstime.c,v 1.112 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -83,7 +83,7 @@ static int istinterval(char *i_string, AbsoluteTime *i_end); -/* +/* * GetCurrentAbsoluteTime() * * Get the current system time (relative to Unix epoch). @@ -152,7 +152,7 @@ GetCurrentDateTime(struct tm * tm) abstime2tm(GetCurrentTransactionStartTime(), &tz, tm, NULL); } -/* +/* * GetCurrentTimeUsec() * * Get the transaction start time ("now()") broken down as a struct tm, @@ -373,13 +373,13 @@ abstimein(PG_FUNCTION_ARGS) if (strlen(str) >= sizeof(lowstr)) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for abstime: \"%s\"", str))); + errmsg("invalid input syntax for abstime: \"%s\"", str))); if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0) || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0)) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for abstime: \"%s\"", str))); + errmsg("invalid input syntax for abstime: \"%s\"", str))); switch (dtype) { @@ -654,7 +654,7 @@ abstime_timestamp(PG_FUNCTION_ARGS) case INVALID_ABSTIME: ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot convert \"invalid\" abstime to timestamp"))); + errmsg("cannot convert \"invalid\" abstime to timestamp"))); TIMESTAMP_NOBEGIN(result); break; @@ -727,7 +727,7 @@ abstime_timestamptz(PG_FUNCTION_ARGS) case INVALID_ABSTIME: ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot convert \"invalid\" abstime to timestamp"))); + errmsg("cannot convert \"invalid\" abstime to timestamp"))); TIMESTAMP_NOBEGIN(result); break; @@ -776,13 +776,13 @@ reltimein(PG_FUNCTION_ARGS) if (strlen(str) >= sizeof(lowstr)) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for reltime: \"%s\"", str))); + errmsg("invalid input syntax for reltime: \"%s\"", str))); if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0) || (DecodeInterval(field, ftype, nf, &dtype, tm, &fsec) != 0)) ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), - errmsg("invalid input syntax for reltime: \"%s\"", str))); + errmsg("invalid input syntax for reltime: \"%s\"", str))); switch (dtype) { @@ -849,7 +849,7 @@ reltimesend(PG_FUNCTION_ARGS) static void reltime2tm(RelativeTime time, struct tm * tm) { - double dtime = time; + double dtime = time; FMODULO(dtime, tm->tm_year, 31557600); FMODULO(dtime, tm->tm_mon, 2592000); @@ -1032,7 +1032,7 @@ reltime_interval(PG_FUNCTION_ARGS) case INVALID_RELTIME: ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot convert \"invalid\" reltime to interval"))); + errmsg("cannot convert \"invalid\" reltime to interval"))); result->time = 0; result->month = 0; break; diff --git a/src/backend/utils/adt/name.c b/src/backend/utils/adt/name.c index 47af778f3d..3c6c4049fc 100644 --- a/src/backend/utils/adt/name.c +++ b/src/backend/utils/adt/name.c @@ -14,7 +14,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/name.c,v 1.47 2003/07/27 04:53:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/name.c,v 1.48 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -89,7 +89,7 @@ namerecv(PG_FUNCTION_ARGS) (errcode(ERRCODE_NAME_TOO_LONG), errmsg("identifier too long"), errdetail("Identifier must be less than %d characters.", - NAMEDATALEN))); + NAMEDATALEN))); result = (NameData *) palloc0(NAMEDATALEN); memcpy(result, str, nbytes); pfree(str); diff --git a/src/backend/utils/adt/network.c b/src/backend/utils/adt/network.c index a9683116e9..e3e7d185df 100644 --- a/src/backend/utils/adt/network.c +++ b/src/backend/utils/adt/network.c @@ -1,7 +1,7 @@ /* * PostgreSQL type definitions for the INET and CIDR types. * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/network.c,v 1.44 2003/08/01 23:22:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/network.c,v 1.45 2003/08/04 00:43:25 momjian Exp $ * * Jon Postel RIP 16 Oct 1998 */ @@ -21,9 +21,9 @@ static Datum text_network(text *src, int type); static int32 network_cmp_internal(inet *a1, inet *a2); -static int bitncmp(void *l, void *r, int n); +static int bitncmp(void *l, void *r, int n); static bool addressOK(unsigned char *a, int bits, int family); -static int ip_addrsize(inet *inetptr); +static int ip_addrsize(inet *inetptr); /* * Access macros. @@ -50,13 +50,14 @@ static int ip_addrsize(inet *inetptr); static int ip_addrsize(inet *inetptr) { - switch (ip_family(inetptr)) { - case PGSQL_AF_INET: - return 4; - case PGSQL_AF_INET6: - return 16; - default: - return -1; + switch (ip_family(inetptr)) + { + case PGSQL_AF_INET: + return 4; + case PGSQL_AF_INET6: + return 16; + default: + return -1; } } @@ -64,34 +65,34 @@ ip_addrsize(inet *inetptr) static inet * network_in(char *src, int type) { - int bits; + int bits; inet *dst; dst = (inet *) palloc0(VARHDRSZ + sizeof(inet_struct)); /* - * First, check to see if this is an IPv6 or IPv4 address. IPv6 - * addresses will have a : somewhere in them (several, in fact) so - * if there is one present, assume it's V6, otherwise assume it's V4. + * First, check to see if this is an IPv6 or IPv4 address. IPv6 + * addresses will have a : somewhere in them (several, in fact) so if + * there is one present, assume it's V6, otherwise assume it's V4. */ if (strchr(src, ':') != NULL) ip_family(dst) = PGSQL_AF_INET6; else ip_family(dst) = PGSQL_AF_INET; - + bits = inet_net_pton(ip_family(dst), src, ip_addr(dst), - type ? ip_addrsize(dst) : -1); + type ? ip_addrsize(dst) : -1); if ((bits < 0) || (bits > ip_maxbits(dst))) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - /* translator: first %s is inet or cidr */ + /* translator: first %s is inet or cidr */ errmsg("invalid input syntax for %s: \"%s\"", - type ? "cidr" : "inet", src))); + type ? "cidr" : "inet", src))); /* - * Error check: CIDR values must not have any bits set beyond - * the masklen. + * Error check: CIDR values must not have any bits set beyond the + * masklen. */ if (type) { @@ -141,7 +142,7 @@ inet_out(PG_FUNCTION_ARGS) int len; dst = inet_net_ntop(ip_family(src), ip_addr(src), ip_bits(src), - tmp, sizeof(tmp)); + tmp, sizeof(tmp)); if (dst == NULL) ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), @@ -208,10 +209,10 @@ inet_recv(PG_FUNCTION_ARGS) (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), errmsg("invalid length in external inet"))); VARATT_SIZEP(addr) = VARHDRSZ - + ((char *)ip_addr(addr) - (char *) VARDATA(addr)) + + ((char *) ip_addr(addr) - (char *) VARDATA(addr)) + ip_addrsize(addr); - addrptr = (char *)ip_addr(addr); + addrptr = (char *) ip_addr(addr); for (i = 0; i < nb; i++) addrptr[i] = pq_getmsgbyte(buf); @@ -258,7 +259,7 @@ inet_send(PG_FUNCTION_ARGS) if (nb < 0) nb = 0; pq_sendbyte(&buf, nb); - addrptr = (char *)ip_addr(addr); + addrptr = (char *) ip_addr(addr); for (i = 0; i < nb; i++) pq_sendbyte(&buf, addrptr[i]); PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); @@ -305,8 +306,8 @@ inet_set_masklen(PG_FUNCTION_ARGS) int bits = PG_GETARG_INT32(1); inet *dst; - if ( bits == -1 ) - bits = ip_maxbits(src); + if (bits == -1) + bits = ip_maxbits(src); if ((bits < 0) || (bits > ip_maxbits(src))) ereport(ERROR, @@ -341,7 +342,7 @@ network_cmp_internal(inet *a1, inet *a2) int order; order = bitncmp(ip_addr(a1), ip_addr(a2), - Min(ip_bits(a1), ip_bits(a2))); + Min(ip_bits(a1), ip_bits(a2))); if (order != 0) return order; order = ((int) ip_bits(a1)) - ((int) ip_bits(a2)); @@ -431,7 +432,7 @@ network_sub(PG_FUNCTION_ARGS) if (ip_family(a1) == ip_family(a2)) { PG_RETURN_BOOL(ip_bits(a1) > ip_bits(a2) - && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0); + && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0); } PG_RETURN_BOOL(false); @@ -446,7 +447,7 @@ network_subeq(PG_FUNCTION_ARGS) if (ip_family(a1) == ip_family(a2)) { PG_RETURN_BOOL(ip_bits(a1) >= ip_bits(a2) - && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0); + && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0); } PG_RETURN_BOOL(false); @@ -461,7 +462,7 @@ network_sup(PG_FUNCTION_ARGS) if (ip_family(a1) == ip_family(a2)) { PG_RETURN_BOOL(ip_bits(a1) < ip_bits(a2) - && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0); + && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0); } PG_RETURN_BOOL(false); @@ -476,7 +477,7 @@ network_supeq(PG_FUNCTION_ARGS) if (ip_family(a1) == ip_family(a2)) { PG_RETURN_BOOL(ip_bits(a1) <= ip_bits(a2) - && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0); + && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0); } PG_RETURN_BOOL(false); @@ -496,7 +497,7 @@ network_host(PG_FUNCTION_ARGS) /* force display of max bits, regardless of masklen... */ if (inet_net_ntop(ip_family(ip), ip_addr(ip), ip_maxbits(ip), - tmp, sizeof(tmp)) == NULL) + tmp, sizeof(tmp)) == NULL) ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), errmsg("could not format inet value: %m"))); @@ -522,7 +523,7 @@ network_show(PG_FUNCTION_ARGS) char tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")]; if (inet_net_ntop(ip_family(ip), ip_addr(ip), ip_maxbits(ip), - tmp, sizeof(tmp)) == NULL) + tmp, sizeof(tmp)) == NULL) ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), errmsg("could not format inet value: %m"))); @@ -553,10 +554,10 @@ network_abbrev(PG_FUNCTION_ARGS) if (ip_type(ip)) dst = inet_cidr_ntop(ip_family(ip), ip_addr(ip), - ip_bits(ip), tmp, sizeof(tmp)); + ip_bits(ip), tmp, sizeof(tmp)); else dst = inet_net_ntop(ip_family(ip), ip_addr(ip), - ip_bits(ip), tmp, sizeof(tmp)); + ip_bits(ip), tmp, sizeof(tmp)); if (dst == NULL) ereport(ERROR, @@ -582,18 +583,19 @@ network_masklen(PG_FUNCTION_ARGS) Datum network_family(PG_FUNCTION_ARGS) { - inet *ip = PG_GETARG_INET_P(0); + inet *ip = PG_GETARG_INET_P(0); - switch (ip_family(ip)) { - case PGSQL_AF_INET: - PG_RETURN_INT32(4); - break; - case PGSQL_AF_INET6: - PG_RETURN_INT32(6); - break; - default: - PG_RETURN_INT32(0); - break; + switch (ip_family(ip)) + { + case PGSQL_AF_INET: + PG_RETURN_INT32(4); + break; + case PGSQL_AF_INET6: + PG_RETURN_INT32(6); + break; + default: + PG_RETURN_INT32(0); + break; } } @@ -602,38 +604,42 @@ network_broadcast(PG_FUNCTION_ARGS) { inet *ip = PG_GETARG_INET_P(0); inet *dst; - int byte; - int bits; - int maxbytes; + int byte; + int bits; + int maxbytes; unsigned char mask; - unsigned char *a, *b; + unsigned char *a, + *b; /* make sure any unused bits are zeroed */ dst = (inet *) palloc0(VARHDRSZ + sizeof(inet_struct)); - if (ip_family(ip) == PGSQL_AF_INET) { + if (ip_family(ip) == PGSQL_AF_INET) maxbytes = 4; - } else { + else maxbytes = 16; - } bits = ip_bits(ip); a = ip_addr(ip); b = ip_addr(dst); - for (byte = 0 ; byte < maxbytes ; byte++) { - if (bits >= 8) { + for (byte = 0; byte < maxbytes; byte++) + { + if (bits >= 8) + { mask = 0x00; bits -= 8; - } else if (bits == 0) { + } + else if (bits == 0) mask = 0xff; - } else { + else + { mask = 0xff >> bits; bits = 0; } b[byte] = a[byte] | mask; - } + } ip_family(dst) = ip_family(ip); ip_bits(dst) = ip_bits(ip); @@ -650,38 +656,42 @@ network_network(PG_FUNCTION_ARGS) { inet *ip = PG_GETARG_INET_P(0); inet *dst; - int byte; - int bits; - int maxbytes; + int byte; + int bits; + int maxbytes; unsigned char mask; - unsigned char *a, *b; + unsigned char *a, + *b; /* make sure any unused bits are zeroed */ dst = (inet *) palloc0(VARHDRSZ + sizeof(inet_struct)); - if (ip_family(ip) == PGSQL_AF_INET) { + if (ip_family(ip) == PGSQL_AF_INET) maxbytes = 4; - } else { + else maxbytes = 16; - } bits = ip_bits(ip); a = ip_addr(ip); b = ip_addr(dst); byte = 0; - while (bits) { - if (bits >= 8) { + while (bits) + { + if (bits >= 8) + { mask = 0xff; bits -= 8; - } else { + } + else + { mask = 0xff << (8 - bits); bits = 0; } b[byte] = a[byte] & mask; byte++; - } + } ip_family(dst) = ip_family(ip); ip_bits(dst) = ip_bits(ip); @@ -698,43 +708,46 @@ network_netmask(PG_FUNCTION_ARGS) { inet *ip = PG_GETARG_INET_P(0); inet *dst; - int byte; - int bits; - int maxbytes; + int byte; + int bits; + int maxbytes; unsigned char mask; unsigned char *b; /* make sure any unused bits are zeroed */ dst = (inet *) palloc0(VARHDRSZ + sizeof(inet_struct)); - if (ip_family(ip) == PGSQL_AF_INET) { + if (ip_family(ip) == PGSQL_AF_INET) maxbytes = 4; - } else { + else maxbytes = 16; - } bits = ip_bits(ip); b = ip_addr(dst); byte = 0; - while (bits) { - if (bits >= 8) { + while (bits) + { + if (bits >= 8) + { mask = 0xff; bits -= 8; - } else { + } + else + { mask = 0xff << (8 - bits); bits = 0; } b[byte] = mask; byte++; - } + } ip_family(dst) = ip_family(ip); ip_bits(dst) = ip_bits(ip); ip_type(dst) = 0; VARATT_SIZEP(dst) = VARHDRSZ - + ((char *)ip_addr(dst) - (char *) VARDATA(dst)) + + ((char *) ip_addr(dst) - (char *) VARDATA(dst)) + ip_addrsize(dst); PG_RETURN_INET_P(dst); @@ -745,43 +758,46 @@ network_hostmask(PG_FUNCTION_ARGS) { inet *ip = PG_GETARG_INET_P(0); inet *dst; - int byte; - int bits; - int maxbytes; + int byte; + int bits; + int maxbytes; unsigned char mask; unsigned char *b; /* make sure any unused bits are zeroed */ dst = (inet *) palloc0(VARHDRSZ + sizeof(inet_struct)); - if (ip_family(ip) == PGSQL_AF_INET) { + if (ip_family(ip) == PGSQL_AF_INET) maxbytes = 4; - } else { + else maxbytes = 16; - } bits = ip_maxbits(ip) - ip_bits(ip); b = ip_addr(dst); byte = maxbytes - 1; - while (bits) { - if (bits >= 8) { + while (bits) + { + if (bits >= 8) + { mask = 0xff; bits -= 8; - } else { + } + else + { mask = 0xff >> (8 - bits); bits = 0; } b[byte] = mask; byte--; - } + } ip_family(dst) = ip_family(ip); ip_bits(dst) = ip_bits(ip); ip_type(dst) = 0; VARATT_SIZEP(dst) = VARHDRSZ - + ((char *)ip_addr(dst) - (char *) VARDATA(dst)) + + ((char *) ip_addr(dst) - (char *) VARDATA(dst)) + ip_addrsize(dst); PG_RETURN_INET_P(dst); @@ -806,13 +822,12 @@ convert_network_to_scalar(Datum value, Oid typid) case CIDROID: { inet *ip = DatumGetInetP(value); - int len; - double res; - int i; + int len; + double res; + int i; /* - * Note that we don't use the full address - * here. + * Note that we don't use the full address here. */ if (ip_family(ip) == PGSQL_AF_INET) len = 4; @@ -820,7 +835,8 @@ convert_network_to_scalar(Datum value, Oid typid) len = 5; res = ip_family(ip); - for (i = 0 ; i < len ; i++) { + for (i = 0; i < len; i++) + { res *= 256; res += ip_addr(ip)[i]; } @@ -851,30 +867,34 @@ convert_network_to_scalar(Datum value, Oid typid) /* * int * bitncmp(l, r, n) - * compare bit masks l and r, for n bits. + * compare bit masks l and r, for n bits. * return: - * -1, 1, or 0 in the libc tradition. + * -1, 1, or 0 in the libc tradition. * note: - * network byte order assumed. this means 192.5.5.240/28 has - * 0x11110000 in its fourth octet. + * network byte order assumed. this means 192.5.5.240/28 has + * 0x11110000 in its fourth octet. * author: - * Paul Vixie (ISC), June 1996 + * Paul Vixie (ISC), June 1996 */ static int bitncmp(void *l, void *r, int n) { - u_int lb, rb; - int x, b; + u_int lb, + rb; + int x, + b; b = n / 8; x = memcmp(l, r, b); if (x) return (x); - lb = ((const u_char *)l)[b]; - rb = ((const u_char *)r)[b]; - for (b = n % 8; b > 0; b--) { - if ((lb & 0x80) != (rb & 0x80)) { + lb = ((const u_char *) l)[b]; + rb = ((const u_char *) r)[b]; + for (b = n % 8; b > 0; b--) + { + if ((lb & 0x80) != (rb & 0x80)) + { if (lb & 0x80) return (1); return (-1); @@ -888,16 +908,19 @@ bitncmp(void *l, void *r, int n) static bool addressOK(unsigned char *a, int bits, int family) { - int byte; - int nbits; - int maxbits; - int maxbytes; + int byte; + int nbits; + int maxbits; + int maxbytes; unsigned char mask; - if (family == PGSQL_AF_INET) { + if (family == PGSQL_AF_INET) + { maxbits = 32; maxbytes = 4; - } else { + } + else + { maxbits = 128; maxbytes = 16; } @@ -912,7 +935,8 @@ addressOK(unsigned char *a, int bits, int family) if (bits != 0) mask >>= nbits; - while (byte < maxbytes) { + while (byte < maxbytes) + { if ((a[byte] & mask) != 0) return false; mask = 0xff; @@ -948,5 +972,5 @@ network_scan_last(Datum in) { return DirectFunctionCall2(inet_set_masklen, DirectFunctionCall1(network_broadcast, in), - Int32GetDatum(-1)); + Int32GetDatum(-1)); } diff --git a/src/backend/utils/adt/not_in.c b/src/backend/utils/adt/not_in.c index c3f0aee5cb..5deeea2f1d 100644 --- a/src/backend/utils/adt/not_in.c +++ b/src/backend/utils/adt/not_in.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/not_in.c,v 1.33 2003/07/27 04:53:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/not_in.c,v 1.34 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -62,7 +62,7 @@ int4notin(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("invalid name syntax"), - errhint("Must provide \"relationname.attributename\"."))); + errhint("Must provide \"relationname.attributename\"."))); attribute = strVal(nth(nnames - 1, names)); names = ltruncate(nnames - 1, names); relrv = makeRangeVarFromNameList(names); diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c index 4f5029a26c..5b0fe29110 100644 --- a/src/backend/utils/adt/numeric.c +++ b/src/backend/utils/adt/numeric.c @@ -14,7 +14,7 @@ * Copyright (c) 1998-2003, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/numeric.c,v 1.64 2003/07/30 19:48:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/numeric.c,v 1.65 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -57,7 +57,7 @@ * Numeric values are represented in a base-NBASE floating point format. * Each "digit" ranges from 0 to NBASE-1. The type NumericDigit is signed * and wide enough to store a digit. We assume that NBASE*NBASE can fit in - * an int. Although the purely calculational routines could handle any even + * an int. Although the purely calculational routines could handle any even * NBASE that's less than sqrt(INT_MAX), in practice we are only interested * in NBASE a power of ten, so that I/O conversions and decimal rounding * are easy. Also, it's actually more efficient if NBASE is rather less than @@ -101,7 +101,7 @@ typedef int16 NumericDigit; * The value represented by a NumericVar is determined by the sign, weight, * ndigits, and digits[] array. * Note: the first digit of a NumericVar's value is assumed to be multiplied - * by NBASE ** weight. Another way to say it is that there are weight+1 + * by NBASE ** weight. Another way to say it is that there are weight+1 * digits before the decimal point. It is possible to have weight < 0. * * buf points at the physical start of the palloc'd digit buffer for the @@ -166,8 +166,10 @@ static NumericVar const_two = #if DEC_DIGITS == 4 static NumericDigit const_zero_point_five_data[1] = {5000}; + #elif DEC_DIGITS == 2 static NumericDigit const_zero_point_five_data[1] = {50}; + #elif DEC_DIGITS == 1 static NumericDigit const_zero_point_five_data[1] = {5}; #endif @@ -176,8 +178,10 @@ static NumericVar const_zero_point_five = #if DEC_DIGITS == 4 static NumericDigit const_zero_point_nine_data[1] = {9000}; + #elif DEC_DIGITS == 2 static NumericDigit const_zero_point_nine_data[1] = {90}; + #elif DEC_DIGITS == 1 static NumericDigit const_zero_point_nine_data[1] = {9}; #endif @@ -188,10 +192,12 @@ static NumericVar const_zero_point_nine = static NumericDigit const_zero_point_01_data[1] = {100}; static NumericVar const_zero_point_01 = {1, -1, NUMERIC_POS, 2, NULL, const_zero_point_01_data}; + #elif DEC_DIGITS == 2 static NumericDigit const_zero_point_01_data[1] = {1}; static NumericVar const_zero_point_01 = {1, -1, NUMERIC_POS, 2, NULL, const_zero_point_01_data}; + #elif DEC_DIGITS == 1 static NumericDigit const_zero_point_01_data[1] = {1}; static NumericVar const_zero_point_01 = @@ -200,8 +206,10 @@ static NumericVar const_zero_point_01 = #if DEC_DIGITS == 4 static NumericDigit const_one_point_one_data[2] = {1, 1000}; + #elif DEC_DIGITS == 2 static NumericDigit const_one_point_one_data[2] = {1, 10}; + #elif DEC_DIGITS == 1 static NumericDigit const_one_point_one_data[2] = {1, 1}; #endif @@ -212,7 +220,7 @@ static NumericVar const_nan = {0, 0, NUMERIC_NAN, 0, NULL, NULL}; #if DEC_DIGITS == 4 -static const int round_powers[4] = { 0, 1000, 100, 10 }; +static const int round_powers[4] = {0, 1000, 100, 10}; #endif @@ -263,9 +271,9 @@ static int cmp_var(NumericVar *var1, NumericVar *var2); static void add_var(NumericVar *var1, NumericVar *var2, NumericVar *result); static void sub_var(NumericVar *var1, NumericVar *var2, NumericVar *result); static void mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, - int rscale); + int rscale); static void div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, - int rscale); + int rscale); static int select_div_scale(NumericVar *var1, NumericVar *var2); static void mod_var(NumericVar *var1, NumericVar *var2, NumericVar *result); static void ceil_var(NumericVar *var, NumericVar *result); @@ -278,7 +286,7 @@ static void ln_var(NumericVar *arg, NumericVar *result, int rscale); static void log_var(NumericVar *base, NumericVar *num, NumericVar *result); static void power_var(NumericVar *base, NumericVar *exp, NumericVar *result); static void power_var_int(NumericVar *base, int exp, NumericVar *result, - int rscale); + int rscale); static int cmp_abs(NumericVar *var1, NumericVar *var2); static void add_abs(NumericVar *var1, NumericVar *var2, NumericVar *result); @@ -408,7 +416,7 @@ numeric_recv(PG_FUNCTION_ARGS) value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16)); for (i = 0; i < len; i++) { - NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit)); + NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit)); if (d < 0 || d >= NBASE) ereport(ERROR, @@ -1081,8 +1089,8 @@ numeric_mul(PG_FUNCTION_ARGS) /* * Unpack the values, let mul_var() compute the result and return it. - * Unlike add_var() and sub_var(), mul_var() will round its result. - * In the case of numeric_mul(), which is invoked for the * operator on + * Unlike add_var() and sub_var(), mul_var() will round its result. In + * the case of numeric_mul(), which is invoked for the * operator on * numerics, we request exact representation for the product (rscale = * sum(dscale of arg1, dscale of arg2)). */ @@ -1303,7 +1311,7 @@ numeric_sqrt(PG_FUNCTION_ARGS) PG_RETURN_NUMERIC(make_result(&const_nan)); /* - * Unpack the argument and determine the result scale. We choose a + * Unpack the argument and determine the result scale. We choose a * scale to give at least NUMERIC_MIN_SIG_DIGITS significant digits; * but in any case not less than the input's dscale. */ @@ -1356,7 +1364,7 @@ numeric_exp(PG_FUNCTION_ARGS) PG_RETURN_NUMERIC(make_result(&const_nan)); /* - * Unpack the argument and determine the result scale. We choose a + * Unpack the argument and determine the result scale. We choose a * scale to give at least NUMERIC_MIN_SIG_DIGITS significant digits; * but in any case not less than the input's dscale. */ @@ -1369,8 +1377,8 @@ numeric_exp(PG_FUNCTION_ARGS) val = numericvar_to_double_no_overflow(&arg); /* - * log10(result) = num * log10(e), so this is approximately the decimal - * weight of the result: + * log10(result) = num * log10(e), so this is approximately the + * decimal weight of the result: */ val *= 0.434294481903252; @@ -2055,7 +2063,7 @@ numeric_variance(PG_FUNCTION_ARGS) } else { - mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */ + mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */ rscale = select_div_scale(&vsumX2, &vNminus1); div_var(&vsumX2, &vNminus1, &vsumX, rscale); /* variance */ @@ -2131,7 +2139,7 @@ numeric_stddev(PG_FUNCTION_ARGS) } else { - mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */ + mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */ rscale = select_div_scale(&vsumX2, &vNminus1); div_var(&vsumX2, &vNminus1, &vsumX, rscale); /* variance */ sqrt_var(&vsumX, &vsumX, rscale); /* stddev */ @@ -2409,7 +2417,6 @@ dump_var(const char *str, NumericVar *var) printf("\n"); } - #endif /* NUMERIC_DEBUG */ @@ -2434,7 +2441,7 @@ alloc_var(NumericVar *var, int ndigits) { digitbuf_free(var->buf); var->buf = digitbuf_alloc(ndigits + 1); - var->buf[0] = 0; /* spare digit for rounding */ + var->buf[0] = 0; /* spare digit for rounding */ var->digits = var->buf + 1; var->ndigits = ndigits; } @@ -2495,8 +2502,8 @@ set_var_from_str(const char *str, NumericVar *dest) NumericDigit *digits; /* - * We first parse the string to extract decimal digits and determine the - * correct decimal weight. Then convert to NBASE representation. + * We first parse the string to extract decimal digits and determine + * the correct decimal weight. Then convert to NBASE representation. */ /* skip leading spaces */ @@ -2529,9 +2536,9 @@ set_var_from_str(const char *str, NumericVar *dest) if (!isdigit((unsigned char) *cp)) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for numeric: \"%s\"", str))); + errmsg("invalid input syntax for numeric: \"%s\"", str))); - decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS*2); + decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2); /* leading padding for digit alignment later */ memset(decdigits, 0, DEC_DIGITS); @@ -2552,8 +2559,8 @@ set_var_from_str(const char *str, NumericVar *dest) if (have_dp) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), - errmsg("invalid input syntax for numeric: \"%s\"", - str))); + errmsg("invalid input syntax for numeric: \"%s\"", + str))); have_dp = TRUE; cp++; } @@ -2563,7 +2570,7 @@ set_var_from_str(const char *str, NumericVar *dest) ddigits = i - DEC_DIGITS; /* trailing padding for digit alignment later */ - memset(decdigits + i, 0, DEC_DIGITS-1); + memset(decdigits + i, 0, DEC_DIGITS - 1); /* Handle exponent, if any */ if (*cp == 'e' || *cp == 'E') @@ -2604,16 +2611,16 @@ set_var_from_str(const char *str, NumericVar *dest) /* * Okay, convert pure-decimal representation to base NBASE. First we - * need to determine the converted weight and ndigits. offset is the + * need to determine the converted weight and ndigits. offset is the * number of decimal zeroes to insert before the first given digit to * have a correctly aligned first NBASE digit. */ if (dweight >= 0) - weight = (dweight + 1 + DEC_DIGITS-1) / DEC_DIGITS - 1; + weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1; else - weight = - ((-dweight - 1) / DEC_DIGITS + 1); + weight = -((-dweight - 1) / DEC_DIGITS + 1); offset = (weight + 1) * DEC_DIGITS - (dweight + 1); - ndigits = (ddigits + offset + DEC_DIGITS-1) / DEC_DIGITS; + ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS; alloc_var(dest, ndigits); dest->sign = sign; @@ -2626,10 +2633,10 @@ set_var_from_str(const char *str, NumericVar *dest) while (ndigits-- > 0) { #if DEC_DIGITS == 4 - *digits++ = ((decdigits[i] * 10 + decdigits[i+1]) * 10 + - decdigits[i+2]) * 10 + decdigits[i+3]; + *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 + + decdigits[i + 2]) * 10 + decdigits[i + 3]; #elif DEC_DIGITS == 2 - *digits++ = decdigits[i] * 10 + decdigits[i+1]; + *digits++ = decdigits[i] * 10 + decdigits[i + 1]; #elif DEC_DIGITS == 1 *digits++ = decdigits[i]; #else @@ -2704,9 +2711,10 @@ get_str_from_var(NumericVar *var, int dscale) char *endcp; int i; int d; - NumericDigit dig; + NumericDigit dig; + #if DEC_DIGITS > 1 - NumericDigit d1; + NumericDigit d1; #endif if (dscale < 0) @@ -2720,10 +2728,10 @@ get_str_from_var(NumericVar *var, int dscale) /* * Allocate space for the result. * - * i is set to to # of decimal digits before decimal point. - * dscale is the # of decimal digits we will print after decimal point. - * We may generate as many as DEC_DIGITS-1 excess digits at the end, - * and in addition we need room for sign, decimal point, null terminator. + * i is set to to # of decimal digits before decimal point. dscale is the + * # of decimal digits we will print after decimal point. We may + * generate as many as DEC_DIGITS-1 excess digits at the end, and in + * addition we need room for sign, decimal point, null terminator. */ i = (var->weight + 1) * DEC_DIGITS; if (i <= 0) @@ -2754,7 +2762,7 @@ get_str_from_var(NumericVar *var, int dscale) /* In the first digit, suppress extra leading decimal zeroes */ #if DEC_DIGITS == 4 { - bool putit = (d > 0); + bool putit = (d > 0); d1 = dig / 1000; dig -= d1 * 1000; @@ -2789,7 +2797,7 @@ get_str_from_var(NumericVar *var, int dscale) /* * If requested, output a decimal point and all the digits that follow - * it. We initially put out a multiple of DEC_DIGITS digits, then + * it. We initially put out a multiple of DEC_DIGITS digits, then * truncate if needed. */ if (dscale > 0) @@ -2966,7 +2974,7 @@ apply_typmod(NumericVar *var, int32 typmod) (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("numeric field overflow"), errdetail("ABS(value) >= 10^%d for field with precision %d, scale %d.", - ddigits-1, precision, scale))); + ddigits - 1, precision, scale))); break; } ddigits -= DEC_DIGITS; @@ -2977,7 +2985,7 @@ apply_typmod(NumericVar *var, int32 typmod) /* * Convert numeric to int8, rounding if needed. * - * If overflow, return FALSE (no error is raised). Return TRUE if okay. + * If overflow, return FALSE (no error is raised). Return TRUE if okay. * * CAUTION: var's contents may be modified by rounding! */ @@ -3006,10 +3014,11 @@ numericvar_to_int8(NumericVar *var, int64 *result) /* * For input like 10000000000, we must treat stripped digits as real. - * So the loop assumes there are weight+1 digits before the decimal point. + * So the loop assumes there are weight+1 digits before the decimal + * point. */ weight = var->weight; - Assert(weight >= 0 && ndigits <= weight+1); + Assert(weight >= 0 && ndigits <= weight + 1); /* Construct the result */ digits = var->digits; @@ -3021,6 +3030,7 @@ numericvar_to_int8(NumericVar *var, int64 *result) val *= NBASE; if (i < ndigits) val += digits[i]; + /* * The overflow check is a bit tricky because we want to accept * INT64_MIN, which will overflow the positive accumulator. We @@ -3051,7 +3061,7 @@ int8_to_numericvar(int64 val, NumericVar *var) int ndigits; /* int8 can require at most 19 decimal digits; add one for safety */ - alloc_var(var, 20/DEC_DIGITS); + alloc_var(var, 20 / DEC_DIGITS); if (val < 0) { var->sign = NUMERIC_NEG; @@ -3071,7 +3081,8 @@ int8_to_numericvar(int64 val, NumericVar *var) } ptr = var->digits + var->ndigits; ndigits = 0; - do { + do + { ptr--; ndigits++; newuval = uval / NBASE; @@ -3420,7 +3431,7 @@ sub_var(NumericVar *var1, NumericVar *var2, NumericVar *result) * mul_var() - * * Multiplication on variable level. Product of var1 * var2 is stored - * in result. Result is rounded to no more than rscale fractional digits. + * in result. Result is rounded to no more than rscale fractional digits. */ static void mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, @@ -3439,6 +3450,7 @@ mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, ri, i1, i2; + /* copy these values into local vars for speed in inner loop */ int var1ndigits = var1->ndigits; int var2ndigits = var2->ndigits; @@ -3462,9 +3474,10 @@ mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, /* * Determine number of result digits to compute. If the exact result - * would have more than rscale fractional digits, truncate the computation - * with MUL_GUARD_DIGITS guard digits. We do that by pretending that - * one or both inputs have fewer digits than they really do. + * would have more than rscale fractional digits, truncate the + * computation with MUL_GUARD_DIGITS guard digits. We do that by + * pretending that one or both inputs have fewer digits than they + * really do. */ res_ndigits = var1ndigits + var2ndigits + 1; maxdigits = res_weight + 1 + (rscale * DEC_DIGITS) + MUL_GUARD_DIGITS; @@ -3498,13 +3511,13 @@ mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, /* * We do the arithmetic in an array "dig[]" of signed int's. Since - * INT_MAX is noticeably larger than NBASE*NBASE, this gives us headroom - * to avoid normalizing carries immediately. + * INT_MAX is noticeably larger than NBASE*NBASE, this gives us + * headroom to avoid normalizing carries immediately. * - * maxdig tracks the maximum possible value of any dig[] entry; - * when this threatens to exceed INT_MAX, we take the time to propagate - * carries. To avoid overflow in maxdig itself, it actually represents - * the max possible value divided by NBASE-1. + * maxdig tracks the maximum possible value of any dig[] entry; when this + * threatens to exceed INT_MAX, we take the time to propagate carries. + * To avoid overflow in maxdig itself, it actually represents the max + * possible value divided by NBASE-1. */ dig = (int *) palloc0(res_ndigits * sizeof(int)); maxdig = 0; @@ -3512,24 +3525,24 @@ mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, ri = res_ndigits - 1; for (i1 = var1ndigits - 1; i1 >= 0; ri--, i1--) { - int var1digit = var1digits[i1]; + int var1digit = var1digits[i1]; if (var1digit == 0) continue; /* Time to normalize? */ maxdig += var1digit; - if (maxdig > INT_MAX/(NBASE-1)) + if (maxdig > INT_MAX / (NBASE - 1)) { /* Yes, do it */ carry = 0; - for (i = res_ndigits-1; i >= 0; i--) + for (i = res_ndigits - 1; i >= 0; i--) { newdig = dig[i] + carry; if (newdig >= NBASE) { - carry = newdig/NBASE; - newdig -= carry*NBASE; + carry = newdig / NBASE; + newdig -= carry * NBASE; } else carry = 0; @@ -3543,9 +3556,7 @@ mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, /* Add appropriate multiple of var2 into the accumulator */ i = ri; for (i2 = var2ndigits - 1; i2 >= 0; i2--) - { dig[i--] += var1digit * var2digits[i2]; - } } /* @@ -3556,13 +3567,13 @@ mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, alloc_var(result, res_ndigits); res_digits = result->digits; carry = 0; - for (i = res_ndigits-1; i >= 0; i--) + for (i = res_ndigits - 1; i >= 0; i--) { newdig = dig[i] + carry; if (newdig >= NBASE) { - carry = newdig/NBASE; - newdig -= carry*NBASE; + carry = newdig / NBASE; + newdig -= carry * NBASE; } else carry = 0; @@ -3590,7 +3601,7 @@ mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result, * div_var() - * * Division on variable level. Quotient of var1 / var2 is stored - * in result. Result is rounded to no more than rscale fractional digits. + * in result. Result is rounded to no more than rscale fractional digits. */ static void div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, @@ -3611,6 +3622,7 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, fquotient; int qi; int i; + /* copy these values into local vars for speed in inner loop */ int var1ndigits = var1->ndigits; int var2ndigits = var2->ndigits; @@ -3645,7 +3657,7 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, res_sign = NUMERIC_NEG; res_weight = var1->weight - var2->weight + 1; /* The number of accurate result digits we need to produce: */ - div_ndigits = res_weight + 1 + (rscale + DEC_DIGITS-1)/DEC_DIGITS; + div_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS; /* Add guard digits for roundoff error */ div_ndigits += DIV_GUARD_DIGITS; if (div_ndigits < DIV_GUARD_DIGITS) @@ -3656,8 +3668,8 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, /* * We do the arithmetic in an array "div[]" of signed int's. Since - * INT_MAX is noticeably larger than NBASE*NBASE, this gives us headroom - * to avoid normalizing carries immediately. + * INT_MAX is noticeably larger than NBASE*NBASE, this gives us + * headroom to avoid normalizing carries immediately. * * We start with div[] containing one zero digit followed by the * dividend's digits (plus appended zeroes to reach the desired @@ -3668,7 +3680,7 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, */ div = (int *) palloc0((div_ndigits + 1) * sizeof(int)); for (i = 0; i < var1ndigits; i++) - div[i+1] = var1digits[i]; + div[i + 1] = var1digits[i]; /* * We estimate each quotient digit using floating-point arithmetic, @@ -3685,10 +3697,10 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, fdivisorinverse = 1.0 / fdivisor; /* - * maxdiv tracks the maximum possible absolute value of any div[] entry; - * when this threatens to exceed INT_MAX, we take the time to propagate - * carries. To avoid overflow in maxdiv itself, it actually represents - * the max possible abs. value divided by NBASE-1. + * maxdiv tracks the maximum possible absolute value of any div[] + * entry; when this threatens to exceed INT_MAX, we take the time to + * propagate carries. To avoid overflow in maxdiv itself, it actually + * represents the max possible abs. value divided by NBASE-1. */ maxdiv = 1; @@ -3702,19 +3714,19 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, for (i = 1; i < 4; i++) { fdividend *= NBASE; - if (qi+i <= div_ndigits) - fdividend += (double) div[qi+i]; + if (qi + i <= div_ndigits) + fdividend += (double) div[qi + i]; } /* Compute the (approximate) quotient digit */ fquotient = fdividend * fdivisorinverse; qdigit = (fquotient >= 0.0) ? ((int) fquotient) : - (((int) fquotient) - 1); /* truncate towards -infinity */ + (((int) fquotient) - 1); /* truncate towards -infinity */ if (qdigit != 0) { /* Do we need to normalize now? */ maxdiv += Abs(qdigit); - if (maxdiv > INT_MAX/(NBASE-1)) + if (maxdiv > INT_MAX / (NBASE - 1)) { /* Yes, do it */ carry = 0; @@ -3723,13 +3735,13 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, newdig = div[i] + carry; if (newdig < 0) { - carry = -((-newdig-1)/NBASE) - 1; - newdig -= carry*NBASE; + carry = -((-newdig - 1) / NBASE) - 1; + newdig -= carry * NBASE; } else if (newdig >= NBASE) { - carry = newdig/NBASE; - newdig -= carry*NBASE; + carry = newdig / NBASE; + newdig -= carry * NBASE; } else carry = 0; @@ -3737,12 +3749,14 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, } newdig = div[qi] + carry; div[qi] = newdig; + /* - * All the div[] digits except possibly div[qi] are now - * in the range 0..NBASE-1. + * All the div[] digits except possibly div[qi] are now in + * the range 0..NBASE-1. */ - maxdiv = Abs(newdig) / (NBASE-1); + maxdiv = Abs(newdig) / (NBASE - 1); maxdiv = Max(maxdiv, 1); + /* * Recompute the quotient digit since new info may have * propagated into the top four dividend digits @@ -3751,33 +3765,34 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, for (i = 1; i < 4; i++) { fdividend *= NBASE; - if (qi+i <= div_ndigits) - fdividend += (double) div[qi+i]; + if (qi + i <= div_ndigits) + fdividend += (double) div[qi + i]; } /* Compute the (approximate) quotient digit */ fquotient = fdividend * fdivisorinverse; qdigit = (fquotient >= 0.0) ? ((int) fquotient) : - (((int) fquotient) - 1); /* truncate towards -infinity */ + (((int) fquotient) - 1); /* truncate towards + * -infinity */ maxdiv += Abs(qdigit); } /* Subtract off the appropriate multiple of the divisor */ if (qdigit != 0) { - int istop = Min(var2ndigits, div_ndigits-qi+1); + int istop = Min(var2ndigits, div_ndigits - qi + 1); for (i = 0; i < istop; i++) - div[qi+i] -= qdigit * var2digits[i]; + div[qi + i] -= qdigit * var2digits[i]; } } /* - * The dividend digit we are about to replace might still be nonzero. - * Fold it into the next digit position. We don't need to worry about - * overflow here since this should nearly cancel with the subtraction - * of the divisor. + * The dividend digit we are about to replace might still be + * nonzero. Fold it into the next digit position. We don't need + * to worry about overflow here since this should nearly cancel + * with the subtraction of the divisor. */ - div[qi+1] += div[qi] * NBASE; + div[qi + 1] += div[qi] * NBASE; div[qi] = qdigit; } @@ -3787,12 +3802,10 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, */ fdividend = (double) div[qi]; for (i = 1; i < 4; i++) - { fdividend *= NBASE; - } fquotient = fdividend * fdivisorinverse; qdigit = (fquotient >= 0.0) ? ((int) fquotient) : - (((int) fquotient) - 1); /* truncate towards -infinity */ + (((int) fquotient) - 1); /* truncate towards -infinity */ div[qi] = qdigit; /* @@ -3800,7 +3813,7 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, * which we combine with storing the result digits into the output. * Note that this is still done at full precision w/guard digits. */ - alloc_var(result, div_ndigits+1); + alloc_var(result, div_ndigits + 1); res_digits = result->digits; carry = 0; for (i = div_ndigits; i >= 0; i--) @@ -3808,13 +3821,13 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result, newdig = div[i] + carry; if (newdig < 0) { - carry = -((-newdig-1)/NBASE) - 1; - newdig -= carry*NBASE; + carry = -((-newdig - 1) / NBASE) - 1; + newdig -= carry * NBASE; } else if (newdig >= NBASE) { - carry = newdig/NBASE; - newdig -= carry*NBASE; + carry = newdig / NBASE; + newdig -= carry * NBASE; } else carry = 0; @@ -3889,8 +3902,8 @@ select_div_scale(NumericVar *var1, NumericVar *var2) } /* - * Estimate weight of quotient. If the two first digits are equal, - * we can't be sure, but assume that var1 is less than var2. + * Estimate weight of quotient. If the two first digits are equal, we + * can't be sure, but assume that var1 is less than var2. */ qweight = weight1 - weight2; if (firstdigit1 <= firstdigit2) @@ -4176,16 +4189,17 @@ exp_var_internal(NumericVar *arg, NumericVar *result, int rscale) { ndiv2++; local_rscale++; - mul_var(&x, &const_zero_point_five, &x, x.dscale+1); + mul_var(&x, &const_zero_point_five, &x, x.dscale + 1); } /* * Use the Taylor series * - * exp(x) = 1 + x + x^2/2! + x^3/3! + ... + * exp(x) = 1 + x + x^2/2! + x^3/3! + ... * * Given the limited range of x, this should converge reasonably quickly. - * We run the series until the terms fall below the local_rscale limit. + * We run the series until the terms fall below the local_rscale + * limit. */ add_var(&const_one, &x, result); set_var_from_var(&x, &xpow); @@ -4265,7 +4279,7 @@ ln_var(NumericVar *arg, NumericVar *result, int rscale) /* * We use the Taylor series for 0.5 * ln((1+z)/(1-z)), * - * z + z^3/3 + z^5/5 + ... + * z + z^3/3 + z^5/5 + ... * * where z = (x-1)/(x+1) is in the range (approximately) -0.053 .. 0.048 * due to the above range-reduction of x. @@ -4292,7 +4306,7 @@ ln_var(NumericVar *arg, NumericVar *result, int rscale) add_var(result, &elem, result); - if (elem.weight < (result->weight - local_rscale * 2/DEC_DIGITS)) + if (elem.weight < (result->weight - local_rscale * 2 / DEC_DIGITS)) break; } @@ -4391,7 +4405,7 @@ power_var(NumericVar *base, NumericVar *exp, NumericVar *result) set_var_from_var(exp, &x); if (numericvar_to_int8(&x, &expval64)) { - int expval = (int) expval64; + int expval = (int) expval64; /* Test for overflow by reverse-conversion. */ if ((int64) expval == expval64) @@ -4420,11 +4434,11 @@ power_var(NumericVar *base, NumericVar *exp, NumericVar *result) dec_digits = (base->weight + 1) * DEC_DIGITS; if (dec_digits > 1) - rscale = NUMERIC_MIN_SIG_DIGITS*2 - (int) log10(dec_digits - 1); + rscale = NUMERIC_MIN_SIG_DIGITS * 2 - (int) log10(dec_digits - 1); else if (dec_digits < 1) - rscale = NUMERIC_MIN_SIG_DIGITS*2 - (int) log10(1 - dec_digits); + rscale = NUMERIC_MIN_SIG_DIGITS * 2 - (int) log10(1 - dec_digits); else - rscale = NUMERIC_MIN_SIG_DIGITS*2; + rscale = NUMERIC_MIN_SIG_DIGITS * 2; rscale = Max(rscale, base->dscale * 2); rscale = Max(rscale, exp->dscale * 2); @@ -4442,7 +4456,10 @@ power_var(NumericVar *base, NumericVar *exp, NumericVar *result) /* convert input to float8, ignoring overflow */ val = numericvar_to_double_no_overflow(&ln_num); - /* log10(result) = num * log10(e), so this is approximately the weight: */ + /* + * log10(result) = num * log10(e), so this is approximately the + * weight: + */ val *= 0.434294481903252; /* limit to something that won't cause integer overflow */ @@ -4483,7 +4500,7 @@ power_var_int(NumericVar *base, int exp, NumericVar *result, int rscale) (errcode(ERRCODE_FLOATING_POINT_EXCEPTION), errmsg("zero raised to zero is undefined"))); set_var_from_var(&const_one, result); - result->dscale = rscale; /* no need to round */ + result->dscale = rscale; /* no need to round */ return; case 1: set_var_from_var(base, result); @@ -4500,8 +4517,8 @@ power_var_int(NumericVar *base, int exp, NumericVar *result, int rscale) } /* - * The general case repeatedly multiplies base according to the - * bit pattern of exp. We do the multiplications with some extra + * The general case repeatedly multiplies base according to the bit + * pattern of exp. We do the multiplications with some extra * precision. */ neg = (exp < 0); @@ -4595,8 +4612,8 @@ cmp_abs(NumericVar *var1, NumericVar *var2) } /* - * At this point, we've run out of digits on one side or the other; - * so any remaining nonzero digits imply that side is larger + * At this point, we've run out of digits on one side or the other; so + * any remaining nonzero digits imply that side is larger */ while (i1 < var1->ndigits) { @@ -4789,7 +4806,7 @@ sub_abs(NumericVar *var1, NumericVar *var2, NumericVar *result) static void round_var(NumericVar *var, int rscale) { - NumericDigit *digits = var->digits; + NumericDigit *digits = var->digits; int di; int ndigits; int carry; @@ -4800,8 +4817,8 @@ round_var(NumericVar *var, int rscale) di = (var->weight + 1) * DEC_DIGITS + rscale; /* - * If di = 0, the value loses all digits, but could round up to 1 - * if its first extra digit is >= 5. If di < 0 the result must be 0. + * If di = 0, the value loses all digits, but could round up to 1 if + * its first extra digit is >= 5. If di < 0 the result must be 0. */ if (di < 0) { @@ -4812,7 +4829,7 @@ round_var(NumericVar *var, int rscale) else { /* NBASE digits wanted */ - ndigits = (di + DEC_DIGITS-1) / DEC_DIGITS; + ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS; /* 0, or number of decimal digits to keep in last NBASE digit */ di %= DEC_DIGITS; @@ -4827,14 +4844,12 @@ round_var(NumericVar *var, int rscale) carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0; #else if (di == 0) - { carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0; - } else { /* Must round within last NBASE digit */ - int extra, - pow10; + int extra, + pow10; #if DEC_DIGITS == 4 pow10 = round_powers[di]; @@ -4846,7 +4861,7 @@ round_var(NumericVar *var, int rscale) extra = digits[--ndigits] % pow10; digits[ndigits] -= extra; carry = 0; - if (extra >= pow10/2) + if (extra >= pow10 / 2) { pow10 += digits[ndigits]; if (pow10 >= NBASE) @@ -4917,7 +4932,7 @@ trunc_var(NumericVar *var, int rscale) else { /* NBASE digits wanted */ - ndigits = (di + DEC_DIGITS-1) / DEC_DIGITS; + ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS; if (ndigits <= var->ndigits) { @@ -4932,9 +4947,9 @@ trunc_var(NumericVar *var, int rscale) if (di > 0) { /* Must truncate within last NBASE digit */ - NumericDigit *digits = var->digits; - int extra, - pow10; + NumericDigit *digits = var->digits; + int extra, + pow10; #if DEC_DIGITS == 4 pow10 = round_powers[di]; @@ -4959,7 +4974,7 @@ trunc_var(NumericVar *var, int rscale) static void strip_var(NumericVar *var) { - NumericDigit *digits = var->digits; + NumericDigit *digits = var->digits; int ndigits = var->ndigits; /* Strip leading zeroes */ diff --git a/src/backend/utils/adt/numutils.c b/src/backend/utils/adt/numutils.c index a73842785e..8b6b43ac89 100644 --- a/src/backend/utils/adt/numutils.c +++ b/src/backend/utils/adt/numutils.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/numutils.c,v 1.55 2003/07/27 04:53:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/numutils.c,v 1.56 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -96,7 +96,7 @@ pg_atoi(char *s, int size, int c) case sizeof(int32): if (errno == ERANGE #if defined(HAVE_LONG_INT_64) - /* won't get ERANGE on these with 64-bit longs... */ + /* won't get ERANGE on these with 64-bit longs... */ || l < INT_MIN || l > INT_MAX #endif ) diff --git a/src/backend/utils/adt/oid.c b/src/backend/utils/adt/oid.c index aa070c2694..d0802593bf 100644 --- a/src/backend/utils/adt/oid.c +++ b/src/backend/utils/adt/oid.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/oid.c,v 1.49 2003/07/27 04:53:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/oid.c,v 1.50 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -222,9 +222,7 @@ oidvectorrecv(PG_FUNCTION_ARGS) int slot; for (slot = 0; slot < INDEX_MAX_KEYS; slot++) - { result[slot] = (Oid) pq_getmsgint(buf, sizeof(Oid)); - } PG_RETURN_POINTER(result); } @@ -240,9 +238,7 @@ oidvectorsend(PG_FUNCTION_ARGS) pq_begintypsend(&buf); for (slot = 0; slot < INDEX_MAX_KEYS; slot++) - { pq_sendint(&buf, oidArray[slot], sizeof(Oid)); - } PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); } diff --git a/src/backend/utils/adt/oracle_compat.c b/src/backend/utils/adt/oracle_compat.c index 8fd63164f0..4e0c14be16 100644 --- a/src/backend/utils/adt/oracle_compat.c +++ b/src/backend/utils/adt/oracle_compat.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/oracle_compat.c,v 1.46 2003/07/27 04:53:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/oracle_compat.c,v 1.47 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -22,8 +22,8 @@ static text *dotrim(const char *string, int stringlen, - const char *set, int setlen, - bool doltrim, bool dortrim); + const char *set, int setlen, + bool doltrim, bool dortrim); /******************************************************************** @@ -403,8 +403,8 @@ dotrim(const char *string, int stringlen, { /* * In the multibyte-encoding case, build arrays of pointers to - * character starts, so that we can avoid inefficient checks in - * the inner loops. + * character starts, so that we can avoid inefficient checks + * in the inner loops. */ const char **stringchars; const char **setchars; @@ -499,13 +499,14 @@ dotrim(const char *string, int stringlen, else { /* - * In the single-byte-encoding case, we don't need such overhead. + * In the single-byte-encoding case, we don't need such + * overhead. */ if (doltrim) { while (stringlen > 0) { - char str_ch = *string; + char str_ch = *string; for (i = 0; i < setlen; i++) { @@ -523,7 +524,7 @@ dotrim(const char *string, int stringlen, { while (stringlen > 0) { - char str_ch = string[stringlen - 1]; + char str_ch = string[stringlen - 1]; for (i = 0; i < setlen; i++) { diff --git a/src/backend/utils/adt/pg_locale.c b/src/backend/utils/adt/pg_locale.c index 26bde944fa..d6a0d97889 100644 --- a/src/backend/utils/adt/pg_locale.c +++ b/src/backend/utils/adt/pg_locale.c @@ -4,7 +4,7 @@ * * Portions Copyright (c) 2002, PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_locale.c,v 1.21 2003/07/27 04:53:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_locale.c,v 1.22 2003/08/04 00:43:25 momjian Exp $ * *----------------------------------------------------------------------- */ @@ -25,7 +25,7 @@ * Instead, we only set the locales briefly when needed, cache the * required information obtained from localeconv(), and set them back. * The cached information is only used by the formatting functions - * (to_char, etc.) and the money type. For the user, this should all be + * (to_char, etc.) and the money type. For the user, this should all be * transparent. (Actually, LC_TIME doesn't do anything at all right * now.) * @@ -40,7 +40,7 @@ * fail = true; * setlocale(category, save); * DOES NOT WORK RELIABLY: on some platforms the second setlocale() call - * will change the memory save is pointing at. To do this sort of thing + * will change the memory save is pointing at. To do this sort of thing * safely, you *must* pstrdup what setlocale returns the first time. *---------- */ @@ -134,9 +134,7 @@ locale_messages_assign(const char *value, bool doit, bool interactive) return NULL; } else - { value = locale_xxx_assign(LC_MESSAGES, value, false, interactive); - } #endif return value; } diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index df8c8e92cc..440783764a 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -308,11 +308,11 @@ pg_stat_get_backend_activity(PG_FUNCTION_ARGS) Datum pg_stat_get_backend_activity_start(PG_FUNCTION_ARGS) { - PgStat_StatBeEntry *beentry; - int32 beid; - AbsoluteTime sec; - int usec; - TimestampTz result; + PgStat_StatBeEntry *beentry; + int32 beid; + AbsoluteTime sec; + int usec; + TimestampTz result; beid = PG_GETARG_INT32(0); @@ -326,8 +326,8 @@ pg_stat_get_backend_activity_start(PG_FUNCTION_ARGS) usec = beentry->activity_start_usec; /* - * No time recorded for start of current query -- this is the case - * if the user hasn't enabled query-level stats collection. + * No time recorded for start of current query -- this is the case if + * the user hasn't enabled query-level stats collection. */ if (sec == 0 && usec == 0) PG_RETURN_NULL(); diff --git a/src/backend/utils/adt/pseudotypes.c b/src/backend/utils/adt/pseudotypes.c index 78b132c516..96f9903ce4 100644 --- a/src/backend/utils/adt/pseudotypes.c +++ b/src/backend/utils/adt/pseudotypes.c @@ -16,7 +16,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/pseudotypes.c,v 1.9 2003/07/28 00:09:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/pseudotypes.c,v 1.10 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -191,7 +191,7 @@ anyarray_out(PG_FUNCTION_ARGS) * anyarray_recv - binary input routine for pseudo-type ANYARRAY. * * XXX this could actually be made to work, since the incoming array - * data will contain the element type OID. Need to think through + * data will contain the element type OID. Need to think through * type-safety issues before allowing it, however. */ Datum diff --git a/src/backend/utils/adt/regexp.c b/src/backend/utils/adt/regexp.c index 8853308663..8ecffd16c9 100644 --- a/src/backend/utils/adt/regexp.c +++ b/src/backend/utils/adt/regexp.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/regexp.c,v 1.46 2003/07/27 04:53:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/regexp.c,v 1.47 2003/08/04 00:43:25 momjian Exp $ * * Alistair Crooks added the code for the regex caching * agc - cached the regular expressions used - there's a good chance @@ -73,10 +73,10 @@ typedef struct cached_re_str text *cre_pat; /* original RE (untoasted TEXT form) */ int cre_flags; /* compile flags: extended,icase etc */ regex_t cre_re; /* the compiled regular expression */ -} cached_re_str; +} cached_re_str; static int num_res = 0; /* # of cached re's */ -static cached_re_str re_array[MAX_CACHED_RES]; /* cached re's */ +static cached_re_str re_array[MAX_CACHED_RES]; /* cached re's */ /* @@ -88,7 +88,7 @@ static cached_re_str re_array[MAX_CACHED_RES]; /* cached re's */ * dat --- the data to match against (need not be null-terminated) * dat_len --- the length of the data string * cflags --- compile options for the pattern - * nmatch, pmatch --- optional return area for match details + * nmatch, pmatch --- optional return area for match details * * Both pattern and data are given in the database encoding. We internally * convert to array of pg_wchar which is what Spencer's regex package wants. @@ -105,14 +105,14 @@ RE_compile_and_execute(text *text_re, unsigned char *dat, int dat_len, int i; int regcomp_result; int regexec_result; - cached_re_str re_temp; + cached_re_str re_temp; /* Convert data string to wide characters */ data = (pg_wchar *) palloc((dat_len + 1) * sizeof(pg_wchar)); data_len = pg_mb2wchar_with_len(dat, data, dat_len); /* - * Look for a match among previously compiled REs. Since the data + * Look for a match among previously compiled REs. Since the data * structure is self-organizing with most-used entries at the front, * our search strategy can just be to scan from the front. */ @@ -135,7 +135,7 @@ RE_compile_and_execute(text *text_re, unsigned char *dat, int dat_len, regexec_result = pg_regexec(&re_array[0].cre_re, data, data_len, - NULL, /* no details */ + NULL, /* no details */ nmatch, pmatch, 0); @@ -213,7 +213,7 @@ RE_compile_and_execute(text *text_re, unsigned char *dat, int dat_len, regexec_result = pg_regexec(&re_array[0].cre_re, data, data_len, - NULL, /* no details */ + NULL, /* no details */ nmatch, pmatch, 0); @@ -383,8 +383,8 @@ textregexsubstr(PG_FUNCTION_ARGS) /* * We pass two regmatch_t structs to get info about the overall match * and the match for the first parenthesized subexpression (if any). - * If there is a parenthesized subexpression, we return what it matched; - * else return what the whole regexp matched. + * If there is a parenthesized subexpression, we return what it + * matched; else return what the whole regexp matched. */ match = RE_compile_and_execute(p, (unsigned char *) VARDATA(s), @@ -395,8 +395,8 @@ textregexsubstr(PG_FUNCTION_ARGS) /* match? then return the substring matching the pattern */ if (match) { - int so, - eo; + int so, + eo; so = pmatch[1].rm_so; eo = pmatch[1].rm_eo; @@ -457,7 +457,7 @@ similar_escape(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE), errmsg("invalid escape string"), - errhint("Escape string must be empty or one character."))); + errhint("Escape string must be empty or one character."))); } /* We need room for ^, $, and up to 2 output bytes per input byte */ @@ -492,9 +492,7 @@ similar_escape(PG_FUNCTION_ARGS) *r++ = '*'; } else if (pchar == '_') - { *r++ = '.'; - } else if (pchar == '\\' || pchar == '.' || pchar == '?' || pchar == '{') { @@ -502,14 +500,12 @@ similar_escape(PG_FUNCTION_ARGS) *r++ = pchar; } else - { *r++ = pchar; - } p++, plen--; } *r++ = '$'; - + VARATT_SIZEP(result) = r - ((unsigned char *) result); PG_RETURN_TEXT_P(result); diff --git a/src/backend/utils/adt/regproc.c b/src/backend/utils/adt/regproc.c index 584e3e5ae8..c4059a2120 100644 --- a/src/backend/utils/adt/regproc.c +++ b/src/backend/utils/adt/regproc.c @@ -13,7 +13,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/regproc.c,v 1.79 2003/07/28 00:09:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/regproc.c,v 1.80 2003/08/04 00:43:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -114,13 +114,13 @@ regprocin(PG_FUNCTION_ARGS) if (matches == 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("no procedure with name %s", pro_name_or_oid))); + errmsg("no procedure with name %s", pro_name_or_oid))); else if (matches > 1) ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_FUNCTION), errmsg("more than one procedure named %s", - pro_name_or_oid))); + pro_name_or_oid))); PG_RETURN_OID(result); } @@ -140,7 +140,7 @@ regprocin(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_FUNCTION), errmsg("more than one procedure named %s", - pro_name_or_oid))); + pro_name_or_oid))); result = clist->oid; @@ -464,12 +464,12 @@ regoperin(PG_FUNCTION_ARGS) if (matches == 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("no operator with name %s", opr_name_or_oid))); + errmsg("no operator with name %s", opr_name_or_oid))); else if (matches > 1) ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_FUNCTION), errmsg("more than one operator named %s", - opr_name_or_oid))); + opr_name_or_oid))); PG_RETURN_OID(result); } @@ -489,7 +489,7 @@ regoperin(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_AMBIGUOUS_FUNCTION), errmsg("more than one operator named %s", - opr_name_or_oid))); + opr_name_or_oid))); result = clist->oid; diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c index ed95d8ed6c..9222bf1c17 100644 --- a/src/backend/utils/adt/ri_triggers.c +++ b/src/backend/utils/adt/ri_triggers.c @@ -17,7 +17,7 @@ * * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.52 2003/07/22 22:14:57 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.53 2003/08/04 00:43:25 momjian Exp $ * * ---------- */ @@ -150,29 +150,29 @@ static bool ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup, HeapTuple newtup, RI_QueryKey *key, int pairidx); static bool ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue); static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, - HeapTuple old_row, - Oid tgoid, int match_type, - int tgnargs, char **tgargs); + HeapTuple old_row, + Oid tgoid, int match_type, + int tgnargs, char **tgargs); static void ri_InitHashTables(void); static void *ri_FetchPreparedPlan(RI_QueryKey *key); static void ri_HashPreparedPlan(RI_QueryKey *key, void *plan); static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, - int tgkind); + int tgkind); static void *ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, - RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, - bool cache_plan); + RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, + bool cache_plan); static bool ri_PerformCheck(RI_QueryKey *qkey, void *qplan, - Relation fk_rel, Relation pk_rel, - HeapTuple old_tuple, HeapTuple new_tuple, - int expect_OK, const char *constrname); + Relation fk_rel, Relation pk_rel, + HeapTuple old_tuple, HeapTuple new_tuple, + int expect_OK, const char *constrname); static void ri_ExtractValues(RI_QueryKey *qkey, int key_idx, - Relation rel, HeapTuple tuple, - Datum *vals, char *nulls); + Relation rel, HeapTuple tuple, + Datum *vals, char *nulls); static void ri_ReportViolation(RI_QueryKey *qkey, const char *constrname, - Relation pk_rel, Relation fk_rel, - HeapTuple violator, bool spi_err); + Relation pk_rel, Relation fk_rel, + HeapTuple violator, bool spi_err); /* ---------- @@ -341,7 +341,7 @@ RI_FKey_check(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_FOREIGN_KEY_VIOLATION), errmsg("insert or update on \"%s\" violates foreign key constraint \"%s\"", - RelationGetRelationName(trigdata->tg_relation), + RelationGetRelationName(trigdata->tg_relation), tgargs[RI_CONSTRAINT_NAME_ARGNO]), errdetail("MATCH FULL does not allow mixing of NULL and non-NULL key values."))); heap_close(pk_rel, RowShareLock); @@ -366,7 +366,7 @@ RI_FKey_check(PG_FUNCTION_ARGS) */ ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("MATCH PARTIAL not yet implemented"))); + errmsg("MATCH PARTIAL not yet implemented"))); heap_close(pk_rel, RowShareLock); return PointerGetDatum(NULL); } @@ -381,8 +381,8 @@ RI_FKey_check(PG_FUNCTION_ARGS) } /* - * No need to check anything if old and new references are the - * same on UPDATE. + * No need to check anything if old and new references are the same on + * UPDATE. */ if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) { @@ -542,7 +542,7 @@ ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, */ ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("MATCH PARTIAL not yet implemented"))); + errmsg("MATCH PARTIAL not yet implemented"))); break; } @@ -759,7 +759,8 @@ RI_FKey_noaction_del(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to check for existing references. + * We have a plan now. Run it to check for existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -897,8 +898,8 @@ RI_FKey_noaction_upd(PG_FUNCTION_ARGS) match_type, tgnargs, tgargs)) { /* - * There's either another row, or no row could match this one. In - * either case, we don't need to do the check. + * There's either another row, or no row could match this + * one. In either case, we don't need to do the check. */ heap_close(fk_rel, RowShareLock); return PointerGetDatum(NULL); @@ -950,7 +951,8 @@ RI_FKey_noaction_upd(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to check for existing references. + * We have a plan now. Run it to check for existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -1110,9 +1112,9 @@ RI_FKey_cascade_del(PG_FUNCTION_ARGS) } /* - * We have a plan now. Build up the arguments - * from the key values in the deleted PK tuple and delete the - * referencing rows + * We have a plan now. Build up the arguments from the key + * values in the deleted PK tuple and delete the referencing + * rows */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -1296,7 +1298,8 @@ RI_FKey_cascade_upd(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to update the existing references. + * We have a plan now. Run it to update the existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -1465,7 +1468,8 @@ RI_FKey_restrict_del(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to check for existing references. + * We have a plan now. Run it to check for existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -1646,7 +1650,8 @@ RI_FKey_restrict_upd(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to check for existing references. + * We have a plan now. Run it to check for existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -1816,7 +1821,8 @@ RI_FKey_setnull_del(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to check for existing references. + * We have a plan now. Run it to check for existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -2034,7 +2040,8 @@ RI_FKey_setnull_upd(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to update the existing references. + * We have a plan now. Run it to update the existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -2209,14 +2216,14 @@ RI_FKey_setdefault_del(PG_FUNCTION_ARGS) * appropriate column defaults, if any (if not, they stay * NULL). * - * XXX This is really ugly; it'd be better to use "UPDATE + * XXX This is really ugly; it'd be better to use "UPDATE * SET foo = DEFAULT", if we had it. */ spi_plan = (Plan *) lfirst(((_SPI_plan *) qplan)->ptlist); foreach(l, spi_plan->targetlist) { TargetEntry *tle = (TargetEntry *) lfirst(l); - Node *dfl; + Node *dfl; /* Ignore any junk columns or Var=Var columns */ if (tle->resdom->resjunk) @@ -2234,7 +2241,8 @@ RI_FKey_setdefault_del(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to update the existing references. + * We have a plan now. Run it to update the existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -2444,14 +2452,14 @@ RI_FKey_setdefault_upd(PG_FUNCTION_ARGS) * appropriate column defaults, if any (if not, they stay * NULL). * - * XXX This is really ugly; it'd be better to use "UPDATE + * XXX This is really ugly; it'd be better to use "UPDATE * SET foo = DEFAULT", if we had it. */ spi_plan = (Plan *) lfirst(((_SPI_plan *) qplan)->ptlist); foreach(l, spi_plan->targetlist) { TargetEntry *tle = (TargetEntry *) lfirst(l); - Node *dfl; + Node *dfl; /* Ignore any junk columns or Var=Var columns */ if (tle->resdom->resjunk) @@ -2469,7 +2477,8 @@ RI_FKey_setdefault_upd(PG_FUNCTION_ARGS) } /* - * We have a plan now. Run it to update the existing references. + * We have a plan now. Run it to update the existing + * references. */ ri_PerformCheck(&qkey, qplan, fk_rel, pk_rel, @@ -2542,8 +2551,8 @@ RI_FKey_keyequal_upd(TriggerData *trigdata) (tgnargs % 2) != 0) ereport(ERROR, (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("%s() called with wrong number of trigger arguments", - "RI_FKey_keyequal_upd"))); + errmsg("%s() called with wrong number of trigger arguments", + "RI_FKey_keyequal_upd"))); /* * Nothing to do if no column names to compare given @@ -2560,9 +2569,9 @@ RI_FKey_keyequal_upd(TriggerData *trigdata) if (!OidIsValid(trigdata->tg_trigger->tgconstrrelid)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("no target table given for trigger \"%s\" on \"%s\"", - trigdata->tg_trigger->tgname, - RelationGetRelationName(trigdata->tg_relation)), + errmsg("no target table given for trigger \"%s\" on \"%s\"", + trigdata->tg_trigger->tgname, + RelationGetRelationName(trigdata->tg_relation)), errhint("Remove this RI trigger and its mates, then do ALTER TABLE ADD CONSTRAINT."))); fk_rel = heap_open(trigdata->tg_trigger->tgconstrrelid, AccessShareLock); @@ -2750,7 +2759,7 @@ ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind) if (!CALLED_AS_TRIGGER(fcinfo)) ereport(ERROR, (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("%s() was not fired by trigger manager", funcname))); + errmsg("%s() was not fired by trigger manager", funcname))); /* * Check proper event @@ -2766,28 +2775,28 @@ ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind) case RI_TRIGTYPE_INSERT: if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event)) ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("%s() must be fired for INSERT", funcname))); + (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), + errmsg("%s() must be fired for INSERT", funcname))); break; case RI_TRIGTYPE_UPDATE: if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("%s() must be fired for UPDATE", funcname))); + (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), + errmsg("%s() must be fired for UPDATE", funcname))); break; case RI_TRIGTYPE_INUP: if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) && !TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("%s() must be fired for INSERT or UPDATE", - funcname))); + (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), + errmsg("%s() must be fired for INSERT or UPDATE", + funcname))); break; case RI_TRIGTYPE_DELETE: if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("%s() must be fired for DELETE", funcname))); + (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), + errmsg("%s() must be fired for DELETE", funcname))); break; } @@ -2800,19 +2809,19 @@ ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind) (tgnargs % 2) != 0) ereport(ERROR, (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED), - errmsg("%s() called with wrong number of trigger arguments", - funcname))); + errmsg("%s() called with wrong number of trigger arguments", + funcname))); /* - * Check that tgconstrrelid is known. We need to check here because of - * ancient pg_dump bug; see notes in CreateTrigger(). + * Check that tgconstrrelid is known. We need to check here because + * of ancient pg_dump bug; see notes in CreateTrigger(). */ if (!OidIsValid(trigdata->tg_trigger->tgconstrrelid)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), - errmsg("no target table given for trigger \"%s\" on \"%s\"", - trigdata->tg_trigger->tgname, - RelationGetRelationName(trigdata->tg_relation)), + errmsg("no target table given for trigger \"%s\" on \"%s\"", + trigdata->tg_trigger->tgname, + RelationGetRelationName(trigdata->tg_relation)), errhint("Remove this RI trigger and its mates, then do ALTER TABLE ADD CONSTRAINT."))); } @@ -2833,9 +2842,9 @@ ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, AclId save_uid; /* - * The query is always run against the FK table except - * when this is an update/insert trigger on the FK table itself - - * either RI_PLAN_CHECK_LOOKUPPK or RI_PLAN_CHECK_LOOKUPPK_NOCOLS + * The query is always run against the FK table except when this is an + * update/insert trigger on the FK table itself - either + * RI_PLAN_CHECK_LOOKUPPK or RI_PLAN_CHECK_LOOKUPPK_NOCOLS */ if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK || qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK_NOCOLS) @@ -2882,9 +2891,9 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, char nulls[RI_MAX_NUMKEYS * 2]; /* - * The query is always run against the FK table except - * when this is an update/insert trigger on the FK table itself - - * either RI_PLAN_CHECK_LOOKUPPK or RI_PLAN_CHECK_LOOKUPPK_NOCOLS + * The query is always run against the FK table except when this is an + * update/insert trigger on the FK table itself - either + * RI_PLAN_CHECK_LOOKUPPK or RI_PLAN_CHECK_LOOKUPPK_NOCOLS */ if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK || qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK_NOCOLS) @@ -2893,10 +2902,10 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, query_rel = fk_rel; /* - * The values for the query are taken from the table on which the trigger - * is called - it is normally the other one with respect to query_rel. - * An exception is ri_Check_Pk_Match(), which uses the PK table for both - * (the case when constrname == NULL) + * The values for the query are taken from the table on which the + * trigger is called - it is normally the other one with respect to + * query_rel. An exception is ri_Check_Pk_Match(), which uses the PK + * table for both (the case when constrname == NULL) */ if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK && constrname != NULL) { @@ -2916,7 +2925,7 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, vals, nulls); if (old_tuple) ri_ExtractValues(qkey, key_idx, source_rel, old_tuple, - vals + qkey->nkeypairs, nulls + qkey->nkeypairs); + vals + qkey->nkeypairs, nulls + qkey->nkeypairs); } else { @@ -2930,9 +2939,9 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, /* * If this is a select query (e.g., for a 'no action' or 'restrict' - * trigger), we only need to see if there is a single row in the table, - * matching the key. Otherwise, limit = 0 - because we want the query to - * affect ALL the matching rows. + * trigger), we only need to see if there is a single row in the + * table, matching the key. Otherwise, limit = 0 - because we want + * the query to affect ALL the matching rows. */ limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0; @@ -2954,7 +2963,7 @@ ri_PerformCheck(RI_QueryKey *qkey, void *qplan, /* XXX wouldn't it be clearer to do this part at the caller? */ if (constrname && expect_OK == SPI_OK_SELECT && - (SPI_processed==0) == (qkey->constr_queryno==RI_PLAN_CHECK_LOOKUPPK)) + (SPI_processed == 0) == (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK)) ri_ReportViolation(qkey, constrname, pk_rel, fk_rel, new_tuple ? new_tuple : old_tuple, @@ -3049,9 +3058,9 @@ ri_ReportViolation(RI_QueryKey *qkey, const char *constrname, /* Get printable versions of the keys involved */ for (idx = 0; idx < qkey->nkeypairs; idx++) { - int fnum = qkey->keypair[idx][key_idx]; - char *name, - *val; + int fnum = qkey->keypair[idx][key_idx]; + char *name, + *val; name = SPI_fname(rel->rd_att, fnum); val = SPI_getvalue(violator, rel->rd_att, fnum); @@ -3075,22 +3084,22 @@ ri_ReportViolation(RI_QueryKey *qkey, const char *constrname, } if (onfk) - ereport(ERROR, - (errcode(ERRCODE_FOREIGN_KEY_VIOLATION), - errmsg("insert or update on \"%s\" violates foreign key constraint \"%s\"", - RelationGetRelationName(fk_rel), constrname), - errdetail("Key (%s)=(%s) is not present in \"%s\".", - key_names, key_values, - RelationGetRelationName(pk_rel)))); + ereport(ERROR, + (errcode(ERRCODE_FOREIGN_KEY_VIOLATION), + errmsg("insert or update on \"%s\" violates foreign key constraint \"%s\"", + RelationGetRelationName(fk_rel), constrname), + errdetail("Key (%s)=(%s) is not present in \"%s\".", + key_names, key_values, + RelationGetRelationName(pk_rel)))); else - ereport(ERROR, - (errcode(ERRCODE_FOREIGN_KEY_VIOLATION), - errmsg("update or delete on \"%s\" violates foreign key constraint \"%s\" on \"%s\"", - RelationGetRelationName(pk_rel), - constrname, RelationGetRelationName(fk_rel)), - errdetail("Key (%s)=(%s) is still referenced from \"%s\".", - key_names, key_values, - RelationGetRelationName(fk_rel)))); + ereport(ERROR, + (errcode(ERRCODE_FOREIGN_KEY_VIOLATION), + errmsg("update or delete on \"%s\" violates foreign key constraint \"%s\" on \"%s\"", + RelationGetRelationName(pk_rel), + constrname, RelationGetRelationName(fk_rel)), + errdetail("Key (%s)=(%s) is still referenced from \"%s\".", + key_names, key_values, + RelationGetRelationName(fk_rel)))); } /* ---------- diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index e2d9dd7ce9..dc0807fc13 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -3,7 +3,7 @@ * back to source text * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v 1.148 2003/08/01 18:00:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v 1.149 2003/08/04 00:43:26 momjian Exp $ * * This software is copyrighted by Jan Wieck - Hamburg. * @@ -77,18 +77,18 @@ */ /* Indent counts */ -#define PRETTYINDENT_STD 8 -#define PRETTYINDENT_JOIN 13 -#define PRETTYINDENT_JOIN_ON (PRETTYINDENT_JOIN-PRETTYINDENT_STD) -#define PRETTYINDENT_VAR 4 +#define PRETTYINDENT_STD 8 +#define PRETTYINDENT_JOIN 13 +#define PRETTYINDENT_JOIN_ON (PRETTYINDENT_JOIN-PRETTYINDENT_STD) +#define PRETTYINDENT_VAR 4 /* Pretty flags */ -#define PRETTYFLAG_PAREN 1 -#define PRETTYFLAG_INDENT 2 +#define PRETTYFLAG_PAREN 1 +#define PRETTYFLAG_INDENT 2 /* macro to test if pretty action needed */ -#define PRETTY_PAREN(context) ((context)->prettyFlags & PRETTYFLAG_PAREN) -#define PRETTY_INDENT(context) ((context)->prettyFlags & PRETTYFLAG_INDENT) +#define PRETTY_PAREN(context) ((context)->prettyFlags & PRETTYFLAG_PAREN) +#define PRETTY_INDENT(context) ((context)->prettyFlags & PRETTYFLAG_INDENT) /* ---------- @@ -146,21 +146,21 @@ static char *query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_c * ---------- */ static char *deparse_expression_pretty(Node *expr, List *dpcontext, - bool forceprefix, bool showimplicit, - int prettyFlags, int startIndent); + bool forceprefix, bool showimplicit, + int prettyFlags, int startIndent); static text *pg_do_getviewdef(Oid viewoid, int prettyFlags); static void decompile_column_index_array(Datum column_index_array, Oid relId, StringInfo buf); static Datum pg_get_ruledef_worker(Oid ruleoid, int prettyFlags); static Datum pg_get_indexdef_worker(Oid indexrelid, int colno, - int prettyFlags); + int prettyFlags); static Datum pg_get_constraintdef_worker(Oid constraintId, int prettyFlags); static Datum pg_get_expr_worker(text *expr, Oid relid, char *relname, - int prettyFlags); + int prettyFlags); static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, - int prettyFlags); + int prettyFlags); static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, - int prettyFlags); + int prettyFlags); static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int startIndent); static void get_select_query_def(Query *query, deparse_context *context, @@ -181,16 +181,16 @@ static void get_names_for_var(Var *var, deparse_context *context, char **schemaname, char **refname, char **attname); static RangeTblEntry *find_rte_by_refname(const char *refname, deparse_context *context); -static const char *get_simple_binary_op_name(OpExpr *expr); +static const char *get_simple_binary_op_name(OpExpr * expr); static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags); static void appendStringInfoSpaces(StringInfo buf, int count); static void appendContextKeyword(deparse_context *context, const char *str, - int indentBefore, int indentAfter, int indentPlus); + int indentBefore, int indentAfter, int indentPlus); static void get_rule_expr(Node *node, deparse_context *context, - bool showimplicit); -static void get_oper_expr(OpExpr *expr, deparse_context *context); -static void get_func_expr(FuncExpr *expr, deparse_context *context, - bool showimplicit); + bool showimplicit); +static void get_oper_expr(OpExpr * expr, deparse_context *context); +static void get_func_expr(FuncExpr * expr, deparse_context *context, + bool showimplicit); static void get_agg_expr(Aggref *aggref, deparse_context *context); static Node *strip_type_coercion(Node *expr, Oid resultType); static void get_const_expr(Const *constval, deparse_context *context); @@ -234,7 +234,7 @@ pg_get_ruledef_ext(PG_FUNCTION_ARGS) bool pretty = PG_GETARG_BOOL(1); int prettyFlags; - prettyFlags = pretty ? PRETTYFLAG_PAREN|PRETTYFLAG_INDENT : 0; + prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0; return pg_get_ruledef_worker(ruleoid, prettyFlags); } @@ -345,7 +345,7 @@ pg_get_viewdef_ext(PG_FUNCTION_ARGS) text *ruledef; int prettyFlags; - prettyFlags = pretty ? PRETTYFLAG_PAREN|PRETTYFLAG_INDENT : 0; + prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0; ruledef = pg_do_getviewdef(viewoid, prettyFlags); PG_RETURN_TEXT_P(ruledef); } @@ -379,7 +379,7 @@ pg_get_viewdef_name_ext(PG_FUNCTION_ARGS) Oid viewoid; text *ruledef; - prettyFlags = pretty ? PRETTYFLAG_PAREN|PRETTYFLAG_INDENT : 0; + prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0; viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname, "get_viewdef")); viewoid = RangeVarGetRelid(viewrel, false); @@ -481,7 +481,7 @@ pg_get_triggerdef(PG_FUNCTION_ARGS) ScanKeyData skey[1]; SysScanDesc tgscan; int findx = 0; - char *tgname; + char *tgname; /* * Fetch the pg_trigger tuple by the Oid of the trigger @@ -544,7 +544,7 @@ pg_get_triggerdef(PG_FUNCTION_ARGS) { if (trigrec->tgconstrrelid != InvalidOid) appendStringInfo(&buf, "FROM %s ", - generate_relation_name(trigrec->tgconstrrelid)); + generate_relation_name(trigrec->tgconstrrelid)); if (!trigrec->tgdeferrable) appendStringInfo(&buf, "NOT "); appendStringInfo(&buf, "DEFERRABLE INITIALLY "); @@ -633,11 +633,11 @@ Datum pg_get_indexdef_ext(PG_FUNCTION_ARGS) { Oid indexrelid = PG_GETARG_OID(0); - int32 colno = PG_GETARG_INT32(1); + int32 colno = PG_GETARG_INT32(1); bool pretty = PG_GETARG_BOOL(2); int prettyFlags; - prettyFlags = pretty ? PRETTYFLAG_PAREN|PRETTYFLAG_INDENT : 0; + prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0; return pg_get_indexdef_worker(indexrelid, colno, prettyFlags); } @@ -696,9 +696,9 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) amrec = (Form_pg_am) GETSTRUCT(ht_am); /* - * Get the index expressions, if any. (NOTE: we do not use the relcache - * versions of the expressions and predicate, because we want to display - * non-const-folded expressions.) + * Get the index expressions, if any. (NOTE: we do not use the + * relcache versions of the expressions and predicate, because we want + * to display non-const-folded expressions.) */ if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs)) { @@ -726,11 +726,11 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) initStringInfo(&buf); if (!colno) - appendStringInfo(&buf, "CREATE %sINDEX %s ON %s USING %s (", - idxrec->indisunique ? "UNIQUE " : "", - quote_identifier(NameStr(idxrelrec->relname)), - generate_relation_name(indrelid), - quote_identifier(NameStr(amrec->amname))); + appendStringInfo(&buf, "CREATE %sINDEX %s ON %s USING %s (", + idxrec->indisunique ? "UNIQUE " : "", + quote_identifier(NameStr(idxrelrec->relname)), + generate_relation_name(indrelid), + quote_identifier(NameStr(amrec->amname))); /* * Report the indexed attributes @@ -741,7 +741,7 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) AttrNumber attnum = idxrec->indkey[keyno]; if (!colno) - appendStringInfo(&buf, sep); + appendStringInfo(&buf, sep); sep = ", "; if (attnum != 0) @@ -750,8 +750,8 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) char *attname; attname = get_relid_attribute_name(indrelid, attnum); - if (!colno || colno == keyno+1) - appendStringInfo(&buf, "%s", quote_identifier(attname)); + if (!colno || colno == keyno + 1) + appendStringInfo(&buf, "%s", quote_identifier(attname)); keycoltype = get_atttype(indrelid, attnum); } else @@ -766,13 +766,13 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) /* Deparse */ str = deparse_expression_pretty(indexkey, context, false, false, prettyFlags, 0); - if (!colno || colno == keyno+1) + if (!colno || colno == keyno + 1) { - /* Need parens if it's not a bare function call */ - if (indexkey && IsA(indexkey, FuncExpr) && + /* Need parens if it's not a bare function call */ + if (indexkey && IsA(indexkey, FuncExpr) && ((FuncExpr *) indexkey)->funcformat == COERCE_EXPLICIT_CALL) appendStringInfo(&buf, "%s", str); - else + else appendStringInfo(&buf, "(%s)", str); } keycoltype = exprType(indexkey); @@ -782,19 +782,19 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) * Add the operator class name */ if (!colno) - get_opclass_name(idxrec->indclass[keyno], keycoltype, - &buf); + get_opclass_name(idxrec->indclass[keyno], keycoltype, + &buf); } if (!colno) { - appendStringInfoChar(&buf, ')'); + appendStringInfoChar(&buf, ')'); - /* - * If it's a partial index, decompile and append the predicate - */ - if (!heap_attisnull(ht_idx, Anum_pg_index_indpred)) - { + /* + * If it's a partial index, decompile and append the predicate + */ + if (!heap_attisnull(ht_idx, Anum_pg_index_indpred)) + { Node *node; Datum predDatum; bool isnull; @@ -810,9 +810,9 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) pfree(predString); /* - * If top level is a List, assume it is an implicit-AND structure, - * and convert to explicit AND. This is needed for partial index - * predicates. + * If top level is a List, assume it is an implicit-AND + * structure, and convert to explicit AND. This is needed for + * partial index predicates. */ if (node && IsA(node, List)) node = (Node *) make_ands_explicit((List *) node); @@ -820,7 +820,7 @@ pg_get_indexdef_worker(Oid indexrelid, int colno, int prettyFlags) str = deparse_expression_pretty(node, context, false, false, prettyFlags, 0); appendStringInfo(&buf, " WHERE %s", str); - } + } } /* @@ -862,7 +862,7 @@ pg_get_constraintdef_ext(PG_FUNCTION_ARGS) bool pretty = PG_GETARG_BOOL(1); int prettyFlags; - prettyFlags = pretty ? PRETTYFLAG_PAREN|PRETTYFLAG_INDENT : 0; + prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0; return pg_get_constraintdef_worker(constraintId, prettyFlags); } @@ -958,7 +958,7 @@ pg_get_constraintdef_worker(Oid constraintId, int prettyFlags) switch (conForm->confupdtype) { case FKCONSTR_ACTION_NOACTION: - string = NULL; /* suppress default */ + string = NULL; /* suppress default */ break; case FKCONSTR_ACTION_RESTRICT: string = "RESTRICT"; @@ -984,7 +984,7 @@ pg_get_constraintdef_worker(Oid constraintId, int prettyFlags) switch (conForm->confdeltype) { case FKCONSTR_ACTION_NOACTION: - string = NULL; /* suppress default */ + string = NULL; /* suppress default */ break; case FKCONSTR_ACTION_RESTRICT: string = "RESTRICT"; @@ -1049,8 +1049,11 @@ pg_get_constraintdef_worker(Oid constraintId, int prettyFlags) List *context; /* Start off the constraint definition */ - /* The consrc for CHECK constraints always seems to be - bracketed, so we don't add extra brackets here. */ + + /* + * The consrc for CHECK constraints always seems to be + * bracketed, so we don't add extra brackets here. + */ appendStringInfo(&buf, "CHECK "); /* Fetch constraint source */ @@ -1064,9 +1067,9 @@ pg_get_constraintdef_worker(Oid constraintId, int prettyFlags) expr = stringToNode(conbin); /* - * If top level is a List, assume it is an implicit-AND structure, and - * convert to explicit AND. This is needed for partial index - * predicates. + * If top level is a List, assume it is an implicit-AND + * structure, and convert to explicit AND. This is needed + * for partial index predicates. */ if (expr && IsA(expr, List)) expr = (Node *) make_ands_explicit((List *) expr); @@ -1076,9 +1079,11 @@ pg_get_constraintdef_worker(Oid constraintId, int prettyFlags) context = deparse_context_for(get_rel_name(conForm->conrelid), conForm->conrelid); else + /* - * Since VARNOs aren't allowed in domain constraints, relation context - * isn't required as anything other than a shell. + * Since VARNOs aren't allowed in domain constraints, + * relation context isn't required as anything other + * than a shell. */ context = deparse_context_for(get_typname(conForm->contypid), InvalidOid); @@ -1087,7 +1092,7 @@ pg_get_constraintdef_worker(Oid constraintId, int prettyFlags) prettyFlags, 0); /* Append the constraint source */ - appendStringInfoString(&buf, consrc); + appendStringInfoString(&buf, consrc); break; } @@ -1095,7 +1100,7 @@ pg_get_constraintdef_worker(Oid constraintId, int prettyFlags) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("unsupported constraint type \"%c\"", - conForm->contype))); + conForm->contype))); break; } @@ -1162,8 +1167,8 @@ decompile_column_index_array(Datum column_index_array, Oid relId, Datum pg_get_expr(PG_FUNCTION_ARGS) { - text *expr = PG_GETARG_TEXT_P(0); - Oid relid = PG_GETARG_OID(1); + text *expr = PG_GETARG_TEXT_P(0); + Oid relid = PG_GETARG_OID(1); char *relname; /* Get the name for the relation */ @@ -1177,13 +1182,13 @@ pg_get_expr(PG_FUNCTION_ARGS) Datum pg_get_expr_ext(PG_FUNCTION_ARGS) { - text *expr = PG_GETARG_TEXT_P(0); - Oid relid = PG_GETARG_OID(1); + text *expr = PG_GETARG_TEXT_P(0); + Oid relid = PG_GETARG_OID(1); bool pretty = PG_GETARG_BOOL(2); int prettyFlags; char *relname; - prettyFlags = pretty ? PRETTYFLAG_PAREN|PRETTYFLAG_INDENT : 0; + prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0; /* Get the name for the relation */ relname = get_rel_name(relid); @@ -1276,7 +1281,7 @@ char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit) { - return deparse_expression_pretty(expr, dpcontext, forceprefix, + return deparse_expression_pretty(expr, dpcontext, forceprefix, showimplicit, 0, 0); } @@ -1292,7 +1297,7 @@ deparse_expression(Node *expr, List *dpcontext, * forceprefix is TRUE to force all Vars to be prefixed with their table names. * * showimplicit is TRUE to force all implicit casts to be shown explicitly. - * + * * tries to pretty up the output according to prettyFlags and startIndent. * * The result is a palloc'd string. @@ -1523,9 +1528,9 @@ make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, quote_identifier(rulename)); if (prettyFlags & PRETTYFLAG_INDENT) - appendStringInfoString(buf, "\n ON "); + appendStringInfoString(buf, "\n ON "); else - appendStringInfoString(buf, " ON "); + appendStringInfoString(buf, " ON "); /* The event the rule is fired for */ switch (ev_type) @@ -1550,7 +1555,7 @@ make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("rule \"%s\" has unsupported event type %d", - rulename, ev_type))); + rulename, ev_type))); break; } @@ -1572,7 +1577,7 @@ make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, deparse_namespace dpns; if (prettyFlags & PRETTYFLAG_INDENT) - appendStringInfoString(buf, "\n "); + appendStringInfoString(buf, "\n "); appendStringInfo(buf, " WHERE "); qual = stringToNode(ev_qual); @@ -1621,9 +1626,9 @@ make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, query = (Query *) lfirst(action); get_query_def(query, buf, NIL, NULL, prettyFlags, 0); if (prettyFlags) - appendStringInfo(buf, ";\n"); + appendStringInfo(buf, ";\n"); else - appendStringInfo(buf, "; "); + appendStringInfo(buf, "; "); } appendStringInfo(buf, ");"); } @@ -1803,8 +1808,8 @@ get_select_query_def(Query *query, deparse_context *context, /* Add the ORDER BY clause if given */ if (query->sortClause != NIL) { - appendContextKeyword(context, " ORDER BY ", - -PRETTYINDENT_STD, PRETTYINDENT_STD, 1); + appendContextKeyword(context, " ORDER BY ", + -PRETTYINDENT_STD, PRETTYINDENT_STD, 1); sep = ""; foreach(l, query->sortClause) { @@ -1863,8 +1868,8 @@ get_basic_select_query(Query *query, deparse_context *context, */ if (PRETTY_INDENT(context)) { - context->indentLevel += PRETTYINDENT_STD; - appendStringInfoChar(buf, ' '); + context->indentLevel += PRETTYINDENT_STD; + appendStringInfoChar(buf, ' '); } appendStringInfo(buf, "SELECT"); @@ -1995,20 +2000,20 @@ get_setop_query(Node *setOp, Query *query, deparse_context *context, else if (IsA(setOp, SetOperationStmt)) { SetOperationStmt *op = (SetOperationStmt *) setOp; - bool need_paren; + bool need_paren; need_paren = (PRETTY_PAREN(context) ? !IsA(op->rarg, RangeTblRef) : true); if (!PRETTY_PAREN(context)) - appendStringInfoString(buf, "(("); + appendStringInfoString(buf, "(("); get_setop_query(op->larg, query, context, resultDesc); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); if (!PRETTY_INDENT(context)) - appendStringInfoChar(buf, ' '); + appendStringInfoChar(buf, ' '); switch (op->op) { case SETOP_UNION: @@ -2031,29 +2036,29 @@ get_setop_query(Node *setOp, Query *query, deparse_context *context, appendStringInfo(buf, "ALL "); if (PRETTY_INDENT(context)) - appendStringInfoChar(buf, '\n'); + appendStringInfoChar(buf, '\n'); if (PRETTY_PAREN(context)) { - if (need_paren) - { + if (need_paren) + { appendStringInfoChar(buf, '('); if (PRETTY_INDENT(context)) appendStringInfoChar(buf, '\n'); - } + } } else - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_setop_query(op->rarg, query, context, resultDesc); if (PRETTY_PAREN(context)) { - if (need_paren) + if (need_paren) appendStringInfoChar(buf, ')'); } else - appendStringInfoString(buf, "))"); + appendStringInfoString(buf, "))"); } else { @@ -2129,8 +2134,8 @@ get_insert_query_def(Query *query, deparse_context *context) if (PRETTY_INDENT(context)) { - context->indentLevel += PRETTYINDENT_STD; - appendStringInfoChar(buf, ' '); + context->indentLevel += PRETTYINDENT_STD; + appendStringInfoChar(buf, ' '); } appendStringInfo(buf, "INSERT INTO %s", generate_relation_name(rte->relid)); @@ -2194,8 +2199,8 @@ get_update_query_def(Query *query, deparse_context *context) Assert(rte->rtekind == RTE_RELATION); if (PRETTY_INDENT(context)) { - appendStringInfoChar(buf, ' '); - context->indentLevel += PRETTYINDENT_STD; + appendStringInfoChar(buf, ' '); + context->indentLevel += PRETTYINDENT_STD; } appendStringInfo(buf, "UPDATE %s%s SET ", only_marker(rte), @@ -2254,8 +2259,8 @@ get_delete_query_def(Query *query, deparse_context *context) Assert(rte->rtekind == RTE_RELATION); if (PRETTY_INDENT(context)) { - context->indentLevel += PRETTYINDENT_STD; - appendStringInfoChar(buf, ' '); + context->indentLevel += PRETTYINDENT_STD; + appendStringInfoChar(buf, ' '); } appendStringInfo(buf, "DELETE FROM %s%s", only_marker(rte), @@ -2434,7 +2439,7 @@ find_rte_by_refname(const char *refname, deparse_context *context) * will return single char binary operator name, or NULL if it's not */ static const char * -get_simple_binary_op_name(OpExpr *expr) +get_simple_binary_op_name(OpExpr * expr) { List *args = expr->args; @@ -2447,7 +2452,7 @@ get_simple_binary_op_name(OpExpr *expr) op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2)); if (strlen(op) == 1) - return op; + return op; } return NULL; } @@ -2456,17 +2461,17 @@ get_simple_binary_op_name(OpExpr *expr) /* * isSimpleNode - check if given node is simple (doesn't need parenthesizing) * - * true : simple in the context of parent node's type - * false : not simple + * true : simple in the context of parent node's type + * false : not simple */ static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags) { - if (!node) + if (!node) return false; - switch (nodeTag(node)) - { + switch (nodeTag(node)) + { case T_Var: case T_Const: case T_Param: @@ -2484,11 +2489,12 @@ isSimpleNode(Node *node, Node *parentNode, int prettyFlags) /* function-like: name(..) or name[..] */ return true; - /* CASE keywords act as parentheses */ + /* CASE keywords act as parentheses */ case T_CaseExpr: return true; case T_FieldSelect: + /* * appears simple since . has top precedence, unless parent is * T_FieldSelect itself! @@ -2497,61 +2503,61 @@ isSimpleNode(Node *node, Node *parentNode, int prettyFlags) case T_CoerceToDomain: /* maybe simple, check args */ - return isSimpleNode((Node*) ((CoerceToDomain*)node)->arg, + return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg, node, prettyFlags); case T_RelabelType: - return isSimpleNode((Node*) ((RelabelType*)node)->arg, + return isSimpleNode((Node *) ((RelabelType *) node)->arg, node, prettyFlags); case T_OpExpr: - { - /* depends on parent node type; needs further checking */ - if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr)) { - const char *op; - const char *parentOp; - bool is_lopriop; - bool is_hipriop; - bool is_lopriparent; - bool is_hipriparent; + /* depends on parent node type; needs further checking */ + if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr)) + { + const char *op; + const char *parentOp; + bool is_lopriop; + bool is_hipriop; + bool is_lopriparent; + bool is_hipriparent; + + op = get_simple_binary_op_name((OpExpr *) node); + if (!op) + return false; + + /* We know only the basic operators + - and * / % */ + is_lopriop = (strchr("+-", *op) != NULL); + is_hipriop = (strchr("*/%", *op) != NULL); + if (!(is_lopriop || is_hipriop)) + return false; + + parentOp = get_simple_binary_op_name((OpExpr *) parentNode); + if (!parentOp) + return false; + + is_lopriparent = (strchr("+-", *parentOp) != NULL); + is_hipriparent = (strchr("*/%", *parentOp) != NULL); + if (!(is_lopriparent || is_hipriparent)) + return false; + + if (is_hipriop && is_lopriparent) + return true; /* op binds tighter than parent */ + + if (is_lopriop && is_hipriparent) + return false; + + /* + * Operators are same priority --- can skip parens + * only if we have (a - b) - c, not a - (b - c). + */ + if (node == (Node *) lfirst(((OpExpr *) parentNode)->args)) + return true; - op = get_simple_binary_op_name((OpExpr*) node); - if (!op) return false; - - /* We know only the basic operators + - and * / % */ - is_lopriop = (strchr("+-", *op) != NULL); - is_hipriop = (strchr("*/%", *op) != NULL); - if (!(is_lopriop || is_hipriop)) - return false; - - parentOp = get_simple_binary_op_name((OpExpr*) parentNode); - if (!parentOp) - return false; - - is_lopriparent = (strchr("+-", *parentOp) != NULL); - is_hipriparent = (strchr("*/%", *parentOp) != NULL); - if (!(is_lopriparent || is_hipriparent)) - return false; - - if (is_hipriop && is_lopriparent) - return true; /* op binds tighter than parent */ - - if (is_lopriop && is_hipriparent) - return false; - - /* - * Operators are same priority --- can skip parens only - * if we have (a - b) - c, not a - (b - c). - */ - if (node == (Node *) lfirst(((OpExpr *) parentNode)->args)) - return true; - - return false; + } + /* else do the same stuff as for T_SubLink et al. */ + /* FALL THROUGH */ } - /* else do the same stuff as for T_SubLink et al. */ - /* FALL THROUGH */ - } case T_SubLink: case T_NullTest: @@ -2560,22 +2566,22 @@ isSimpleNode(Node *node, Node *parentNode, int prettyFlags) switch (nodeTag(parentNode)) { case T_FuncExpr: - { - /* special handling for casts */ - CoercionForm type = ((FuncExpr*)parentNode)->funcformat; + { + /* special handling for casts */ + CoercionForm type = ((FuncExpr *) parentNode)->funcformat; - if (type == COERCE_EXPLICIT_CAST || - type == COERCE_IMPLICIT_CAST) - return false; - return true; /* own parentheses */ - } - case T_BoolExpr: /* lower precedence */ - case T_ArrayRef: /* other separators */ - case T_ArrayExpr: /* other separators */ - case T_CoalesceExpr: /* own parentheses */ - case T_NullIfExpr: /* other separators */ - case T_Aggref: /* own parentheses */ - case T_CaseExpr: /* other separators */ + if (type == COERCE_EXPLICIT_CAST || + type == COERCE_IMPLICIT_CAST) + return false; + return true; /* own parentheses */ + } + case T_BoolExpr: /* lower precedence */ + case T_ArrayRef: /* other separators */ + case T_ArrayExpr: /* other separators */ + case T_CoalesceExpr: /* own parentheses */ + case T_NullIfExpr: /* other separators */ + case T_Aggref: /* own parentheses */ + case T_CaseExpr: /* other separators */ return true; default: return false; @@ -2590,8 +2596,8 @@ isSimpleNode(Node *node, Node *parentNode, int prettyFlags) BoolExprType type; BoolExprType parentType; - type = ((BoolExpr*)node)->boolop; - parentType = ((BoolExpr*)parentNode)->boolop; + type = ((BoolExpr *) node)->boolop; + parentType = ((BoolExpr *) parentNode)->boolop; switch (type) { case NOT_EXPR: @@ -2607,21 +2613,21 @@ isSimpleNode(Node *node, Node *parentNode, int prettyFlags) } return false; case T_FuncExpr: - { - /* special handling for casts */ - CoercionForm type=((FuncExpr*)parentNode)->funcformat; + { + /* special handling for casts */ + CoercionForm type = ((FuncExpr *) parentNode)->funcformat; - if (type == COERCE_EXPLICIT_CAST || - type == COERCE_IMPLICIT_CAST) - return false; - return true; /* own parentheses */ - } - case T_ArrayRef: /* other separators */ - case T_ArrayExpr: /* other separators */ - case T_CoalesceExpr: /* own parentheses */ - case T_NullIfExpr: /* other separators */ - case T_Aggref: /* own parentheses */ - case T_CaseExpr: /* other separators */ + if (type == COERCE_EXPLICIT_CAST || + type == COERCE_IMPLICIT_CAST) + return false; + return true; /* own parentheses */ + } + case T_ArrayRef: /* other separators */ + case T_ArrayExpr: /* other separators */ + case T_CoalesceExpr: /* own parentheses */ + case T_NullIfExpr: /* other separators */ + case T_Aggref: /* own parentheses */ + case T_CaseExpr: /* other separators */ return true; default: return false; @@ -2629,9 +2635,9 @@ isSimpleNode(Node *node, Node *parentNode, int prettyFlags) default: break; - } - /* those we don't know: in dubio complexo */ - return false; + } + /* those we don't know: in dubio complexo */ + return false; } @@ -2641,7 +2647,7 @@ isSimpleNode(Node *node, Node *parentNode, int prettyFlags) static void appendStringInfoSpaces(StringInfo buf, int count) { - while (count-- > 0) + while (count-- > 0) appendStringInfoChar(buf, ' '); } @@ -2655,8 +2661,8 @@ static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus) { - if (PRETTY_INDENT(context)) - { + if (PRETTY_INDENT(context)) + { context->indentLevel += indentBefore; if (context->indentLevel < 0) context->indentLevel = 0; @@ -2664,20 +2670,20 @@ appendContextKeyword(deparse_context *context, const char *str, appendStringInfoChar(context->buf, '\n'); appendStringInfoSpaces(context->buf, context->indentLevel + indentPlus); - } + } - appendStringInfoString(context->buf, str); + appendStringInfoString(context->buf, str); - if (PRETTY_INDENT(context)) - { + if (PRETTY_INDENT(context)) + { context->indentLevel += indentAfter; if (context->indentLevel < 0) context->indentLevel = 0; - } + } } /* - * get_rule_expr_paren - deparse expr using get_rule_expr, + * get_rule_expr_paren - deparse expr using get_rule_expr, * embracing the string with parentheses if necessary for prettyPrint. * * Never embrace if prettyFlags=0, because it's done in the calling node. @@ -2688,21 +2694,21 @@ appendContextKeyword(deparse_context *context, const char *str, * added. */ static void -get_rule_expr_paren(Node *node, deparse_context *context, +get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode) { - bool need_paren; + bool need_paren; need_paren = PRETTY_PAREN(context) && !isSimpleNode(node, parentNode, context->prettyFlags); if (need_paren) - appendStringInfoChar(context->buf, '('); + appendStringInfoChar(context->buf, '('); get_rule_expr(node, context, showimplicit); if (need_paren) - appendStringInfoChar(context->buf, ')'); + appendStringInfoChar(context->buf, ')'); } @@ -2812,6 +2818,7 @@ get_rule_expr(Node *node, deparse_context *context, */ if (aref->refassgnexpr) context->varprefix = false; + /* * Parenthesize the argument unless it's a simple Var. */ @@ -2862,12 +2869,12 @@ get_rule_expr(Node *node, deparse_context *context, Node *arg2 = (Node *) lsecond(args); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren(arg1, context, true, node); appendStringInfo(buf, " IS DISTINCT FROM "); get_rule_expr_paren(arg2, context, true, node); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); } break; @@ -2879,17 +2886,17 @@ get_rule_expr(Node *node, deparse_context *context, Node *arg2 = (Node *) lsecond(args); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren(arg1, context, true, node); appendStringInfo(buf, " %s %s (", generate_operator_name(expr->opno, exprType(arg1), - get_element_type(exprType(arg2))), + get_element_type(exprType(arg2))), expr->useOr ? "ANY" : "ALL"); get_rule_expr_paren(arg2, context, true, node); appendStringInfoChar(buf, ')'); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); } break; @@ -2902,7 +2909,7 @@ get_rule_expr(Node *node, deparse_context *context, { case AND_EXPR: if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren((Node *) lfirst(args), context, false, node); while ((args = lnext(args)) != NIL) @@ -2912,12 +2919,12 @@ get_rule_expr(Node *node, deparse_context *context, false, node); } if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); break; case OR_EXPR: if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren((Node *) lfirst(args), context, false, node); while ((args = lnext(args)) != NIL) @@ -2927,17 +2934,17 @@ get_rule_expr(Node *node, deparse_context *context, false, node); } if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); break; case NOT_EXPR: if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); appendStringInfo(buf, "NOT "); get_rule_expr_paren((Node *) lfirst(args), context, false, node); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); break; default: @@ -2954,9 +2961,9 @@ get_rule_expr(Node *node, deparse_context *context, case T_SubPlan: { /* - * We cannot see an already-planned subplan in - * rule deparsing, only while EXPLAINing a query - * plan. For now, just punt. + * We cannot see an already-planned subplan in rule + * deparsing, only while EXPLAINing a query plan. For now, + * just punt. */ if (((SubPlan *) node)->useHashTable) appendStringInfo(buf, "(hashed subplan)"); @@ -2986,10 +2993,10 @@ get_rule_expr(Node *node, deparse_context *context, * are *not* simple. So, always use parenthesized syntax. */ if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren((Node *) fselect->arg, context, true, node); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); appendStringInfo(buf, ".%s", quote_identifier(fieldname)); } break; @@ -2997,7 +3004,7 @@ get_rule_expr(Node *node, deparse_context *context, case T_RelabelType: { RelabelType *relabel = (RelabelType *) node; - Node *arg = (Node *) relabel->arg; + Node *arg = (Node *) relabel->arg; if (relabel->relabelformat == COERCE_IMPLICIT_CAST && !showimplicit) @@ -3008,21 +3015,22 @@ get_rule_expr(Node *node, deparse_context *context, else { /* - * Strip off any type coercions on the input, so we don't - * print redundancies like x::bpchar::character(8). + * Strip off any type coercions on the input, so we + * don't print redundancies like + * x::bpchar::character(8). * * XXX Are there any cases where this is a bad idea? */ arg = strip_type_coercion(arg, relabel->resulttype); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren(arg, context, showimplicit, node); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); appendStringInfo(buf, "::%s", format_type_with_typemod(relabel->resulttype, - relabel->resulttypmod)); + relabel->resulttypmod)); } } break; @@ -3047,12 +3055,12 @@ get_rule_expr(Node *node, deparse_context *context, get_rule_expr((Node *) when->result, context, true); } if (!PRETTY_INDENT(context)) - appendStringInfoChar(buf, ' '); + appendStringInfoChar(buf, ' '); appendContextKeyword(context, "ELSE ", 0, 0, 0); get_rule_expr((Node *) caseexpr->defresult, context, true); if (!PRETTY_INDENT(context)) - appendStringInfoChar(buf, ' '); + appendStringInfoChar(buf, ' '); appendContextKeyword(context, "END", -PRETTYINDENT_VAR, 0, 0); } @@ -3060,15 +3068,15 @@ get_rule_expr(Node *node, deparse_context *context, case T_ArrayExpr: { - ArrayExpr *arrayexpr = (ArrayExpr *) node; - List *element; - char *sep; + ArrayExpr *arrayexpr = (ArrayExpr *) node; + List *element; + char *sep; appendStringInfo(buf, "ARRAY["); sep = ""; foreach(element, arrayexpr->elements) { - Node *e = (Node *) lfirst(element); + Node *e = (Node *) lfirst(element); appendStringInfo(buf, sep); get_rule_expr(e, context, true); @@ -3077,18 +3085,18 @@ get_rule_expr(Node *node, deparse_context *context, appendStringInfo(buf, "]"); } break; - + case T_CoalesceExpr: { CoalesceExpr *coalesceexpr = (CoalesceExpr *) node; - List *arg; - char *sep; + List *arg; + char *sep; appendStringInfo(buf, "COALESCE("); sep = ""; foreach(arg, coalesceexpr->args) { - Node *e = (Node *) lfirst(arg); + Node *e = (Node *) lfirst(arg); appendStringInfo(buf, sep); get_rule_expr(e, context, true); @@ -3097,18 +3105,18 @@ get_rule_expr(Node *node, deparse_context *context, appendStringInfo(buf, ")"); } break; - + case T_NullIfExpr: { NullIfExpr *nullifexpr = (NullIfExpr *) node; - List *arg; - char *sep; + List *arg; + char *sep; appendStringInfo(buf, "NULLIF("); sep = ""; foreach(arg, nullifexpr->args) { - Node *e = (Node *) lfirst(arg); + Node *e = (Node *) lfirst(arg); appendStringInfo(buf, sep); get_rule_expr(e, context, true); @@ -3123,7 +3131,7 @@ get_rule_expr(Node *node, deparse_context *context, NullTest *ntest = (NullTest *) node; if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren((Node *) ntest->arg, context, true, node); switch (ntest->nulltesttype) { @@ -3138,7 +3146,7 @@ get_rule_expr(Node *node, deparse_context *context, (int) ntest->nulltesttype); } if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); } break; @@ -3147,7 +3155,7 @@ get_rule_expr(Node *node, deparse_context *context, BooleanTest *btest = (BooleanTest *) node; if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren((Node *) btest->arg, context, false, node); switch (btest->booltesttype) { @@ -3174,14 +3182,14 @@ get_rule_expr(Node *node, deparse_context *context, (int) btest->booltesttype); } if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); } break; case T_CoerceToDomain: { CoerceToDomain *ctest = (CoerceToDomain *) node; - Node *arg = (Node *) ctest->arg; + Node *arg = (Node *) ctest->arg; /* * Any implicit coercion at the top level of the argument @@ -3197,13 +3205,13 @@ get_rule_expr(Node *node, deparse_context *context, else { if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr_paren(arg, context, false, node); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); appendStringInfo(buf, "::%s", - format_type_with_typemod(ctest->resulttype, - ctest->resulttypmod)); + format_type_with_typemod(ctest->resulttype, + ctest->resulttypmod)); } } break; @@ -3227,25 +3235,26 @@ get_rule_expr(Node *node, deparse_context *context, * get_oper_expr - Parse back an OpExpr node */ static void -get_oper_expr(OpExpr *expr, deparse_context *context) +get_oper_expr(OpExpr * expr, deparse_context *context) { StringInfo buf = context->buf; Oid opno = expr->opno; List *args = expr->args; if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); if (length(args) == 2) { /* binary operator */ Node *arg1 = (Node *) lfirst(args); Node *arg2 = (Node *) lsecond(args); - get_rule_expr_paren(arg1, context, true, (Node*)expr); + + get_rule_expr_paren(arg1, context, true, (Node *) expr); appendStringInfo(buf, " %s ", generate_operator_name(opno, exprType(arg1), exprType(arg2))); - get_rule_expr_paren(arg2, context, true, (Node*)expr); + get_rule_expr_paren(arg2, context, true, (Node *) expr); } else { @@ -3267,10 +3276,10 @@ get_oper_expr(OpExpr *expr, deparse_context *context) generate_operator_name(opno, InvalidOid, exprType(arg))); - get_rule_expr_paren(arg, context, true, (Node*)expr); + get_rule_expr_paren(arg, context, true, (Node *) expr); break; case 'r': - get_rule_expr_paren(arg, context, true, (Node*)expr); + get_rule_expr_paren(arg, context, true, (Node *) expr); appendStringInfo(buf, " %s", generate_operator_name(opno, exprType(arg), @@ -3282,14 +3291,14 @@ get_oper_expr(OpExpr *expr, deparse_context *context) ReleaseSysCache(tp); } if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); } /* * get_func_expr - Parse back a FuncExpr node */ static void -get_func_expr(FuncExpr *expr, deparse_context *context, +get_func_expr(FuncExpr * expr, deparse_context *context, bool showimplicit) { StringInfo buf = context->buf; @@ -3301,18 +3310,19 @@ get_func_expr(FuncExpr *expr, deparse_context *context, /* * If the function call came from an implicit coercion, then just show - * the first argument --- unless caller wants to see implicit coercions. + * the first argument --- unless caller wants to see implicit + * coercions. */ if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit) { get_rule_expr_paren((Node *) lfirst(expr->args), context, - showimplicit, (Node*)expr); + showimplicit, (Node *) expr); return; } /* - * If the function call came from a cast, then show - * the first argument plus an explicit cast operation. + * If the function call came from a cast, then show the first argument + * plus an explicit cast operation. */ if (expr->funcformat == COERCE_EXPLICIT_CAST || expr->funcformat == COERCE_IMPLICIT_CAST) @@ -3333,12 +3343,12 @@ get_func_expr(FuncExpr *expr, deparse_context *context, arg = strip_type_coercion(arg, rettype); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); - get_rule_expr_paren(arg, context, showimplicit, (Node*)expr); + appendStringInfoChar(buf, '('); + get_rule_expr_paren(arg, context, showimplicit, (Node *) expr); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); appendStringInfo(buf, "::%s", - format_type_with_typemod(rettype, coercedTypmod)); + format_type_with_typemod(rettype, coercedTypmod)); return; } @@ -3493,7 +3503,7 @@ get_const_expr(Const *constval, deparse_context *context) { appendStringInfoString(buf, extval); if (strcspn(extval, "eE.") != strlen(extval)) - isfloat = true; /* it looks like a float */ + isfloat = true; /* it looks like a float */ } else appendStringInfo(buf, "'%s'", extval); @@ -3541,8 +3551,8 @@ get_const_expr(Const *constval, deparse_context *context) /* * Append ::typename unless the constant will be implicitly typed as - * the right type when it is read in. XXX this code has to be kept - * in sync with the behavior of the parser, especially make_const. + * the right type when it is read in. XXX this code has to be kept in + * sync with the behavior of the parser, especially make_const. */ switch (constval->consttype) { @@ -3562,7 +3572,7 @@ get_const_expr(Const *constval, deparse_context *context) } if (needlabel) appendStringInfo(buf, "::%s", - format_type_with_typemod(constval->consttype, -1)); + format_type_with_typemod(constval->consttype, -1)); ReleaseSysCache(typetup); } @@ -3609,10 +3619,10 @@ get_sublink_expr(SubLink *sublink, deparse_context *context) need_paren = true; /* - * XXX we regurgitate the originally given operator name, with or without - * schema qualification. This is not necessarily 100% right but it's - * the best we can do, since the operators actually used might not all - * be in the same schema. + * XXX we regurgitate the originally given operator name, with or + * without schema qualification. This is not necessarily 100% right + * but it's the best we can do, since the operators actually used + * might not all be in the same schema. */ switch (sublink->subLinkType) { @@ -3705,12 +3715,12 @@ get_from_clause(Query *query, deparse_context *context) if (first) { - appendContextKeyword(context, " FROM ", + appendContextKeyword(context, " FROM ", -PRETTYINDENT_STD, PRETTYINDENT_STD, 2); first = false; } else - appendStringInfoString(buf, ", "); + appendStringInfoString(buf, ", "); get_from_clause_item(jtnode, query, context); } @@ -3739,7 +3749,7 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context) case RTE_SUBQUERY: /* Subquery RTE */ appendStringInfoChar(buf, '('); - get_query_def(rte->subquery, buf, context->namespaces, NULL, + get_query_def(rte->subquery, buf, context->namespaces, NULL, context->prettyFlags, context->indentLevel); appendStringInfoChar(buf, ')'); break; @@ -3796,22 +3806,22 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context) else if (IsA(jtnode, JoinExpr)) { JoinExpr *j = (JoinExpr *) jtnode; - bool need_paren_on_right; + bool need_paren_on_right; need_paren_on_right = PRETTY_PAREN(context) && !IsA(j->rarg, RangeTblRef); if (!PRETTY_PAREN(context) || j->alias != NULL) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_from_clause_item(j->larg, query, context); if (j->isNatural) { - if (!PRETTY_INDENT(context)) + if (!PRETTY_INDENT(context)) appendStringInfoChar(buf, ' '); - switch (j->jointype) - { + switch (j->jointype) + { case JOIN_INNER: if (j->quals) appendContextKeyword(context, "NATURAL JOIN ", @@ -3845,12 +3855,12 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context) default: elog(ERROR, "unrecognized join type: %d", (int) j->jointype); - } + } } else { - switch (j->jointype) - { + switch (j->jointype) + { case JOIN_INNER: if (j->quals) appendContextKeyword(context, " JOIN ", @@ -3884,14 +3894,14 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context) default: elog(ERROR, "unrecognized join type: %d", (int) j->jointype); - } + } } if (need_paren_on_right) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_from_clause_item(j->rarg, query, context); if (need_paren_on_right) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); context->indentLevel -= PRETTYINDENT_JOIN_ON; @@ -3907,7 +3917,7 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context) if (col != j->using) appendStringInfo(buf, ", "); appendStringInfo(buf, "%s", - quote_identifier(strVal(lfirst(col)))); + quote_identifier(strVal(lfirst(col)))); } appendStringInfoChar(buf, ')'); } @@ -3915,14 +3925,14 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context) { appendStringInfo(buf, " ON "); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, '('); + appendStringInfoChar(buf, '('); get_rule_expr(j->quals, context, false); if (!PRETTY_PAREN(context)) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); } } if (!PRETTY_PAREN(context) || j->alias != NULL) - appendStringInfoChar(buf, ')'); + appendStringInfoChar(buf, ')'); /* Yes, it's correct to put alias after the right paren ... */ if (j->alias != NULL) @@ -3939,7 +3949,7 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context) if (col != j->alias->colnames) appendStringInfo(buf, ", "); appendStringInfo(buf, "%s", - quote_identifier(strVal(lfirst(col)))); + quote_identifier(strVal(lfirst(col)))); } appendStringInfoChar(buf, ')'); } @@ -4325,7 +4335,7 @@ generate_operator_name(Oid operid, Oid arg1, Oid arg2) static void print_operator_name(StringInfo buf, List *opname) { - int nnames = length(opname); + int nnames = length(opname); if (nnames == 1) appendStringInfo(buf, "%s", strVal(lfirst(opname))); diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c index 79c4af76a6..af11ed2296 100644 --- a/src/backend/utils/adt/selfuncs.c +++ b/src/backend/utils/adt/selfuncs.c @@ -15,7 +15,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/selfuncs.c,v 1.142 2003/07/27 04:53:09 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/selfuncs.c,v 1.143 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -180,7 +180,7 @@ static bool get_restriction_var(List *args, int varRelid, bool *varonleft); static void get_join_vars(List *args, Var **var1, Var **var2); static Selectivity prefix_selectivity(Query *root, Var *var, - Oid opclass, Const *prefix); + Oid opclass, Const *prefix); static Selectivity pattern_selectivity(Const *patt, Pattern_Type ptype); static Datum string_to_datum(const char *str, Oid datatype); static Const *string_to_const(const char *str, Oid datatype); @@ -871,8 +871,8 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype) /* * The right-hand const is type text or bytea for all supported * operators. We do not expect to see binary-compatible types here, - * since const-folding should have relabeled the const to exactly match - * the operator's declared type. + * since const-folding should have relabeled the const to exactly + * match the operator's declared type. */ if (consttype != TEXTOID && consttype != BYTEAOID) return DEFAULT_MATCH_SEL; @@ -890,10 +890,10 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype) * We should now be able to recognize the var's datatype. Choose the * index opclass from which we must draw the comparison operators. * - * NOTE: It would be more correct to use the PATTERN opclasses than - * the simple ones, but at the moment ANALYZE will not generate statistics - * for the PATTERN operators. But our results are so approximate anyway - * that it probably hardly matters. + * NOTE: It would be more correct to use the PATTERN opclasses than the + * simple ones, but at the moment ANALYZE will not generate statistics + * for the PATTERN operators. But our results are so approximate + * anyway that it probably hardly matters. */ switch (vartype) { @@ -921,22 +921,22 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype) pstatus = pattern_fixed_prefix(patt, ptype, &prefix, &rest); /* - * If necessary, coerce the prefix constant to the right type. - * (The "rest" constant need not be changed.) + * If necessary, coerce the prefix constant to the right type. (The + * "rest" constant need not be changed.) */ if (prefix && prefix->consttype != vartype) { - char *prefixstr; + char *prefixstr; switch (prefix->consttype) { case TEXTOID: prefixstr = DatumGetCString(DirectFunctionCall1(textout, - prefix->constvalue)); + prefix->constvalue)); break; case BYTEAOID: prefixstr = DatumGetCString(DirectFunctionCall1(byteaout, - prefix->constvalue)); + prefix->constvalue)); break; default: elog(ERROR, "unrecognized consttype: %u", @@ -1133,7 +1133,7 @@ booltestsel(Query *root, BoolTestType booltesttype, Node *arg, case IS_FALSE: case IS_NOT_TRUE: selec = 1.0 - (double) clause_selectivity(root, arg, - varRelid, jointype); + varRelid, jointype); break; default: elog(ERROR, "unrecognized booltesttype: %d", @@ -1523,27 +1523,29 @@ eqjoinsel(PG_FUNCTION_ARGS) hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool)); /* - * If we are doing any variant of JOIN_IN, pretend all the values - * of the righthand relation are unique (ie, act as if it's been - * DISTINCT'd). + * If we are doing any variant of JOIN_IN, pretend all the + * values of the righthand relation are unique (ie, act as if + * it's been DISTINCT'd). * * NOTE: it might seem that we should unique-ify the lefthand - * input when considering JOIN_REVERSE_IN. But this is not so, - * because the join clause we've been handed has not been - * commuted from the way the parser originally wrote it. We know - * that the unique side of the IN clause is *always* on the right. + * input when considering JOIN_REVERSE_IN. But this is not + * so, because the join clause we've been handed has not been + * commuted from the way the parser originally wrote it. We + * know that the unique side of the IN clause is *always* on + * the right. * * NOTE: it would be dangerous to try to be smart about JOIN_LEFT - * or JOIN_RIGHT here, because we do not have enough information - * to determine which var is really on which side of the join. - * Perhaps someday we should pass in more information. + * or JOIN_RIGHT here, because we do not have enough + * information to determine which var is really on which side + * of the join. Perhaps someday we should pass in more + * information. */ if (jointype == JOIN_IN || jointype == JOIN_REVERSE_IN || jointype == JOIN_UNIQUE_INNER || jointype == JOIN_UNIQUE_OUTER) { - float4 oneovern = 1.0 / nd2; + float4 oneovern = 1.0 / nd2; for (i = 0; i < nvalues2; i++) numbers2[i] = oneovern; @@ -1647,20 +1649,22 @@ eqjoinsel(PG_FUNCTION_ARGS) { /* * We do not have MCV lists for both sides. Estimate the join - * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). - * This is plausible if we assume that the join operator is - * strict and the non-null values are about equally distributed: - * a given non-null tuple of rel1 will join to either zero or - * N2*(1-nullfrac2)/nd2 rows of rel2, so total join rows are at - * most N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join - * selectivity of not more than (1-nullfrac1)*(1-nullfrac2)/nd2. - * By the same logic it is not more than - * (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression with MIN() - * is an upper bound. Using the MIN() means we estimate from the - * point of view of the relation with smaller nd (since the larger - * nd is determining the MIN). It is reasonable to assume that - * most tuples in this rel will have join partners, so the bound - * is probably reasonably tight and should be taken as-is. + * selectivity as + * MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This is + * plausible if we assume that the join operator is strict and + * the non-null values are about equally distributed: a given + * non-null tuple of rel1 will join to either zero or + * N2*(1-nullfrac2)/nd2 rows of rel2, so total join rows are + * at most N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join + * selectivity of not more than + * (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it is + * not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the + * expression with MIN() is an upper bound. Using the MIN() + * means we estimate from the point of view of the relation + * with smaller nd (since the larger nd is determining the + * MIN). It is reasonable to assume that most tuples in this + * rel will have join partners, so the bound is probably + * reasonably tight and should be taken as-is. * * XXX Can we be smarter if we have an MCV list for just one * side? It seems that if we assume equal distribution for the @@ -1715,9 +1719,9 @@ neqjoinsel(PG_FUNCTION_ARGS) { result = DatumGetFloat8(DirectFunctionCall4(eqjoinsel, PointerGetDatum(root), - ObjectIdGetDatum(eqop), + ObjectIdGetDatum(eqop), PointerGetDatum(args), - Int16GetDatum(jointype))); + Int16GetDatum(jointype))); } else { @@ -1886,8 +1890,9 @@ mergejoinscansel(Query *root, Node *clause, righttype = exprType((Node *) right); /* - * Now skip any binary-compatible relabeling; there can only be one level - * since constant-expression folder eliminates adjacent RelabelTypes. + * Now skip any binary-compatible relabeling; there can only be one + * level since constant-expression folder eliminates adjacent + * RelabelTypes. */ if (IsA(left, RelabelType)) left = (Var *) ((RelabelType *) left)->arg; @@ -2002,7 +2007,7 @@ mergejoinscansel(Query *root, Node *clause, * of values, clamp to the number of rows in the rel, and then multiply * by the selectivity of the restriction clauses for that rel. The * initial product is probably too high (it's the worst case) but since - * we can clamp to the rel's rows it won't be hugely bad. Multiplying + * we can clamp to the rel's rows it won't be hugely bad. Multiplying * by the restriction selectivity is effectively assuming that the * restriction clauses are independent of the grouping, which is a crummy * assumption, but it's hard to do better. @@ -2021,10 +2026,11 @@ estimate_num_groups(Query *root, List *groupExprs, double input_rows) List *varinfos = NIL; double numdistinct; List *l; - typedef struct { /* varinfos is a List of these */ - Var *var; - double ndistinct; - } MyVarInfo; + typedef struct + { /* varinfos is a List of these */ + Var *var; + double ndistinct; + } MyVarInfo; /* We should not be called unless query has GROUP BY (or DISTINCT) */ Assert(groupExprs != NIL); @@ -2036,9 +2042,10 @@ estimate_num_groups(Query *root, List *groupExprs, double input_rows) List *varshere; varshere = pull_var_clause(groupexpr, false); + /* - * If we find any variable-free GROUP BY item, then either it is - * a constant (and we can ignore it) or it contains a volatile + * If we find any variable-free GROUP BY item, then either it is a + * constant (and we can ignore it) or it contains a volatile * function; in the latter case we punt and assume that each input * row will yield a distinct group. */ @@ -2065,13 +2072,13 @@ estimate_num_groups(Query *root, List *groupExprs, double input_rows) */ foreach(l, allvars) { - Var *var = (Var *) lfirst(l); - Oid relid = getrelid(var->varno, root->rtable); + Var *var = (Var *) lfirst(l); + Oid relid = getrelid(var->varno, root->rtable); HeapTuple statsTuple = NULL; Form_pg_statistic stats = NULL; - double ndistinct; - bool keep = true; - List *l2; + double ndistinct; + bool keep = true; + List *l2; if (OidIsValid(relid)) { @@ -2096,7 +2103,7 @@ estimate_num_groups(Query *root, List *groupExprs, double input_rows) l2 = lnext(l2); if (var->varno != varinfo->var->varno && - exprs_known_equal(root, (Node *) var, (Node *) varinfo->var)) + exprs_known_equal(root, (Node *) var, (Node *) varinfo->var)) { /* Found a match */ if (varinfo->ndistinct <= ndistinct) @@ -2126,10 +2133,10 @@ estimate_num_groups(Query *root, List *groupExprs, double input_rows) /* * Steps 3/4: group Vars by relation and estimate total numdistinct. * - * For each iteration of the outer loop, we process the frontmost - * Var in varinfos, plus all other Vars in the same relation. We - * remove these Vars from the newvarinfos list for the next iteration. - * This is the easiest way to group Vars of same rel together. + * For each iteration of the outer loop, we process the frontmost Var in + * varinfos, plus all other Vars in the same relation. We remove + * these Vars from the newvarinfos list for the next iteration. This + * is the easiest way to group Vars of same rel together. */ Assert(varinfos != NIL); numdistinct = 1.0; @@ -2138,8 +2145,8 @@ estimate_num_groups(Query *root, List *groupExprs, double input_rows) { MyVarInfo *varinfo1 = (MyVarInfo *) lfirst(varinfos); RelOptInfo *rel = find_base_rel(root, varinfo1->var->varno); - double reldistinct = varinfo1->ndistinct; - List *newvarinfos = NIL; + double reldistinct = varinfo1->ndistinct; + List *newvarinfos = NIL; /* * Get the largest numdistinct estimate of the Vars for this rel. @@ -2150,9 +2157,7 @@ estimate_num_groups(Query *root, List *groupExprs, double input_rows) MyVarInfo *varinfo2 = (MyVarInfo *) lfirst(l); if (varinfo2->var->varno == varinfo1->var->varno) - { reldistinct *= varinfo2->ndistinct; - } else { /* not time to process varinfo2 yet */ @@ -2364,9 +2369,10 @@ convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue, * constant-folding will ensure that any Const passed to the operator * has been reduced to the correct type). However, the boundstypid is * the type of some variable that might be only binary-compatible with - * the declared type; in particular it might be a domain type. Must + * the declared type; in particular it might be a domain type. Must * fold the variable type down to base type so we can recognize it. - * (But we can skip that lookup if the variable type matches the const.) + * (But we can skip that lookup if the variable type matches the + * const.) */ if (boundstypid != valuetypid) boundstypid = getBaseType(boundstypid); @@ -2696,15 +2702,15 @@ convert_string_datum(Datum value, Oid typid) /* * Note: originally we guessed at a suitable output buffer size, - * and only needed to call strxfrm twice if our guess was too small. - * However, it seems that some versions of Solaris have buggy - * strxfrm that can write past the specified buffer length in that - * scenario. So, do it the dumb way for portability. + * and only needed to call strxfrm twice if our guess was too + * small. However, it seems that some versions of Solaris have + * buggy strxfrm that can write past the specified buffer length + * in that scenario. So, do it the dumb way for portability. * * Yet other systems (e.g., glibc) sometimes return a smaller value * from the second call than the first; thus the Assert must be <= - * not == as you'd expect. Can't any of these people program their - * way out of a paper bag? + * not == as you'd expect. Can't any of these people program + * their way out of a paper bag? */ xfrmlen = strxfrm(NULL, val, 0); xfrmstr = (char *) palloc(xfrmlen + 1); @@ -3113,7 +3119,7 @@ like_fixed_prefix(Const *patt_const, bool case_insensitive, if (typeid == BYTEAOID && case_insensitive) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("case insensitive matching not supported on type bytea"))); + errmsg("case insensitive matching not supported on type bytea"))); if (typeid != BYTEAOID) { @@ -3355,7 +3361,7 @@ pattern_fixed_prefix(Const *patt, Pattern_Type ptype, * "var >= 'foo' AND var < 'fop'" (see also indxqual.c). * * We use the >= and < operators from the specified btree opclass to do the - * estimation. The given Var and Const must be of the associated datatype. + * estimation. The given Var and Const must be of the associated datatype. * * XXX Note: we make use of the upper bound to estimate operator selectivity * even if the locale is such that we cannot rely on the upper-bound string. @@ -3476,7 +3482,7 @@ like_selectivity(Const *patt_const, bool case_insensitive) if (typeid == BYTEAOID && case_insensitive) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("case insensitive matching not supported on type bytea"))); + errmsg("case insensitive matching not supported on type bytea"))); if (typeid != BYTEAOID) { @@ -3917,8 +3923,8 @@ btcostestimate(PG_FUNCTION_ARGS) indexSelectivity, indexCorrelation); /* - * If the first column is a simple variable, and we can get an estimate - * for its ordering correlation C from pg_statistic, estimate + * If the first column is a simple variable, and we can get an + * estimate for its ordering correlation C from pg_statistic, estimate * the index correlation as C / number-of-columns. (The idea here is * that multiple columns dilute the importance of the first column's * ordering, but don't negate it entirely.) diff --git a/src/backend/utils/adt/sets.c b/src/backend/utils/adt/sets.c index a611f7271a..9087cf07ee 100644 --- a/src/backend/utils/adt/sets.c +++ b/src/backend/utils/adt/sets.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/sets.c,v 1.56 2003/07/27 04:53:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/sets.c,v 1.57 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -154,14 +154,15 @@ seteval(PG_FUNCTION_ARGS) fcache = (FuncExprState *) fcinfo->flinfo->fn_extra; if (fcache == NULL) { - MemoryContext oldcontext; + MemoryContext oldcontext; FuncExpr *func; oldcontext = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt); func = makeNode(FuncExpr); func->funcid = funcoid; - func->funcresulttype = InvalidOid; /* nothing will look at this */ + func->funcresulttype = InvalidOid; /* nothing will look at + * this */ func->funcretset = true; func->funcformat = COERCE_EXPLICIT_CALL; func->args = NIL; /* there are no arguments */ diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c index fb84596bee..ec7b303585 100644 --- a/src/backend/utils/adt/timestamp.c +++ b/src/backend/utils/adt/timestamp.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/timestamp.c,v 1.88 2003/07/27 04:53:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/timestamp.c,v 1.89 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -254,15 +254,15 @@ AdjustTimestampForTypmod(Timestamp *time, int32 typmod) if ((typmod < 0) || (typmod > MAX_TIMESTAMP_PRECISION)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("timestamp(%d) precision must be between %d and %d", - typmod, 0, MAX_TIMESTAMP_PRECISION))); + errmsg("timestamp(%d) precision must be between %d and %d", + typmod, 0, MAX_TIMESTAMP_PRECISION))); /* * Note: this round-to-nearest code is not completely consistent * about rounding values that are exactly halfway between integral - * values. On most platforms, rint() will implement round-to-nearest-even, - * but the integer code always rounds up (away from zero). Is it - * worth trying to be consistent? + * values. On most platforms, rint() will implement + * round-to-nearest-even, but the integer code always rounds up + * (away from zero). Is it worth trying to be consistent? */ #ifdef HAVE_INT64_TIMESTAMP if (*time >= INT64CONST(0)) @@ -272,8 +272,8 @@ AdjustTimestampForTypmod(Timestamp *time, int32 typmod) } else { - *time = - ((((- *time) + TimestampOffsets[typmod]) / TimestampScales[typmod]) - * TimestampScales[typmod]); + *time = -((((-*time) + TimestampOffsets[typmod]) / TimestampScales[typmod]) + * TimestampScales[typmod]); } #else *time = (rint(((double) *time) * TimestampScales[typmod]) @@ -411,7 +411,7 @@ timestamptz_recv(PG_FUNCTION_ARGS) Datum timestamptz_send(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0); StringInfoData buf; pq_begintypsend(&buf); @@ -829,15 +829,16 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod) if ((precision < 0) || (precision > MAX_INTERVAL_PRECISION)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("interval(%d) precision must be between %d and %d", - precision, 0, MAX_INTERVAL_PRECISION))); + errmsg("interval(%d) precision must be between %d and %d", + precision, 0, MAX_INTERVAL_PRECISION))); /* - * Note: this round-to-nearest code is not completely consistent - * about rounding values that are exactly halfway between integral - * values. On most platforms, rint() will implement round-to-nearest-even, - * but the integer code always rounds up (away from zero). Is it - * worth trying to be consistent? + * Note: this round-to-nearest code is not completely + * consistent about rounding values that are exactly halfway + * between integral values. On most platforms, rint() will + * implement round-to-nearest-even, but the integer code + * always rounds up (away from zero). Is it worth trying to + * be consistent? */ #ifdef HAVE_INT64_TIMESTAMP if (interval->time >= INT64CONST(0)) @@ -847,8 +848,8 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod) } else { - interval->time = - (((-interval->time + IntervalOffsets[precision]) / IntervalScales[precision]) - * IntervalScales[precision]); + interval->time = -(((-interval->time + IntervalOffsets[precision]) / IntervalScales[precision]) + * IntervalScales[precision]); } #else interval->time = (rint(((double) interval->time) * IntervalScales[precision]) @@ -1024,7 +1025,7 @@ timestamp2tm(Timestamp dt, int *tzp, struct tm * tm, fsec_t *fsec, char **tzn) { #ifdef HAVE_INT64_TIMESTAMP utime = ((dt / INT64CONST(1000000)) - + ((date0 - UNIX_EPOCH_JDATE) * INT64CONST(86400))); + + ((date0 - UNIX_EPOCH_JDATE) * INT64CONST(86400))); #else utime = (dt + ((date0 - UNIX_EPOCH_JDATE) * 86400)); #endif @@ -2410,7 +2411,7 @@ text_timestamp(PG_FUNCTION_ARGS) (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("invalid input syntax for timestamp: \"%s\"", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(str)))))); + PointerGetDatum(str)))))); sp = VARDATA(str); dp = dstr; @@ -2470,7 +2471,7 @@ text_timestamptz(PG_FUNCTION_ARGS) (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("invalid input syntax for timestamp with time zone: \"%s\"", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(str)))))); + PointerGetDatum(str)))))); sp = VARDATA(str); dp = dstr; @@ -2531,7 +2532,7 @@ text_interval(PG_FUNCTION_ARGS) (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("invalid input syntax for interval: \"%s\"", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(str)))))); + PointerGetDatum(str)))))); sp = VARDATA(str); dp = dstr; @@ -2568,8 +2569,8 @@ timestamp_trunc(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("timestamp units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; @@ -2676,9 +2677,9 @@ timestamptz_trunc(PG_FUNCTION_ARGS) if (VARSIZE(units) - VARHDRSZ > MAXDATELEN) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("timestamp with time zone units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + errmsg("timestamp with time zone units \"%s\" not recognized", + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -2737,8 +2738,8 @@ timestamptz_trunc(PG_FUNCTION_ARGS) default: ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("timestamp with time zone units \"%s\" not " - "supported", lowunits))); + errmsg("timestamp with time zone units \"%s\" not " + "supported", lowunits))); result = 0; } @@ -2753,8 +2754,8 @@ timestamptz_trunc(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("timestamp with time zone units \"%s\" not recognized", - lowunits))); + errmsg("timestamp with time zone units \"%s\" not recognized", + lowunits))); result = 0; } @@ -2786,8 +2787,8 @@ interval_trunc(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("interval units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -2841,7 +2842,7 @@ interval_trunc(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("interval units \"%s\" not supported", - lowunits))); + lowunits))); } if (tm2interval(tm, fsec, result) != 0) @@ -2850,17 +2851,15 @@ interval_trunc(PG_FUNCTION_ARGS) errmsg("interval out of range"))); } else - { elog(ERROR, "could not convert interval to tm"); - } } else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("interval units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); *result = *interval; } @@ -2882,7 +2881,7 @@ isoweek2date(int woy, int *year, int *mon, int *mday) if (!*year) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("cannot convert week number without year information"))); + errmsg("cannot convert week number without year information"))); /* fourth day of current year */ day4 = date2j(*year, 1, 4); @@ -2972,8 +2971,8 @@ timestamp_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("timestamp units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -3081,7 +3080,7 @@ timestamp_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("timestamp units \"%s\" not supported", - lowunits))); + lowunits))); result = 0; } } @@ -3090,30 +3089,33 @@ timestamp_part(PG_FUNCTION_ARGS) switch (val) { case DTK_EPOCH: - { - int tz; - TimestampTz timestamptz; + { + int tz; + TimestampTz timestamptz; - /* convert to timestamptz to produce consistent results */ - if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0) - ereport(ERROR, - (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), - errmsg("timestamp out of range"))); + /* + * convert to timestamptz to produce consistent + * results + */ + if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0) + ereport(ERROR, + (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), + errmsg("timestamp out of range"))); - tz = DetermineLocalTimeZone(tm); + tz = DetermineLocalTimeZone(tm); - if (tm2timestamp(tm, fsec, &tz, ×tamptz) != 0) - ereport(ERROR, - (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), - errmsg("timestamp out of range"))); + if (tm2timestamp(tm, fsec, &tz, ×tamptz) != 0) + ereport(ERROR, + (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), + errmsg("timestamp out of range"))); #ifdef HAVE_INT64_TIMESTAMP - result = ((timestamptz - SetEpochTimestamp()) / 1000000e0); + result = ((timestamptz - SetEpochTimestamp()) / 1000000e0); #else - result = timestamptz - SetEpochTimestamp(); + result = timestamptz - SetEpochTimestamp(); #endif - break; - } + break; + } case DTK_DOW: if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0) ereport(ERROR, @@ -3135,7 +3137,7 @@ timestamp_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("timestamp units \"%s\" not supported", - lowunits))); + lowunits))); result = 0; } @@ -3144,7 +3146,7 @@ timestamp_part(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("timestamp units \"%s\" not recognized", lowunits))); + errmsg("timestamp units \"%s\" not recognized", lowunits))); result = 0; } @@ -3176,9 +3178,9 @@ timestamptz_part(PG_FUNCTION_ARGS) if (VARSIZE(units) - VARHDRSZ > MAXDATELEN) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("timestamp with time zone units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + errmsg("timestamp with time zone units \"%s\" not recognized", + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -3298,7 +3300,7 @@ timestamptz_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("timestamp with time zone units \"%s\" not supported", - lowunits))); + lowunits))); result = 0; } @@ -3336,7 +3338,7 @@ timestamptz_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("timestamp with time zone units \"%s\" not supported", - lowunits))); + lowunits))); result = 0; } } @@ -3344,8 +3346,8 @@ timestamptz_part(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("timestamp with time zone units \"%s\" not recognized", - lowunits))); + errmsg("timestamp with time zone units \"%s\" not recognized", + lowunits))); result = 0; } @@ -3377,8 +3379,8 @@ interval_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("interval units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -3460,7 +3462,7 @@ interval_part(PG_FUNCTION_ARGS) (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("interval units \"%s\" not supported", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + PointerGetDatum(units)))))); result = 0; } @@ -3489,8 +3491,8 @@ interval_part(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("interval units \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(units)))))); result = 0; } @@ -3521,8 +3523,8 @@ timestamp_zone(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("time zone \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(zone)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(zone)))))); if (TIMESTAMP_NOT_FINITE(timestamp)) PG_RETURN_TIMESTAMPTZ(timestamp); @@ -3546,7 +3548,7 @@ timestamp_zone(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("time zone \"%s\" not recognized", - lowzone))); + lowzone))); PG_RETURN_NULL(); } @@ -3571,9 +3573,9 @@ timestamp_izone(PG_FUNCTION_ARGS) if (zone->month != 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("interval time zone \"%s\" must not specify month", - DatumGetCString(DirectFunctionCall1(interval_out, - PointerGetDatum(zone)))))); + errmsg("interval time zone \"%s\" must not specify month", + DatumGetCString(DirectFunctionCall1(interval_out, + PointerGetDatum(zone)))))); #ifdef HAVE_INT64_TIMESTAMP tz = (zone->time / INT64CONST(1000000)); @@ -3673,8 +3675,8 @@ timestamptz_zone(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("time zone \"%s\" not recognized", - DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(zone)))))); + DatumGetCString(DirectFunctionCall1(textout, + PointerGetDatum(zone)))))); up = VARDATA(zone); lp = lowzone; for (i = 0; i < (VARSIZE(zone) - VARHDRSZ); i++) @@ -3722,9 +3724,9 @@ timestamptz_izone(PG_FUNCTION_ARGS) if (zone->month != 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("interval time zone \"%s\" must not specify month", - DatumGetCString(DirectFunctionCall1(interval_out, - PointerGetDatum(zone)))))); + errmsg("interval time zone \"%s\" must not specify month", + DatumGetCString(DirectFunctionCall1(interval_out, + PointerGetDatum(zone)))))); #ifdef HAVE_INT64_TIMESTAMP tz = -(zone->time / INT64CONST(1000000)); diff --git a/src/backend/utils/adt/varbit.c b/src/backend/utils/adt/varbit.c index ea76783413..8ced9f846f 100644 --- a/src/backend/utils/adt/varbit.c +++ b/src/backend/utils/adt/varbit.c @@ -9,7 +9,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/varbit.c,v 1.32 2003/07/27 04:53:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/varbit.c,v 1.33 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -106,8 +106,8 @@ bit_in(PG_FUNCTION_ARGS) else if (bitlen != atttypmod) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), - errmsg("bit string length %d does not match type bit(%d)", - bitlen, atttypmod))); + errmsg("bit string length %d does not match type bit(%d)", + bitlen, atttypmod))); len = VARBITTOTALLEN(atttypmod); /* set to 0 so that *r is always initialised and string is zero-padded */ @@ -260,8 +260,8 @@ bit(PG_FUNCTION_ARGS) if (!isExplicit) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), - errmsg("bit string length %d does not match type bit(%d)", - VARBITLEN(arg), len))); + errmsg("bit string length %d does not match type bit(%d)", + VARBITLEN(arg), len))); rlen = VARBITTOTALLEN(len); /* set to 0 so that string is zero-padded */ @@ -346,7 +346,7 @@ varbit_in(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), errmsg("bit string too long for type bit varying(%d)", - atttypmod))); + atttypmod))); len = VARBITTOTALLEN(bitlen); /* set to 0 so that *r is always initialised and string is zero-padded */ @@ -530,7 +530,7 @@ varbit(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), errmsg("bit string too long for type bit varying(%d)", - len))); + len))); rlen = VARBITTOTALLEN(len); result = (VarBit *) palloc(rlen); diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c index 1b401b66df..8ffa3969b4 100644 --- a/src/backend/utils/adt/varchar.c +++ b/src/backend/utils/adt/varchar.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/varchar.c,v 1.99 2003/07/27 04:53:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/varchar.c,v 1.100 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -103,7 +103,7 @@ bpcharin(PG_FUNCTION_ARGS) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), errmsg("value too long for type character(%d)", - (int) maxlen))); + (int) maxlen))); /* * XXX: at this point, maxlen is the necessary byte length, not @@ -190,7 +190,7 @@ bpcharsend(PG_FUNCTION_ARGS) * * Truncation rules: for an explicit cast, silently truncate to the given * length; for an implicit cast, raise error unless extra characters are - * all spaces. (This is sort-of per SQL: the spec would actually have us + * all spaces. (This is sort-of per SQL: the spec would actually have us * raise a "completion condition" for the explicit cast case, but Postgres * hasn't got such a concept.) */ @@ -230,8 +230,8 @@ bpchar(PG_FUNCTION_ARGS) if (*(VARDATA(source) + i) != ' ') ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), - errmsg("value too long for type character(%d)", - maxlen - VARHDRSZ))); + errmsg("value too long for type character(%d)", + maxlen - VARHDRSZ))); } len = maxmblen; @@ -388,8 +388,8 @@ varcharin(PG_FUNCTION_ARGS) else ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), - errmsg("value too long for type character varying(%d)", - (int) maxlen))); + errmsg("value too long for type character varying(%d)", + (int) maxlen))); } result = palloc(len + VARHDRSZ); @@ -456,7 +456,7 @@ varcharsend(PG_FUNCTION_ARGS) * * Truncation rules: for an explicit cast, silently truncate to the given * length; for an implicit cast, raise error unless extra characters are - * all spaces. (This is sort-of per SQL: the spec would actually have us + * all spaces. (This is sort-of per SQL: the spec would actually have us * raise a "completion condition" for the explicit cast case, but Postgres * hasn't got such a concept.) */ @@ -488,8 +488,8 @@ varchar(PG_FUNCTION_ARGS) if (*(VARDATA(source) + i) != ' ') ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), - errmsg("value too long for type character varying(%d)", - maxlen - VARHDRSZ))); + errmsg("value too long for type character varying(%d)", + maxlen - VARHDRSZ))); } len = maxmblen + VARHDRSZ; diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c index fc4574b6a6..1055c927ad 100644 --- a/src/backend/utils/adt/varlena.c +++ b/src/backend/utils/adt/varlena.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/varlena.c,v 1.102 2003/07/27 04:53:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/varlena.c,v 1.103 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -34,7 +34,7 @@ typedef struct varlena unknown; #define DatumGetUnknownP(X) ((unknown *) PG_DETOAST_DATUM(X)) #define DatumGetUnknownPCopy(X) ((unknown *) PG_DETOAST_DATUM_COPY(X)) #define PG_GETARG_UNKNOWN_P(n) DatumGetUnknownP(PG_GETARG_DATUM(n)) -#define PG_GETARG_UNKNOWN_P_COPY(n) DatumGetUnknownPCopy(PG_GETARG_DATUM(n)) +#define PG_GETARG_UNKNOWN_P_COPY(n) DatumGetUnknownPCopy(PG_GETARG_DATUM(n)) #define PG_RETURN_UNKNOWN_P(x) PG_RETURN_POINTER(x) #define PG_TEXTARG_GET_STR(arg_) \ @@ -120,7 +120,7 @@ byteain(PG_FUNCTION_ARGS) byte += VARHDRSZ; result = (bytea *) palloc(byte); - VARATT_SIZEP(result) = byte; /* set varlena length */ + VARATT_SIZEP(result) = byte; /* set varlena length */ tp = inputText; rp = VARDATA(result); @@ -376,7 +376,7 @@ Datum unknownrecv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); - unknown *result; + unknown *result; int nbytes; nbytes = buf->len - buf->cursor; @@ -395,7 +395,7 @@ unknownrecv(PG_FUNCTION_ARGS) Datum unknownsend(PG_FUNCTION_ARGS) { - unknown *vlena = PG_GETARG_UNKNOWN_P_COPY(0); + unknown *vlena = PG_GETARG_UNKNOWN_P_COPY(0); PG_RETURN_UNKNOWN_P(vlena); } @@ -584,7 +584,7 @@ text_substring(Datum str, int32 start, int32 length, bool length_not_specified) if (E < S) ereport(ERROR, (errcode(ERRCODE_SUBSTRING_ERROR), - errmsg("negative substring length not allowed"))); + errmsg("negative substring length not allowed"))); /* * A zero or negative value for the end position can happen if @@ -648,7 +648,7 @@ text_substring(Datum str, int32 start, int32 length, bool length_not_specified) if (E < S) ereport(ERROR, (errcode(ERRCODE_SUBSTRING_ERROR), - errmsg("negative substring length not allowed"))); + errmsg("negative substring length not allowed"))); /* * A zero or negative value for the end position can happen if @@ -851,10 +851,10 @@ varstr_cmp(char *arg1, int len1, char *arg2, int len2) if (!lc_collate_is_c()) { - char a1buf[STACKBUFLEN]; - char a2buf[STACKBUFLEN]; - char *a1p, - *a2p; + char a1buf[STACKBUFLEN]; + char a2buf[STACKBUFLEN]; + char *a1p, + *a2p; if (len1 >= STACKBUFLEN) a1p = (char *) palloc(len1 + 1); @@ -1065,7 +1065,7 @@ text_smaller(PG_FUNCTION_ARGS) static int internal_text_pattern_compare(text *arg1, text *arg2) { - int result; + int result; result = memcmp(VARDATA(arg1), VARDATA(arg2), Min(VARSIZE(arg1), VARSIZE(arg2)) - VARHDRSZ); @@ -2004,7 +2004,8 @@ split_text(PG_FUNCTION_ARGS) if (fldnum == 1) /* first field - just return the input * string */ PG_RETURN_TEXT_P(inputstring); - else /* otherwise return an empty string */ + else +/* otherwise return an empty string */ PG_RETURN_TEXT_P(PG_STR_GET_TEXT("")); } @@ -2026,7 +2027,8 @@ split_text(PG_FUNCTION_ARGS) if (fldnum == 1) /* first field - just return the input * string */ PG_RETURN_TEXT_P(inputstring); - else /* otherwise return an empty string */ + else +/* otherwise return an empty string */ PG_RETURN_TEXT_P(PG_STR_GET_TEXT("")); } else if ((start_posn != 0) && (end_posn == 0)) @@ -2073,32 +2075,36 @@ text_to_array(PG_FUNCTION_ARGS) if (inputstring_len < 1) PG_RETURN_NULL(); - /* empty field separator - * return one element, 1D, array using the input string */ + /* + * empty field separator return one element, 1D, array using the input + * string + */ if (fldsep_len < 1) PG_RETURN_ARRAYTYPE_P(create_singleton_array(fcinfo, TEXTOID, - CStringGetDatum(inputstring), 1)); + CStringGetDatum(inputstring), 1)); /* start with end position holding the initial start position */ end_posn = 0; - for (fldnum=1;;fldnum++) /* field number is 1 based */ + for (fldnum = 1;; fldnum++) /* field number is 1 based */ { - Datum dvalue; - bool disnull = false; + Datum dvalue; + bool disnull = false; start_posn = end_posn; end_posn = text_position(PointerGetDatum(inputstring), PointerGetDatum(fldsep), fldnum); - if ((start_posn == 0) && (end_posn == 0)) /* fldsep not found */ + if ((start_posn == 0) && (end_posn == 0)) /* fldsep not found */ { if (fldnum == 1) { - /* first element - * return one element, 1D, array using the input string */ + /* + * first element return one element, 1D, array using the + * input string + */ PG_RETURN_ARRAYTYPE_P(create_singleton_array(fcinfo, TEXTOID, - CStringGetDatum(inputstring), 1)); + CStringGetDatum(inputstring), 1)); } else { @@ -2143,7 +2149,9 @@ array_to_text(PG_FUNCTION_ARGS) { ArrayType *v = PG_GETARG_ARRAYTYPE_P(0); char *fldsep = PG_TEXTARG_GET_STR(1); - int nitems, *dims, ndims; + int nitems, + *dims, + ndims; char *p; Oid element_type; int typlen; @@ -2167,21 +2175,24 @@ array_to_text(PG_FUNCTION_ARGS) /* * We arrange to look up info about element type, including its output - * conversion proc, only once per series of calls, assuming the element - * type doesn't change underneath us. + * conversion proc, only once per series of calls, assuming the + * element type doesn't change underneath us. */ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; if (my_extra == NULL) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, - sizeof(ArrayMetaState)); + sizeof(ArrayMetaState)); my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra; my_extra->element_type = InvalidOid; } if (my_extra->element_type != element_type) { - /* Get info about element type, including its output conversion proc */ + /* + * Get info about element type, including its output conversion + * proc + */ get_type_io_data(element_type, IOFunc_output, &my_extra->typlen, &my_extra->typbyval, &my_extra->typalign, &my_extra->typdelim, diff --git a/src/backend/utils/adt/xid.c b/src/backend/utils/adt/xid.c index ba21bd7896..9dabcf75e0 100644 --- a/src/backend/utils/adt/xid.c +++ b/src/backend/utils/adt/xid.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/xid.c,v 1.1 2003/05/12 23:08:50 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/xid.c,v 1.2 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -151,7 +151,7 @@ cidrecv(PG_FUNCTION_ARGS) Datum cidsend(PG_FUNCTION_ARGS) { - CommandId arg1 = PG_GETARG_COMMANDID(0); + CommandId arg1 = PG_GETARG_COMMANDID(0); StringInfoData buf; pq_begintypsend(&buf); diff --git a/src/backend/utils/cache/catcache.c b/src/backend/utils/cache/catcache.c index a1e55ee71f..9c098aa41f 100644 --- a/src/backend/utils/cache/catcache.c +++ b/src/backend/utils/cache/catcache.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/cache/catcache.c,v 1.106 2003/07/28 00:09:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/catcache.c,v 1.107 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -956,8 +956,8 @@ CatalogCacheInitializeCache(CatCache *cache) cache->cc_isname[i] = (keytype == NAMEOID); /* - * Do equality-function lookup (we assume this won't need a catalog - * lookup for any supported type) + * Do equality-function lookup (we assume this won't need a + * catalog lookup for any supported type) */ fmgr_info_cxt(cache->cc_skey[i].sk_procedure, &cache->cc_skey[i].sk_func, diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c index 080338a77b..973f1b4b50 100644 --- a/src/backend/utils/cache/inval.c +++ b/src/backend/utils/cache/inval.c @@ -74,7 +74,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/cache/inval.c,v 1.56 2003/07/25 20:17:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/inval.c,v 1.57 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -449,9 +449,7 @@ LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg) } } else - { elog(FATAL, "unrecognized SI message id: %d", msg->id); - } } /* diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c index 86bb40e738..0a68ade5da 100644 --- a/src/backend/utils/cache/lsyscache.c +++ b/src/backend/utils/cache/lsyscache.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/cache/lsyscache.c,v 1.103 2003/07/28 00:09:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/lsyscache.c,v 1.104 2003/08/04 00:43:26 momjian Exp $ * * NOTES * Eventually, the index information should go through here, too. @@ -126,8 +126,8 @@ get_op_hash_function(Oid opno) Oid opclass = InvalidOid; /* - * Search pg_amop to see if the target operator is registered as the "=" - * operator of any hash opclass. If the operator is registered in + * Search pg_amop to see if the target operator is registered as the + * "=" operator of any hash opclass. If the operator is registered in * multiple opclasses, assume we can use the associated hash function * from any one. */ @@ -728,8 +728,8 @@ get_func_rettype(Oid funcid) Oid get_func_signature(Oid funcid, Oid *argtypes, int *nargs) { - HeapTuple tp; - Form_pg_proc procstruct; + HeapTuple tp; + Form_pg_proc procstruct; Oid result; tp = SearchSysCache(PROCOID, diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index c9a56c0072..8271473183 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/cache/relcache.c,v 1.186 2003/07/25 20:17:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/relcache.c,v 1.187 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -962,7 +962,8 @@ RelationInitIndexAccessInfo(Relation relation) /* * Make a copy of the pg_index entry for the index. Since pg_index * contains variable-length and possibly-null fields, we have to do - * this honestly rather than just treating it as a Form_pg_index struct. + * this honestly rather than just treating it as a Form_pg_index + * struct. */ tuple = SearchSysCache(INDEXRELID, ObjectIdGetDatum(RelationGetRelid(relation)), @@ -1368,8 +1369,7 @@ formrdesc(const char *relationName, bool has_not_null; /* - * allocate new relation desc - * clear all fields of reldesc + * allocate new relation desc clear all fields of reldesc */ relation = (Relation) palloc0(sizeof(RelationData)); relation->rd_targblock = InvalidBlockNumber; @@ -1710,8 +1710,8 @@ RelationClearRelation(Relation relation, bool rebuild) /* * Never, never ever blow away a nailed-in system relation, because - * we'd be unable to recover. However, we must update rd_nblocks - * and reset rd_targblock, in case we got called because of a relation + * we'd be unable to recover. However, we must update rd_nblocks and + * reset rd_targblock, in case we got called because of a relation * cache flush that was triggered by VACUUM. */ if (relation->rd_isnailed) @@ -1742,8 +1742,8 @@ RelationClearRelation(Relation relation, bool rebuild) * Free all the subsidiary data structures of the relcache entry. We * cannot free rd_att if we are trying to rebuild the entry, however, * because pointers to it may be cached in various places. The rule - * manager might also have pointers into the rewrite rules. So to begin - * with, we can only get rid of these fields: + * manager might also have pointers into the rewrite rules. So to + * begin with, we can only get rid of these fields: */ FreeTriggerDesc(relation->trigdesc); if (relation->rd_indextuple) @@ -2705,15 +2705,15 @@ RelationGetIndexExpressions(Relation relation) /* * We build the tree we intend to return in the caller's context. - * After successfully completing the work, we copy it into the relcache - * entry. This avoids problems if we get some sort of - * error partway through. + * After successfully completing the work, we copy it into the + * relcache entry. This avoids problems if we get some sort of error + * partway through. * - * We make use of the syscache's copy of pg_index's tupledesc - * to access the non-fixed fields of the tuple. We assume that - * the syscache will be initialized before any access of a - * partial index could occur. (This would probably fail if we - * were to allow partial indexes on system catalogs.) + * We make use of the syscache's copy of pg_index's tupledesc to access + * the non-fixed fields of the tuple. We assume that the syscache + * will be initialized before any access of a partial index could + * occur. (This would probably fail if we were to allow partial + * indexes on system catalogs.) */ exprsDatum = SysCacheGetAttr(INDEXRELID, relation->rd_indextuple, Anum_pg_index_indexprs, &isnull); @@ -2723,8 +2723,8 @@ RelationGetIndexExpressions(Relation relation) pfree(exprsString); /* - * Run the expressions through eval_const_expressions. This is not just - * an optimization, but is necessary, because the planner will be + * Run the expressions through eval_const_expressions. This is not + * just an optimization, but is necessary, because the planner will be * comparing them to const-folded qual clauses, and may fail to detect * valid matches without this. */ @@ -2770,15 +2770,15 @@ RelationGetIndexPredicate(Relation relation) /* * We build the tree we intend to return in the caller's context. - * After successfully completing the work, we copy it into the relcache - * entry. This avoids problems if we get some sort of - * error partway through. + * After successfully completing the work, we copy it into the + * relcache entry. This avoids problems if we get some sort of error + * partway through. * - * We make use of the syscache's copy of pg_index's tupledesc - * to access the non-fixed fields of the tuple. We assume that - * the syscache will be initialized before any access of a - * partial index could occur. (This would probably fail if we - * were to allow partial indexes on system catalogs.) + * We make use of the syscache's copy of pg_index's tupledesc to access + * the non-fixed fields of the tuple. We assume that the syscache + * will be initialized before any access of a partial index could + * occur. (This would probably fail if we were to allow partial + * indexes on system catalogs.) */ predDatum = SysCacheGetAttr(INDEXRELID, relation->rd_indextuple, Anum_pg_index_indpred, &isnull); @@ -2788,8 +2788,8 @@ RelationGetIndexPredicate(Relation relation) pfree(predString); /* - * Run the expression through eval_const_expressions. This is not just - * an optimization, but is necessary, because the planner will be + * Run the expression through eval_const_expressions. This is not + * just an optimization, but is necessary, because the planner will be * comparing it to const-folded qual clauses, and may fail to detect * valid matches without this. */ @@ -3183,7 +3183,7 @@ write_relcache_init_file(void) (errcode_for_file_access(), errmsg("could not create init file \"%s\": %m", tempfilename), - errdetail("Continuing anyway, but there's something wrong."))); + errdetail("Continuing anyway, but there's something wrong."))); return; } @@ -3322,8 +3322,8 @@ write_relcache_init_file(void) { ereport(WARNING, (errcode_for_file_access(), - errmsg("could not rename init file \"%s\" to \"%s\": %m", - tempfilename, finalfilename), + errmsg("could not rename init file \"%s\" to \"%s\": %m", + tempfilename, finalfilename), errdetail("Continuing anyway, but there's something wrong."))); /* diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c index a8d2984009..c848c57e68 100644 --- a/src/backend/utils/error/elog.c +++ b/src/backend/utils/error/elog.c @@ -9,19 +9,19 @@ * if we run out of memory, it's important to be able to report that fact. * There are a number of considerations that go into this. * - * First, distinguish between re-entrant use and actual recursion. It + * First, distinguish between re-entrant use and actual recursion. It * is possible for an error or warning message to be emitted while the - * parameters for an error message are being computed. In this case + * parameters for an error message are being computed. In this case * errstart has been called for the outer message, and some field values - * may have already been saved, but we are not actually recursing. We handle - * this by providing a (small) stack of ErrorData records. The inner message + * may have already been saved, but we are not actually recursing. We handle + * this by providing a (small) stack of ErrorData records. The inner message * can be computed and sent without disturbing the state of the outer message. * (If the inner message is actually an error, this isn't very interesting * because control won't come back to the outer message generator ... but * if the inner message is only debug or log data, this is critical.) * * Second, actual recursion will occur if an error is reported by one of - * the elog.c routines or something they call. By far the most probable + * the elog.c routines or something they call. By far the most probable * scenario of this sort is "out of memory"; and it's also the nastiest * to handle because we'd likely also run out of memory while trying to * report this error! Our escape hatch for this condition is to force any @@ -37,7 +37,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/error/elog.c,v 1.116 2003/08/03 23:44:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/error/elog.c,v 1.117 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -69,8 +69,9 @@ ErrorContextCallback *error_context_stack = NULL; /* GUC parameters */ PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE; -bool Log_timestamp = false; /* show timestamps in stderr output */ -bool Log_pid = false; /* show PIDs in stderr output */ +bool Log_timestamp = false; /* show timestamps in stderr + * output */ +bool Log_pid = false; /* show PIDs in stderr output */ #ifdef HAVE_SYSLOG /* @@ -88,8 +89,7 @@ static void write_syslog(int level, const char *line); #else #define Use_syslog 0 - -#endif /* HAVE_SYSLOG */ +#endif /* HAVE_SYSLOG */ /* @@ -102,8 +102,8 @@ static void write_syslog(int level, const char *line); typedef struct ErrorData { int elevel; /* error level */ - bool output_to_server; /* will report to server log? */ - bool output_to_client; /* will report to client? */ + bool output_to_server; /* will report to server log? */ + bool output_to_client; /* will report to client? */ bool show_funcname; /* true to force funcname inclusion */ const char *filename; /* __FILE__ of ereport() call */ int lineno; /* __LINE__ of ereport() call */ @@ -115,7 +115,7 @@ typedef struct ErrorData char *context; /* context message */ int cursorpos; /* cursor index into query string */ int saved_errno; /* errno at entry */ -} ErrorData; +} ErrorData; /* We provide a small stack of ErrorData records for re-entrant cases */ #define ERRORDATA_STACK_SIZE 5 @@ -124,7 +124,7 @@ static ErrorData errordata[ERRORDATA_STACK_SIZE]; static int errordata_stack_depth = -1; /* index of topmost active frame */ -static int recursion_depth = 0; /* to detect actual recursion */ +static int recursion_depth = 0; /* to detect actual recursion */ /* Macro for checking errordata_stack_depth is reasonable */ @@ -138,9 +138,9 @@ static int recursion_depth = 0; /* to detect actual recursion */ } while (0) -static void send_message_to_server_log(ErrorData *edata); -static void send_message_to_frontend(ErrorData *edata); -static char *expand_fmt_string(const char *fmt, ErrorData *edata); +static void send_message_to_server_log(ErrorData * edata); +static void send_message_to_frontend(ErrorData * edata); +static char *expand_fmt_string(const char *fmt, ErrorData * edata); static const char *useful_strerror(int errnum); static const char *error_severity(int elevel); static const char *print_timestamp(void); @@ -167,9 +167,9 @@ errstart(int elevel, const char *filename, int lineno, bool output_to_client = false; /* - * First decide whether we need to process this report at all; - * if it's warning or less and not enabled for logging, just - * return FALSE without starting up any error logging machinery. + * First decide whether we need to process this report at all; if it's + * warning or less and not enabled for logging, just return FALSE + * without starting up any error logging machinery. */ /* @@ -246,15 +246,16 @@ errstart(int elevel, const char *filename, int lineno, if (recursion_depth++ > 0) { /* - * Ooops, error during error processing. Clear ErrorContext and force - * level up to ERROR or greater, as discussed at top of file. Adjust - * output decisions too. + * Ooops, error during error processing. Clear ErrorContext and + * force level up to ERROR or greater, as discussed at top of + * file. Adjust output decisions too. */ MemoryContextReset(ErrorContext); output_to_server = true; if (whereToSendOutput == Remote && elevel != COMMERROR) output_to_client = true; elevel = Max(elevel, ERROR); + /* * If we recurse more than once, the problem might be something * broken in a context traceback routine. Abandon them too. @@ -265,9 +266,10 @@ errstart(int elevel, const char *filename, int lineno, if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE) { /* Wups, stack not big enough */ - int i; + int i; elevel = Max(elevel, ERROR); + /* * Don't forget any FATAL/PANIC status on the stack (see comments * in errfinish) @@ -311,7 +313,7 @@ errstart(int elevel, const char *filename, int lineno, * See elog.h for the error level definitions. */ void -errfinish(int dummy, ...) +errfinish(int dummy,...) { ErrorData *edata = &errordata[errordata_stack_depth]; int elevel = edata->elevel; @@ -322,8 +324,8 @@ errfinish(int dummy, ...) CHECK_STACK_DEPTH(); /* - * Do processing in ErrorContext, which we hope has enough reserved space - * to report an error. + * Do processing in ErrorContext, which we hope has enough reserved + * space to report an error. */ oldcontext = MemoryContextSwitchTo(ErrorContext); @@ -335,9 +337,7 @@ errfinish(int dummy, ...) for (econtext = error_context_stack; econtext != NULL; econtext = econtext->previous) - { (*econtext->callback) (econtext->arg); - } /* Send to server log, if enabled */ if (edata->output_to_server) @@ -374,15 +374,15 @@ errfinish(int dummy, ...) /* * If the error level is ERROR or more, we are not going to return to - * caller; therefore, if there is any stacked error already in progress - * it will be lost. This is more or less okay, except we do not want - * to have a FATAL or PANIC error downgraded because the reporting process - * was interrupted by a lower-grade error. So check the stack and make - * sure we panic if panic is warranted. + * caller; therefore, if there is any stacked error already in + * progress it will be lost. This is more or less okay, except we do + * not want to have a FATAL or PANIC error downgraded because the + * reporting process was interrupted by a lower-grade error. So check + * the stack and make sure we panic if panic is warranted. */ if (elevel >= ERROR) { - int i; + int i; for (i = 0; i <= errordata_stack_depth; i++) elevel = Max(elevel, errordata[i].elevel); @@ -415,23 +415,24 @@ errfinish(int dummy, ...) /* * For a FATAL error, we let proc_exit clean up and exit. * - * There are several other cases in which we treat ERROR as FATAL - * and go directly to proc_exit: + * There are several other cases in which we treat ERROR as FATAL and + * go directly to proc_exit: * * 1. ExitOnAnyError mode switch is set (initdb uses this). - * - * 2. we have not yet entered the main backend loop (ie, we are in - * the postmaster or in backend startup); we have noplace to recover. * - * 3. the error occurred after proc_exit has begun to run. (It's + * 2. we have not yet entered the main backend loop (ie, we are in + * the postmaster or in backend startup); we have noplace to + * recover. + * + * 3. the error occurred after proc_exit has begun to run. (It's * proc_exit's responsibility to see that this doesn't turn into * infinite recursion!) * * In the last case, we exit with nonzero exit code to indicate that - * something's pretty wrong. We also want to exit with nonzero exit - * code if not running under the postmaster (for example, if we are - * being run from the initdb script, we'd better return an error - * status). + * something's pretty wrong. We also want to exit with nonzero + * exit code if not running under the postmaster (for example, if + * we are being run from the initdb script, we'd better return an + * error status). */ if (elevel == FATAL || ExitOnAnyError || @@ -469,8 +470,8 @@ errfinish(int dummy, ...) * Serious crash time. Postmaster will observe nonzero process * exit status and kill the other backends too. * - * XXX: what if we are *in* the postmaster? abort() won't kill - * our children... + * XXX: what if we are *in* the postmaster? abort() won't kill our + * children... */ ImmediateInterruptOK = false; fflush(stdout); @@ -504,7 +505,7 @@ errcode(int sqlerrcode) /* * errcode_for_file_access --- add SQLSTATE error code to the current error * - * The SQLSTATE code is chosen based on the saved errno value. We assume + * The SQLSTATE code is chosen based on the saved errno value. We assume * that the failing operation was some type of disk file access. * * NOTE: the primary error message string should generally include %m @@ -520,7 +521,7 @@ errcode_for_file_access(void) switch (edata->saved_errno) { - /* Permission-denied failures */ + /* Permission-denied failures */ case EPERM: /* Not super-user */ case EACCES: /* Permission denied */ #ifdef EROFS @@ -529,24 +530,24 @@ errcode_for_file_access(void) edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE; break; - /* Object not found */ + /* Object not found */ case ENOENT: /* No such file or directory */ edata->sqlerrcode = ERRCODE_UNDEFINED_OBJECT; break; - /* Duplicate object */ + /* Duplicate object */ case EEXIST: /* File exists */ edata->sqlerrcode = ERRCODE_DUPLICATE_OBJECT; break; - /* Wrong object type or state */ + /* Wrong object type or state */ case ENOTDIR: /* Not a directory */ case EISDIR: /* Is a directory */ - case ENOTEMPTY: /* Directory not empty */ + case ENOTEMPTY: /* Directory not empty */ edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE; break; - /* Insufficient resources */ + /* Insufficient resources */ case ENOSPC: /* No space left on device */ edata->sqlerrcode = ERRCODE_DISK_FULL; break; @@ -556,12 +557,12 @@ errcode_for_file_access(void) edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES; break; - /* Hardware failure */ + /* Hardware failure */ case EIO: /* I/O error */ edata->sqlerrcode = ERRCODE_IO_ERROR; break; - /* All else is classified as internal errors */ + /* All else is classified as internal errors */ default: edata->sqlerrcode = ERRCODE_INTERNAL_ERROR; break; @@ -573,7 +574,7 @@ errcode_for_file_access(void) /* * errcode_for_socket_access --- add SQLSTATE error code to the current error * - * The SQLSTATE code is chosen based on the saved errno value. We assume + * The SQLSTATE code is chosen based on the saved errno value. We assume * that the failing operation was some type of socket access. * * NOTE: the primary error message string should generally include %m @@ -589,7 +590,7 @@ errcode_for_socket_access(void) switch (edata->saved_errno) { - /* Loss of connection */ + /* Loss of connection */ case EPIPE: #ifdef ECONNRESET case ECONNRESET: @@ -597,7 +598,7 @@ errcode_for_socket_access(void) edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE; break; - /* All else is classified as internal errors */ + /* All else is classified as internal errors */ default: edata->sqlerrcode = ERRCODE_INTERNAL_ERROR; break; @@ -611,7 +612,7 @@ errcode_for_socket_access(void) * This macro handles expansion of a format string and associated parameters; * it's common code for errmsg(), errdetail(), etc. Must be called inside * a routine that is declared like "const char *fmt, ..." and has an edata - * pointer set up. The message is assigned to edata->targetfield, or + * pointer set up. The message is assigned to edata->targetfield, or * appended to it if appendval is true. * * Note: we pstrdup the buffer rather than just transferring its storage @@ -661,7 +662,7 @@ errcode_for_socket_access(void) * ereport will provide one for the output methods that need it. */ int -errmsg(const char *fmt, ...) +errmsg(const char *fmt,...) { ErrorData *edata = &errordata[errordata_stack_depth]; MemoryContext oldcontext; @@ -687,7 +688,7 @@ errmsg(const char *fmt, ...) * spending translation effort on. */ int -errmsg_internal(const char *fmt, ...) +errmsg_internal(const char *fmt,...) { ErrorData *edata = &errordata[errordata_stack_depth]; MemoryContext oldcontext; @@ -708,7 +709,7 @@ errmsg_internal(const char *fmt, ...) * errdetail --- add a detail error message text to the current error */ int -errdetail(const char *fmt, ...) +errdetail(const char *fmt,...) { ErrorData *edata = &errordata[errordata_stack_depth]; MemoryContext oldcontext; @@ -729,7 +730,7 @@ errdetail(const char *fmt, ...) * errhint --- add a hint error message text to the current error */ int -errhint(const char *fmt, ...) +errhint(const char *fmt,...) { ErrorData *edata = &errordata[errordata_stack_depth]; MemoryContext oldcontext; @@ -754,7 +755,7 @@ errhint(const char *fmt, ...) * states. */ int -errcontext(const char *fmt, ...) +errcontext(const char *fmt,...) { ErrorData *edata = &errordata[errordata_stack_depth]; MemoryContext oldcontext; @@ -816,7 +817,7 @@ errposition(int cursorpos) * the true elevel. */ void -elog_finish(int elevel, const char *fmt, ...) +elog_finish(int elevel, const char *fmt,...) { ErrorData *edata = &errordata[errordata_stack_depth]; MemoryContext oldcontext; @@ -870,7 +871,7 @@ DebugFileOpen(void) 0666)) < 0) ereport(FATAL, (errcode_for_file_access(), - errmsg("failed to open \"%s\": %m", OutputFileName))); + errmsg("failed to open \"%s\": %m", OutputFileName))); istty = isatty(fd); close(fd); @@ -1016,7 +1017,6 @@ write_syslog(int level, const char *line) syslog(level, "[%lu] %s", seq, line); } } - #endif /* HAVE_SYSLOG */ @@ -1024,9 +1024,9 @@ write_syslog(int level, const char *line) * Write error report to server's log */ static void -send_message_to_server_log(ErrorData *edata) +send_message_to_server_log(ErrorData * edata) { - StringInfoData buf; + StringInfoData buf; initStringInfo(&buf); @@ -1035,9 +1035,9 @@ send_message_to_server_log(ErrorData *edata) if (Log_error_verbosity >= PGERROR_VERBOSE) { /* unpack MAKE_SQLSTATE code */ - char tbuf[12]; - int ssval; - int i; + char tbuf[12]; + int ssval; + int i; ssval = edata->sqlerrcode; for (i = 0; i < 5; i++) @@ -1080,9 +1080,10 @@ send_message_to_server_log(ErrorData *edata) } /* - * If the user wants the query that generated this error logged, do so. - * We use debug_query_string to get at the query, which is kinda useless - * for queries triggered by extended query protocol; how to improve? + * If the user wants the query that generated this error logged, do + * so. We use debug_query_string to get at the query, which is kinda + * useless for queries triggered by extended query protocol; how to + * improve? */ if (edata->elevel >= log_min_error_statement && debug_query_string != NULL) appendStringInfo(&buf, gettext("STATEMENT: %s\n"), @@ -1150,7 +1151,7 @@ send_message_to_server_log(ErrorData *edata) * Write error report to client */ static void -send_message_to_frontend(ErrorData *edata) +send_message_to_frontend(ErrorData * edata) { StringInfoData msgbuf; @@ -1160,9 +1161,9 @@ send_message_to_frontend(ErrorData *edata) if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3) { /* New style with separate fields */ - char tbuf[12]; - int ssval; - int i; + char tbuf[12]; + int ssval; + int i; pq_sendbyte(&msgbuf, 'S'); pq_sendstring(&msgbuf, error_severity(edata->elevel)); @@ -1230,7 +1231,7 @@ send_message_to_frontend(ErrorData *edata) pq_sendstring(&msgbuf, edata->funcname); } - pq_sendbyte(&msgbuf, '\0'); /* terminator */ + pq_sendbyte(&msgbuf, '\0'); /* terminator */ } else { @@ -1288,9 +1289,9 @@ send_message_to_frontend(ErrorData *edata) * The result is a palloc'd string. */ static char * -expand_fmt_string(const char *fmt, ErrorData *edata) +expand_fmt_string(const char *fmt, ErrorData * edata) { - StringInfoData buf; + StringInfoData buf; const char *cp; initStringInfo(&buf); @@ -1303,9 +1304,9 @@ expand_fmt_string(const char *fmt, ErrorData *edata) if (*cp == 'm') { /* - * Replace %m by system error string. If there are any %'s - * in the string, we'd better double them so that vsnprintf - * won't misinterpret. + * Replace %m by system error string. If there are any + * %'s in the string, we'd better double them so that + * vsnprintf won't misinterpret. */ const char *cp2; @@ -1340,7 +1341,7 @@ useful_strerror(int errnum) { /* this buffer is only used if errno has a bogus value */ static char errorstr_buf[48]; - const char *str; + const char *str; str = strerror(errnum); diff --git a/src/backend/utils/fmgr/dfmgr.c b/src/backend/utils/fmgr/dfmgr.c index e536749441..052711ef45 100644 --- a/src/backend/utils/fmgr/dfmgr.c +++ b/src/backend/utils/fmgr/dfmgr.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/dfmgr.c,v 1.62 2003/07/19 20:20:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/dfmgr.c,v 1.63 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -96,7 +96,7 @@ load_external_function(char *filename, char *funcname, if (stat(fullname, &stat_buf) == -1) ereport(ERROR, (errcode_for_file_access(), - errmsg("could not access file \"%s\": %m", fullname))); + errmsg("could not access file \"%s\": %m", fullname))); for (file_scanner = file_list; file_scanner != (DynamicFileList *) NULL && @@ -404,7 +404,7 @@ find_in_dynamic_libpath(const char *basename) if (len == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), - errmsg("zero-length component in DYNAMIC_LIBRARY_PATH"))); + errmsg("zero-length component in DYNAMIC_LIBRARY_PATH"))); piece = palloc(len + 1); strncpy(piece, p, len); @@ -417,7 +417,7 @@ find_in_dynamic_libpath(const char *basename) if (!is_absolute_path(mangled)) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), - errmsg("DYNAMIC_LIBRARY_PATH component is not absolute"))); + errmsg("DYNAMIC_LIBRARY_PATH component is not absolute"))); full = palloc(strlen(mangled) + 1 + baselen + 1); sprintf(full, "%s/%s", mangled, basename); diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c index 03bf022663..a441909def 100644 --- a/src/backend/utils/fmgr/fmgr.c +++ b/src/backend/utils/fmgr/fmgr.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/fmgr.c,v 1.73 2003/07/25 20:17:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/fmgr.c,v 1.74 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -220,8 +220,8 @@ fmgr_info_cxt_security(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt, if (fbp == NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("internal function \"%s\" is not in table", - prosrc))); + errmsg("internal function \"%s\" is not in table", + prosrc))); pfree(prosrc); /* Should we check that nargs, strict, retset match the table? */ finfo->fn_addr = fbp->func; @@ -619,8 +619,8 @@ fmgr_oldstyle(PG_FUNCTION_ARGS) */ ereport(ERROR, (errcode(ERRCODE_TOO_MANY_ARGUMENTS), - errmsg("function %u has too many arguments (%d > %d)", - fcinfo->flinfo->fn_oid, n_arguments, 16))); + errmsg("function %u has too many arguments (%d > %d)", + fcinfo->flinfo->fn_oid, n_arguments, 16))); returnValue = NULL; /* keep compiler quiet */ break; } @@ -698,7 +698,7 @@ fmgr_security_definer(PG_FUNCTION_ARGS) * NOTE: the simplest way to reliably initialize a FunctionCallInfoData * is to MemSet it to zeroes and then fill in the fields that should be * nonzero. However, in a few of the most heavily used paths, we instead - * just zero the fields that must be zero. This saves a fair number of + * just zero the fields that must be zero. This saves a fair number of * cycles so it's worth the extra maintenance effort. Also see inlined * version of FunctionCall2 in utils/sort/tuplesort.c if you need to change * these routines! @@ -1483,8 +1483,8 @@ fmgr(Oid procedureId,...) if (n_arguments > FUNC_MAX_ARGS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_ARGUMENTS), - errmsg("function %u has too many arguments (%d > %d)", - flinfo.fn_oid, n_arguments, FUNC_MAX_ARGS))); + errmsg("function %u has too many arguments (%d > %d)", + flinfo.fn_oid, n_arguments, FUNC_MAX_ARGS))); va_start(pvar, procedureId); for (i = 0; i < n_arguments; i++) fcinfo.arg[i] = (Datum) va_arg(pvar, char *); @@ -1607,11 +1607,11 @@ pg_detoast_datum_slice(struct varlena * datum, int32 first, int32 count) Oid get_fn_expr_rettype(FmgrInfo *flinfo) { - Node *expr; + Node *expr; /* - * can't return anything useful if we have no FmgrInfo or if - * its fn_expr node has not been initialized + * can't return anything useful if we have no FmgrInfo or if its + * fn_expr node has not been initialized */ if (!flinfo || !flinfo->fn_expr) return InvalidOid; @@ -1629,13 +1629,13 @@ get_fn_expr_rettype(FmgrInfo *flinfo) Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum) { - Node *expr; - List *args; - Oid argtype; + Node *expr; + List *args; + Oid argtype; /* - * can't return anything useful if we have no FmgrInfo or if - * its fn_expr node has not been initialized + * can't return anything useful if we have no FmgrInfo or if its + * fn_expr node has not been initialized */ if (!flinfo || !flinfo->fn_expr) return InvalidOid; diff --git a/src/backend/utils/init/findbe.c b/src/backend/utils/init/findbe.c index a725160ee6..8eb0a7954d 100644 --- a/src/backend/utils/init/findbe.c +++ b/src/backend/utils/init/findbe.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/init/Attic/findbe.c,v 1.35 2003/07/25 20:17:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/init/Attic/findbe.c,v 1.36 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -44,6 +44,7 @@ static int ValidateBinary(char *path) { struct stat buf; + #ifndef WIN32 uid_t euid; struct group *gp; @@ -85,9 +86,9 @@ ValidateBinary(char *path) * dynamic loading). */ #ifdef WIN32 - is_r = buf.st_mode & S_IRUSR; - is_x = buf.st_mode & S_IXUSR; - return is_x ? (is_r ? 0 : -2) : -1; + is_r = buf.st_mode & S_IRUSR; + is_x = buf.st_mode & S_IXUSR; + return is_x ? (is_r ? 0 : -2) : -1; #else euid = geteuid(); if (euid == buf.st_uid) diff --git a/src/backend/utils/init/miscinit.c b/src/backend/utils/init/miscinit.c index ea38b94973..4ccc8042d0 100644 --- a/src/backend/utils/init/miscinit.c +++ b/src/backend/utils/init/miscinit.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.110 2003/08/01 00:15:23 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.111 2003/08/04 00:43:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -482,9 +482,9 @@ GetCharSetByHost(char *TableName, int host, const char *DataDir) * restore the current user id if you need to change it. * ---------------------------------------------------------------- */ -static AclId AuthenticatedUserId = 0; -static AclId SessionUserId = 0; -static AclId CurrentUserId = 0; +static AclId AuthenticatedUserId = 0; +static AclId SessionUserId = 0; +static AclId CurrentUserId = 0; static bool AuthenticatedUserIsSuperuser = false; @@ -620,7 +620,7 @@ SetSessionAuthorization(AclId userid, bool is_superuser) !AuthenticatedUserIsSuperuser) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to set session authorization"))); + errmsg("permission denied to set session authorization"))); SetSessionUserId(userid); SetUserId(userid); @@ -685,15 +685,16 @@ GetUserNameFromId(AclId userid) static void UnlinkLockFile(int status, Datum filename) { - char *fname = (char *)DatumGetPointer(filename); - if( fname != NULL ) - { - if( unlink(fname) != 0 ) + char *fname = (char *) DatumGetPointer(filename); + + if (fname != NULL) { - /* Should we complain if the unlink fails? */ + if (unlink(fname) != 0) + { + /* Should we complain if the unlink fails? */ + } + free(fname); } - free(fname); - } } /* @@ -789,11 +790,11 @@ CreateLockFile(const char *filename, bool amPostmaster, errmsg("lock file \"%s\" already exists", filename), isDDLock ? - errhint("Is another %s (pid %d) running in \"%s\"?", - (encoded_pid < 0 ? "postgres" : "postmaster"), - (int) other_pid, refName) : + errhint("Is another %s (pid %d) running in \"%s\"?", + (encoded_pid < 0 ? "postgres" : "postmaster"), + (int) other_pid, refName) : errhint("Is another %s (pid %d) using \"%s\"?", - (encoded_pid < 0 ? "postgres" : "postmaster"), + (encoded_pid < 0 ? "postgres" : "postmaster"), (int) other_pid, refName))); } } @@ -821,14 +822,14 @@ CreateLockFile(const char *filename, bool amPostmaster, if (PGSharedMemoryIsInUse(id1, id2)) ereport(FATAL, (errcode(ERRCODE_LOCK_FILE_EXISTS), - errmsg("pre-existing shared memory block " - "(key %lu, id %lu) is still in use", - id1, id2), - errhint("If you're sure there are no old " - "backends still running, remove " - "the shared memory block with " - "ipcrm(1), or just delete \"%s\".", - filename))); + errmsg("pre-existing shared memory block " + "(key %lu, id %lu) is still in use", + id1, id2), + errhint("If you're sure there are no old " + "backends still running, remove " + "the shared memory block with " + "ipcrm(1), or just delete \"%s\".", + filename))); } } } @@ -844,7 +845,7 @@ CreateLockFile(const char *filename, bool amPostmaster, errmsg("could not remove old lock file \"%s\": %m", filename), errhint("The file seems accidentally left over, but " - "I couldn't remove it. Please remove the file " + "I couldn't remove it. Please remove the file " "by hand and try again."))); } @@ -865,7 +866,7 @@ CreateLockFile(const char *filename, bool amPostmaster, errno = save_errno ? save_errno : ENOSPC; ereport(FATAL, (errcode_for_file_access(), - errmsg("could not write lock file \"%s\": %m", filename))); + errmsg("could not write lock file \"%s\": %m", filename))); } close(fd); @@ -912,17 +913,17 @@ TouchSocketLockFile(void) if (socketLockFile[0] != '\0') { /* - * utime() is POSIX standard, utimes() is a common alternative; - * if we have neither, fall back to actually reading the file - * (which only sets the access time not mod time, but that should - * be enough in most cases). In all paths, we ignore errors. + * utime() is POSIX standard, utimes() is a common alternative; if + * we have neither, fall back to actually reading the file (which + * only sets the access time not mod time, but that should be + * enough in most cases). In all paths, we ignore errors. */ #ifdef HAVE_UTIME utime(socketLockFile, NULL); -#else /* !HAVE_UTIME */ +#else /* !HAVE_UTIME */ #ifdef HAVE_UTIMES utimes(socketLockFile, NULL); -#else /* !HAVE_UTIMES */ +#else /* !HAVE_UTIMES */ int fd; char buffer[1]; @@ -932,8 +933,8 @@ TouchSocketLockFile(void) read(fd, buffer, sizeof(buffer)); close(fd); } -#endif /* HAVE_UTIMES */ -#endif /* HAVE_UTIME */ +#endif /* HAVE_UTIMES */ +#endif /* HAVE_UTIME */ } } @@ -1072,13 +1073,13 @@ ValidatePgVersion(const char *path) ret = fscanf(file, "%ld.%ld", &file_major, &file_minor); if (ret != 2) - ereport(FATAL, - (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("\"%s\" is not a valid data directory", - path), - errdetail("File \"%s\" does not contain valid data.", - full_path), - errhint("You may need to initdb."))); + ereport(FATAL, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("\"%s\" is not a valid data directory", + path), + errdetail("File \"%s\" does not contain valid data.", + full_path), + errhint("You may need to initdb."))); FreeFile(file); @@ -1087,7 +1088,7 @@ ValidatePgVersion(const char *path) (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("database files are incompatible with server"), errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, " - "which is not compatible with this version %s.", + "which is not compatible with this version %s.", file_major, file_minor, version_string))); } @@ -1098,6 +1099,7 @@ ValidatePgVersion(const char *path) #if defined(__mc68000__) && defined(__ELF__) typedef int32 ((*func_ptr) ()); + #else typedef char *((*func_ptr) ()); #endif @@ -1142,8 +1144,9 @@ process_preload_libraries(char *preload_libraries_string) if (sep) { /* - * a colon separator implies there is an initialization function - * that we need to run in addition to loading the library + * a colon separator implies there is an initialization + * function that we need to run in addition to loading the + * library */ size_t filename_len = sep - tok; size_t funcname_len = strlen(tok) - filename_len - 1; @@ -1167,7 +1170,7 @@ process_preload_libraries(char *preload_libraries_string) initfunc = (func_ptr) load_external_function(filename, funcname, true, NULL); if (initfunc) - (*initfunc)(); + (*initfunc) (); if (funcname) ereport(LOG, @@ -1186,4 +1189,3 @@ process_preload_libraries(char *preload_libraries_string) pfree(rawstring); freeList(elemlist); } - diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c index 9dc96f0653..33c3e6a124 100644 --- a/src/backend/utils/init/postinit.c +++ b/src/backend/utils/init/postinit.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.124 2003/07/25 20:17:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.125 2003/08/04 00:43:26 momjian Exp $ * * *------------------------------------------------------------------------- @@ -124,8 +124,8 @@ ReverifyMyDatabase(const char *name) if (!dbform->datallowconn) ereport(FATAL, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), - errmsg("database \"%s\" is not currently accepting connections", - name))); + errmsg("database \"%s\" is not currently accepting connections", + name))); /* * OK, we're golden. Only other to-do item is to save the encoding @@ -179,8 +179,8 @@ InitCommunication(void) if (!IsUnderPostmaster) /* postmaster already did this */ { /* - * We're running a postgres bootstrap process or a standalone backend. - * Create private "shmem" and semaphores. + * We're running a postgres bootstrap process or a standalone + * backend. Create private "shmem" and semaphores. */ CreateSharedMemoryAndSemaphores(true, MaxBackends, 0); } @@ -272,8 +272,8 @@ InitPostgres(const char *dbname, const char *username) (errcode(ERRCODE_UNDEFINED_DATABASE), errmsg("database \"%s\" does not exist", dbname), - errdetail("The database subdirectory \"%s\" is missing.", - fullpath))); + errdetail("The database subdirectory \"%s\" is missing.", + fullpath))); else ereport(FATAL, (errcode_for_file_access(), @@ -368,7 +368,7 @@ InitPostgres(const char *dbname, const char *username) if (!ThereIsAtLeastOneUser()) ereport(WARNING, (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("no users are defined in this database system"), + errmsg("no users are defined in this database system"), errhint("You should immediately run 'CREATE USER \"%s\" WITH SYSID %d CREATEUSER;'.", username, BOOTSTRAP_USESYSID))); } @@ -395,10 +395,10 @@ InitPostgres(const char *dbname, const char *username) /* * Check a normal user hasn't connected to a superuser reserved slot. - * We can't do this till after we've read the user information, and - * we must do it inside a transaction since checking superuserness - * may require database access. The superuser check is probably the - * most expensive part; don't do it until necessary. + * We can't do this till after we've read the user information, and we + * must do it inside a transaction since checking superuserness may + * require database access. The superuser check is probably the most + * expensive part; don't do it until necessary. */ if (ReservedBackends > 0 && CountEmptyBackendSlots() < ReservedBackends && @@ -419,8 +419,8 @@ InitPostgres(const char *dbname, const char *username) InitializeClientEncoding(); /* - * Now all default states are fully set up. Report them to client - * if appropriate. + * Now all default states are fully set up. Report them to client if + * appropriate. */ BeginReportingGUCOptions(); diff --git a/src/backend/utils/mb/conv.c b/src/backend/utils/mb/conv.c index ec1af6a4e7..c29d1bdc7b 100644 --- a/src/backend/utils/mb/conv.c +++ b/src/backend/utils/mb/conv.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/mb/conv.c,v 1.46 2003/07/25 20:17:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mb/conv.c,v 1.47 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -313,7 +313,7 @@ compare1(const void *p1, const void *p2) v1 = *(unsigned int *) p1; v2 = ((pg_utf_to_local *) p2)->utf; - return (v1 > v2)?1:((v1 == v2)?0:-1); + return (v1 > v2) ? 1 : ((v1 == v2) ? 0 : -1); } /* @@ -328,7 +328,7 @@ compare2(const void *p1, const void *p2) v1 = *(unsigned int *) p1; v2 = ((pg_local_to_utf *) p2)->code; - return (v1 > v2)?1:((v1 == v2)?0:-1); + return (v1 > v2) ? 1 : ((v1 == v2) ? 0 : -1); } /* @@ -373,8 +373,8 @@ UtfToLocal(unsigned char *utf, unsigned char *iso, { ereport(WARNING, (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER), - errmsg("ignoring unconvertible UTF-8 character 0x%04x", - iutf))); + errmsg("ignoring unconvertible UTF-8 character 0x%04x", + iutf))); continue; } if (p->code & 0xff000000) diff --git a/src/backend/utils/mb/mbutils.c b/src/backend/utils/mb/mbutils.c index 6ec2c1ad02..495c492e2b 100644 --- a/src/backend/utils/mb/mbutils.c +++ b/src/backend/utils/mb/mbutils.c @@ -4,7 +4,7 @@ * (currently mule internal code (mic) is used) * Tatsuo Ishii * - * $Header: /cvsroot/pgsql/src/backend/utils/mb/mbutils.c,v 1.42 2003/07/25 20:17:55 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mb/mbutils.c,v 1.43 2003/08/04 00:43:27 momjian Exp $ */ #include "postgres.h" @@ -45,7 +45,7 @@ static int pending_client_encoding = PG_SQL_ASCII; /* Internal functions */ static unsigned char *perform_default_encoding_conversion(unsigned char *src, int len, bool is_client_to_server); -static int cliplen(const unsigned char *str, int len, int limit); +static int cliplen(const unsigned char *str, int len, int limit); /* @@ -108,10 +108,10 @@ SetClientEncoding(int encoding, bool doit) /* * If we're not inside a transaction then we can't do catalog lookups, - * so fail. After backend startup, this could only happen if we - * are re-reading postgresql.conf due to SIGHUP --- so basically this - * just constrains the ability to change client_encoding on the fly - * from postgresql.conf. Which would probably be a stupid thing to do + * so fail. After backend startup, this could only happen if we are + * re-reading postgresql.conf due to SIGHUP --- so basically this just + * constrains the ability to change client_encoding on the fly from + * postgresql.conf. Which would probably be a stupid thing to do * anyway. */ if (!IsTransactionState()) @@ -180,8 +180,8 @@ InitializeClientEncoding(void) if (SetClientEncoding(pending_client_encoding, true) < 0) { /* - * Oops, the requested conversion is not available. - * We couldn't fail before, but we can now. + * Oops, the requested conversion is not available. We couldn't + * fail before, but we can now. */ ereport(FATAL, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), @@ -249,15 +249,15 @@ pg_do_encoding_conversion(unsigned char *src, int len, { ereport(LOG, (errcode(ERRCODE_UNDEFINED_FUNCTION), - errmsg("default conversion proc for %s to %s does not exist", - pg_encoding_to_char(src_encoding), - pg_encoding_to_char(dest_encoding)))); + errmsg("default conversion proc for %s to %s does not exist", + pg_encoding_to_char(src_encoding), + pg_encoding_to_char(dest_encoding)))); return src; } /* - * XXX we should avoid throwing errors in OidFunctionCall. Otherwise we - * are going into infinite loop! So we have to make sure that the + * XXX we should avoid throwing errors in OidFunctionCall. Otherwise + * we are going into infinite loop! So we have to make sure that the * function exists before calling OidFunctionCall. */ if (!SearchSysCacheExists(PROCOID, diff --git a/src/backend/utils/mb/wchar.c b/src/backend/utils/mb/wchar.c index 909a2ae867..566ff571b5 100644 --- a/src/backend/utils/mb/wchar.c +++ b/src/backend/utils/mb/wchar.c @@ -1,7 +1,7 @@ /* * conversion functions between pg_wchar and multibyte streams. * Tatsuo Ishii - * $Id: wchar.c,v 1.32 2003/07/27 04:53:11 tgl Exp $ + * $Id: wchar.c,v 1.33 2003/08/04 00:43:27 momjian Exp $ * * WIN1250 client encoding updated by Pavel Behal * @@ -612,7 +612,7 @@ pg_encoding_max_length(int encoding) * mbstr is not necessarily NULL terminated; length of mbstr is * specified by len. * - * If OK, return TRUE. If a problem is found, return FALSE when noError is + * If OK, return TRUE. If a problem is found, return FALSE when noError is * true; when noError is false, ereport() a descriptive message. */ bool @@ -637,7 +637,7 @@ pg_verifymbstr(const unsigned char *mbstr, int len, bool noError) return false; ereport(ERROR, (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE), - errmsg("UNICODE characters >= 0x10000 are not supported"))); + errmsg("UNICODE characters >= 0x10000 are not supported"))); } l = pg_mblen(mbstr); @@ -659,12 +659,10 @@ pg_verifymbstr(const unsigned char *mbstr, int len, bool noError) return false; jlimit = Min(l, len); - jlimit = Min(jlimit, 8); /* prevent buffer overrun */ + jlimit = Min(jlimit, 8); /* prevent buffer overrun */ for (j = 0; j < jlimit; j++) - { p += sprintf(p, "%02x", mbstr[j]); - } ereport(ERROR, (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE), diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c index d26cefa5d0..da4a508717 100644 --- a/src/backend/utils/misc/guc.c +++ b/src/backend/utils/misc/guc.c @@ -10,7 +10,7 @@ * Written by Peter Eisentraut . * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/misc/guc.c,v 1.146 2003/08/01 01:23:11 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/misc/guc.c,v 1.147 2003/08/04 00:43:27 momjian Exp $ * *-------------------------------------------------------------------- */ @@ -200,34 +200,34 @@ static char *XactIsoLevel_string; * * Note: these strings are deliberately not localized. */ -const char * const GucContext_Names[] = +const char *const GucContext_Names[] = { - /* PGC_INTERNAL */ "internal", - /* PGC_POSTMASTER */ "postmaster", - /* PGC_SIGHUP */ "sighup", - /* PGC_BACKEND */ "backend", - /* PGC_SUSET */ "superuser", - /* PGC_USERLIMIT */ "userlimit", - /* PGC_USERSET */ "user" + /* PGC_INTERNAL */ "internal", + /* PGC_POSTMASTER */ "postmaster", + /* PGC_SIGHUP */ "sighup", + /* PGC_BACKEND */ "backend", + /* PGC_SUSET */ "superuser", + /* PGC_USERLIMIT */ "userlimit", + /* PGC_USERSET */ "user" }; /* * Displayable names for source types (enum GucSource) * * Note: these strings are deliberately not localized. - */ -const char * const GucSource_Names[] = + */ +const char *const GucSource_Names[] = { - /* PGC_S_DEFAULT */ "default", - /* PGC_S_ENV_VAR */ "environment variable", - /* PGC_S_FILE */ "configuration file", - /* PGC_S_ARGV */ "command line", - /* PGC_S_UNPRIVILEGED */ "unprivileged", - /* PGC_S_DATABASE */ "database", - /* PGC_S_USER */ "user", - /* PGC_S_CLIENT */ "client", - /* PGC_S_OVERRIDE */ "override", - /* PGC_S_SESSION */ "session" + /* PGC_S_DEFAULT */ "default", + /* PGC_S_ENV_VAR */ "environment variable", + /* PGC_S_FILE */ "configuration file", + /* PGC_S_ARGV */ "command line", + /* PGC_S_UNPRIVILEGED */ "unprivileged", + /* PGC_S_DATABASE */ "database", + /* PGC_S_USER */ "user", + /* PGC_S_CLIENT */ "client", + /* PGC_S_OVERRIDE */ "override", + /* PGC_S_SESSION */ "session" }; /* @@ -308,12 +308,12 @@ const char *const config_group_names[] = * * Note: these strings are deliberately not localized. */ -const char * const config_type_names[] = +const char *const config_type_names[] = { - /* PGC_BOOL */ "bool", - /* PGC_INT */ "integer", - /* PGC_REAL */ "real", - /* PGC_STRING */ "string" + /* PGC_BOOL */ "bool", + /* PGC_INT */ "integer", + /* PGC_REAL */ "real", + /* PGC_STRING */ "string" }; @@ -1351,7 +1351,7 @@ static struct config_string ConfigureNamesString[] = {"default_transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT, gettext_noop("The default isolation level of each new transaction"), gettext_noop("Each SQL transaction has an isolation level, which " - "can be either \"read committed\" or \"serializable\".") + "can be either \"read committed\" or \"serializable\".") }, &default_iso_level_string, "read committed", assign_defaultxactisolevel, NULL @@ -1800,7 +1800,11 @@ InitializeGUCOptions(void) Assert(conf->reset_val >= conf->min); Assert(conf->reset_val <= conf->max); - /* Check to make sure we only have valid PGC_USERLIMITs */ + + /* + * Check to make sure we only have valid + * PGC_USERLIMITs + */ Assert(conf->gen.context != PGC_USERLIMIT || strcmp(conf->gen.name, "log_min_duration_statement") == 0); if (conf->assign_hook) @@ -1831,11 +1835,14 @@ InitializeGUCOptions(void) struct config_string *conf = (struct config_string *) gconf; char *str; - /* Check to make sure we only have valid PGC_USERLIMITs */ + /* + * Check to make sure we only have valid + * PGC_USERLIMITs + */ Assert(conf->gen.context != PGC_USERLIMIT || conf->assign_hook == assign_log_min_messages || - conf->assign_hook == assign_client_min_messages || - conf->assign_hook == assign_min_error_statement); + conf->assign_hook == assign_client_min_messages || + conf->assign_hook == assign_min_error_statement); *conf->variable = NULL; conf->reset_val = NULL; conf->session_val = NULL; @@ -2434,8 +2441,8 @@ set_config_option(const char *name, const char *value, { ereport(elevel, (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM), - errmsg("\"%s\" cannot be changed after server start", - name))); + errmsg("\"%s\" cannot be changed after server start", + name))); return false; } break; @@ -2474,8 +2481,8 @@ set_config_option(const char *name, const char *value, { ereport(elevel, (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM), - errmsg("\"%s\" cannot be set after connection start", - name))); + errmsg("\"%s\" cannot be set after connection start", + name))); return false; } break; @@ -2514,7 +2521,7 @@ set_config_option(const char *name, const char *value, * to set the reset/session values even if we can't set the variable * itself. */ - DoIt_orig = DoIt; /* we might have to reverse this later */ + DoIt_orig = DoIt; /* we might have to reverse this later */ if (record->source > source) { if (DoIt && !makeDefault) @@ -2554,8 +2561,8 @@ set_config_option(const char *name, const char *value, { ereport(elevel, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to set option \"%s\"", - name), + errmsg("permission denied to set option \"%s\"", + name), errhint("Must be superuser to change this value to false."))); return false; } @@ -2565,7 +2572,7 @@ set_config_option(const char *name, const char *value, record->session_source > PGC_S_UNPRIVILEGED && newval > conf->session_val && !superuser()) - DoIt = DoIt_orig; + DoIt = DoIt_orig; } else { @@ -2630,8 +2637,8 @@ set_config_option(const char *name, const char *value, { ereport(elevel, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("\"%s\" requires an integer value", - name))); + errmsg("\"%s\" requires an integer value", + name))); return false; } if (newval < conf->min || newval > conf->max) @@ -2639,7 +2646,7 @@ set_config_option(const char *name, const char *value, ereport(elevel, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%d is outside the valid range for \"%s\" (%d .. %d)", - newval, name, conf->min, conf->max))); + newval, name, conf->min, conf->max))); return false; } /* Limit non-superuser changes */ @@ -2651,8 +2658,8 @@ set_config_option(const char *name, const char *value, { ereport(elevel, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to set option \"%s\"", - name), + errmsg("permission denied to set option \"%s\"", + name), errhint("Must be superuser to increase this value or set it to zero."))); return false; } @@ -2662,7 +2669,7 @@ set_config_option(const char *name, const char *value, record->session_source > PGC_S_UNPRIVILEGED && newval < conf->session_val && !superuser()) - DoIt = DoIt_orig; + DoIt = DoIt_orig; } else { @@ -2736,7 +2743,7 @@ set_config_option(const char *name, const char *value, ereport(elevel, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%g is outside the valid range for \"%s\" (%g .. %g)", - newval, name, conf->min, conf->max))); + newval, name, conf->min, conf->max))); return false; } /* Limit non-superuser changes */ @@ -2747,8 +2754,8 @@ set_config_option(const char *name, const char *value, { ereport(elevel, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to set option \"%s\"", - name), + errmsg("permission denied to set option \"%s\"", + name), errhint("Must be superuser to increase this value."))); return false; } @@ -2758,7 +2765,7 @@ set_config_option(const char *name, const char *value, record->session_source > PGC_S_UNPRIVILEGED && newval < conf->session_val && !superuser()) - DoIt = DoIt_orig; + DoIt = DoIt_orig; } else { @@ -2831,7 +2838,8 @@ set_config_option(const char *name, const char *value, if (record->context == PGC_USERLIMIT && *conf->variable) { - int old_int_value, new_int_value; + int old_int_value, + new_int_value; /* all USERLIMIT strings are message levels */ assign_msglvl(&old_int_value, conf->reset_val, @@ -2844,10 +2852,10 @@ set_config_option(const char *name, const char *value, !superuser()) { ereport(elevel, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to set option \"%s\"", - name), - errhint("Must be superuser to increase this value."))); + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to set option \"%s\"", + name), + errhint("Must be superuser to increase this value."))); return false; } /* Allow admin to override non-superuser setting */ @@ -2855,7 +2863,7 @@ set_config_option(const char *name, const char *value, record->session_source > PGC_S_UNPRIVILEGED && newval < conf->session_val && !superuser()) - DoIt = DoIt_orig; + DoIt = DoIt_orig; } } else if (conf->reset_val) @@ -2901,8 +2909,8 @@ set_config_option(const char *name, const char *value, free(newval); ereport(elevel, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), - errmsg("invalid value for \"%s\": \"%s\"", - name, value ? value : ""))); + errmsg("invalid value for \"%s\": \"%s\"", + name, value ? value : ""))); return false; } else if (hookresult != newval) @@ -3408,8 +3416,8 @@ GetConfigOptionByName(const char *name, const char **varname) void GetConfigOptionByNum(int varnum, const char **values, bool *noshow) { - char buffer[256]; - struct config_generic *conf; + char buffer[256]; + struct config_generic *conf; /* check requested variable number valid */ Assert((varnum >= 0) && (varnum < num_guc_variables)); @@ -3490,7 +3498,8 @@ GetConfigOptionByNum(int varnum, const char **values, bool *noshow) default: { /* - * should never get here, but in case we do, set 'em to NULL + * should never get here, but in case we do, set 'em to + * NULL */ /* min_val */ @@ -3566,8 +3575,8 @@ show_all_settings(PG_FUNCTION_ARGS) oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); /* - * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns - * of the appropriate types + * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS + * columns of the appropriate types */ tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false); TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name", @@ -4371,7 +4380,7 @@ assign_phony_autocommit(bool newval, bool doit, bool interactive) if (doit && interactive) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("SET AUTOCOMMIT TO OFF is no longer supported"))); + errmsg("SET AUTOCOMMIT TO OFF is no longer supported"))); return false; } return true; diff --git a/src/backend/utils/misc/help_config.c b/src/backend/utils/misc/help_config.c index d5d9736e59..ed117bef18 100644 --- a/src/backend/utils/misc/help_config.c +++ b/src/backend/utils/misc/help_config.c @@ -25,7 +25,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/misc/help_config.c,v 1.3 2003/07/28 19:31:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/misc/help_config.c,v 1.4 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -58,35 +58,35 @@ enum outputFormat MACHINE_OUTPUT }; -static const char * const GENERIC_FORMAT[] = { +static const char *const GENERIC_FORMAT[] = { gettext_noop("Name : %-20s \nContext : %-20s \nGroup : %-20s\n"), gettext_noop("%s\t%s\t%s\t") }; -static const char * const GENERIC_DESC[] = { +static const char *const GENERIC_DESC[] = { gettext_noop("Description: %s\n%s\n"), gettext_noop("%s %s\n") }; -static const char * const BOOL_FORMAT[] = { +static const char *const BOOL_FORMAT[] = { gettext_noop("Type : BOOL\nReset Value: %-s \n"), gettext_noop("BOOL\t%s\t\t\t") }; -static const char * const INT_FORMAT[] = { +static const char *const INT_FORMAT[] = { gettext_noop("Type : INT\nReset Value: %-20d \nMin Value : %-20d \nMax Value : %-20d \n"), gettext_noop("INT\t%d\t%d\t%d\t") }; -static const char * const REAL_FORMAT[] = { +static const char *const REAL_FORMAT[] = { gettext_noop("Type : REAL\nReset Value: %-20g \nMin Value : %-20g \nMax Value : %-20g \n"), gettext_noop("REAL\t%g\t%g\t%g\t") }; -static const char * const STRING_FORMAT[] = { +static const char *const STRING_FORMAT[] = { gettext_noop("Type : STRING\nReset Value: %-s \n"), gettext_noop("STRING\t%s\t\t\t") }; -static const char * const COLUMN_HEADER[] = { +static const char *const COLUMN_HEADER[] = { "", gettext_noop("NAME\tCONTEXT\tGROUP\tTYPE\tRESET_VALUE\tMIN\tMAX\tSHORT_DESCRIPTION\tLONG_DESCRIPTION\n") }; -static const char * const ROW_SEPARATOR[] = { +static const char *const ROW_SEPARATOR[] = { "------------------------------------------------------------\n", "" }; @@ -101,8 +101,8 @@ static char *groupString = NULL; /* The var group pattern to match */ static bool groupRegexBool = false; /* Match the group pattern as a * regex */ static enum outputFormat outFormat = HUMAN_OUTPUT; -static bool suppressAllHeaders = false; /* MACHINE_OUTPUT output, no column - * headers */ +static bool suppressAllHeaders = false; /* MACHINE_OUTPUT output, no + * column headers */ static bool groupResults = true; /* sort result list by groups */ @@ -444,5 +444,5 @@ helpMessage(void) " -m Machine friendly format: tab separated fields\n" " -M Same as m, except header with column names is suppressed\n"), usageErrMsg() - ); + ); } diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index aea4ee09a7..2889952657 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -11,7 +11,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/aset.c,v 1.50 2003/07/25 20:17:56 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/aset.c,v 1.51 2003/08/04 00:43:27 momjian Exp $ * * NOTE: * This is a new (Feb. 05, 1999) implementation of the allocation set @@ -333,8 +333,8 @@ AllocSetContextCreate(MemoryContext parent, ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), - errdetail("Failed while creating memory context \"%s\".", - name))); + errdetail("Failed while creating memory context \"%s\".", + name))); } block->aset = context; block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ; @@ -376,7 +376,7 @@ AllocSetInit(MemoryContext context) * Actually, this routine has some discretion about what to do. * It should mark all allocated chunks freed, but it need not necessarily * give back all the resources the set owns. Our actual implementation is - * that we hang onto any "keeper" block specified for the set. In this way, + * that we hang onto any "keeper" block specified for the set. In this way, * we don't thrash malloc() when a context is repeatedly reset after small * allocations, which is typical behavior for per-tuple contexts. */ @@ -708,13 +708,13 @@ AllocSetAlloc(MemoryContext context, Size size) block->endptr = ((char *) block) + blksize; /* - * If this is the first block of the set, make it the "keeper" block. - * Formerly, a keeper block could only be created during context - * creation, but allowing it to happen here lets us have fast reset - * cycling even for contexts created with minContextSize = 0; that - * way we don't have to force space to be allocated in contexts that - * might never need any space. Don't mark an oversize block as - * a keeper, however. + * If this is the first block of the set, make it the "keeper" + * block. Formerly, a keeper block could only be created during + * context creation, but allowing it to happen here lets us have + * fast reset cycling even for contexts created with + * minContextSize = 0; that way we don't have to force space to be + * allocated in contexts that might never need any space. Don't + * mark an oversize block as a keeper, however. */ if (set->blocks == NULL && blksize == set->initBlockSize) { diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 6055fe5278..859f11d23c 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -14,7 +14,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/mcxt.c,v 1.41 2003/07/25 20:17:56 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/mcxt.c,v 1.42 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,6 +45,7 @@ MemoryContext PostmasterContext = NULL; MemoryContext CacheMemoryContext = NULL; MemoryContext MessageContext = NULL; MemoryContext TopTransactionContext = NULL; + /* These two are transient links to contexts owned by other objects: */ MemoryContext QueryContext = NULL; MemoryContext PortalContext = NULL; @@ -494,7 +495,7 @@ MemoryContextAlloc(MemoryContext context, Size size) void * MemoryContextAllocZero(MemoryContext context, Size size) { - void *ret; + void *ret; AssertArg(MemoryContextIsValid(context)); @@ -519,7 +520,7 @@ MemoryContextAllocZero(MemoryContext context, Size size) void * MemoryContextAllocZeroAligned(MemoryContext context, Size size) { - void *ret; + void *ret; AssertArg(MemoryContextIsValid(context)); diff --git a/src/backend/utils/mmgr/portalmem.c b/src/backend/utils/mmgr/portalmem.c index 918d03fb90..81bf887710 100644 --- a/src/backend/utils/mmgr/portalmem.c +++ b/src/backend/utils/mmgr/portalmem.c @@ -12,7 +12,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/portalmem.c,v 1.59 2003/07/25 20:17:56 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/portalmem.c,v 1.60 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -228,7 +228,7 @@ CreateNewPortal(void) * A simple subroutine to establish a portal's query. * * Notes: commandTag shall be NULL if and only if the original query string - * (before rewriting) was an empty string. Also, the passed commandTag must + * (before rewriting) was an empty string. Also, the passed commandTag must * be a pointer to a constant string, since it is not copied. The caller is * responsible for ensuring that the passed sourceText (if any), parse and * plan trees have adequate lifetime. Also, queryContext must accurately @@ -243,7 +243,7 @@ PortalDefineQuery(Portal portal, MemoryContext queryContext) { AssertArg(PortalIsValid(portal)); - AssertState(portal->queryContext == NULL); /* else defined already */ + AssertState(portal->queryContext == NULL); /* else defined already */ Assert(length(parseTrees) == length(planTrees)); @@ -269,8 +269,8 @@ PortalCreateHoldStore(Portal portal) Assert(portal->holdStore == NULL); /* - * Create the memory context that is used for storage of the tuple set. - * Note this is NOT a child of the portal's heap memory. + * Create the memory context that is used for storage of the tuple + * set. Note this is NOT a child of the portal's heap memory. */ portal->holdContext = AllocSetContextCreate(PortalMemory, @@ -306,9 +306,9 @@ PortalDrop(Portal portal, bool isError) /* * Remove portal from hash table. Because we do this first, we will - * not come back to try to remove the portal again if there's any error - * in the subsequent steps. Better to leak a little memory than to get - * into an infinite error-recovery loop. + * not come back to try to remove the portal again if there's any + * error in the subsequent steps. Better to leak a little memory than + * to get into an infinite error-recovery loop. */ PortalHashTableDelete(portal); @@ -358,7 +358,7 @@ DropDependentPortals(MemoryContext queryContext) while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL) { - Portal portal = hentry->portal; + Portal portal = hentry->portal; if (portal->queryContext == queryContext) PortalDrop(portal, false); @@ -391,11 +391,11 @@ AtCommit_Portals(void) while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL) { - Portal portal = hentry->portal; + Portal portal = hentry->portal; /* - * Do not touch active portals --- this can only happen in the case of - * a multi-transaction utility command, such as VACUUM. + * Do not touch active portals --- this can only happen in the + * case of a multi-transaction utility command, such as VACUUM. */ if (portal->portalActive) continue; @@ -403,18 +403,19 @@ AtCommit_Portals(void) if (portal->cursorOptions & CURSOR_OPT_HOLD) { /* - * Do nothing to cursors held over from a previous transaction. + * Do nothing to cursors held over from a previous + * transaction. */ if (portal->createXact != xact) continue; /* * We are exiting the transaction that created a holdable - * cursor. Instead of dropping the portal, prepare it for + * cursor. Instead of dropping the portal, prepare it for * access by later transactions. * - * Note that PersistHoldablePortal() must release all - * resources used by the portal that are local to the creating + * Note that PersistHoldablePortal() must release all resources + * used by the portal that are local to the creating * transaction. */ PortalCreateHoldStore(portal); @@ -450,15 +451,15 @@ AtAbort_Portals(void) while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL) { - Portal portal = hentry->portal; + Portal portal = hentry->portal; portal->portalActive = false; /* - * Do nothing else to cursors held over from a previous transaction. - * (This test must include checking CURSOR_OPT_HOLD, else we will - * fail to clean up a VACUUM portal if it fails after its first - * sub-transaction.) + * Do nothing else to cursors held over from a previous + * transaction. (This test must include checking CURSOR_OPT_HOLD, + * else we will fail to clean up a VACUUM portal if it fails after + * its first sub-transaction.) */ if (portal->createXact != xact && (portal->cursorOptions & CURSOR_OPT_HOLD)) @@ -489,7 +490,7 @@ AtCleanup_Portals(void) while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL) { - Portal portal = hentry->portal; + Portal portal = hentry->portal; /* * Let's just make sure no one's active... @@ -497,10 +498,10 @@ AtCleanup_Portals(void) portal->portalActive = false; /* - * Do nothing else to cursors held over from a previous transaction. - * (This test must include checking CURSOR_OPT_HOLD, else we will - * fail to clean up a VACUUM portal if it fails after its first - * sub-transaction.) + * Do nothing else to cursors held over from a previous + * transaction. (This test must include checking CURSOR_OPT_HOLD, + * else we will fail to clean up a VACUUM portal if it fails after + * its first sub-transaction.) */ if (portal->createXact != xact && (portal->cursorOptions & CURSOR_OPT_HOLD)) diff --git a/src/backend/utils/sort/logtape.c b/src/backend/utils/sort/logtape.c index 185c78d2e2..783ceb3a63 100644 --- a/src/backend/utils/sort/logtape.c +++ b/src/backend/utils/sort/logtape.c @@ -64,7 +64,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/sort/logtape.c,v 1.10 2003/07/25 20:17:58 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/sort/logtape.c,v 1.11 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -197,7 +197,7 @@ ltsWriteBlock(LogicalTapeSet *lts, long blocknum, void *buffer) if (BufFileSeekBlock(lts->pfile, blocknum) != 0 || BufFileWrite(lts->pfile, buffer, BLCKSZ) != BLCKSZ) ereport(ERROR, - /* XXX is it okay to assume errno is correct? */ + /* XXX is it okay to assume errno is correct? */ (errcode_for_file_access(), errmsg("could not write block %ld of temporary file: %m", blocknum), @@ -216,7 +216,7 @@ ltsReadBlock(LogicalTapeSet *lts, long blocknum, void *buffer) if (BufFileSeekBlock(lts->pfile, blocknum) != 0 || BufFileRead(lts->pfile, buffer, BLCKSZ) != BLCKSZ) ereport(ERROR, - /* XXX is it okay to assume errno is correct? */ + /* XXX is it okay to assume errno is correct? */ (errcode_for_file_access(), errmsg("could not read block %ld of temporary file: %m", blocknum))); diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c index eb91a8e71b..75c90c9a54 100644 --- a/src/backend/utils/sort/tuplesort.c +++ b/src/backend/utils/sort/tuplesort.c @@ -78,7 +78,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplesort.c,v 1.34 2003/07/25 20:17:59 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplesort.c,v 1.35 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -1715,12 +1715,12 @@ SelectSortFunction(Oid sortOperator, Oid opclass = InvalidOid; /* - * Search pg_amop to see if the target operator is registered as the "<" - * or ">" operator of any btree opclass. It's possible that it might - * be registered both ways (eg, if someone were to build a "reverse - * sort" opclass for some reason); prefer the "<" case if so. If the - * operator is registered the same way in multiple opclasses, assume - * we can use the associated comparator function from any one. + * Search pg_amop to see if the target operator is registered as the + * "<" or ">" operator of any btree opclass. It's possible that it + * might be registered both ways (eg, if someone were to build a + * "reverse sort" opclass for some reason); prefer the "<" case if so. + * If the operator is registered the same way in multiple opclasses, + * assume we can use the associated comparator function from any one. */ catlist = SearchSysCacheList(AMOPOPID, 1, ObjectIdGetDatum(sortOperator), diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c index 8818c2203f..e6e01b83ed 100644 --- a/src/backend/utils/sort/tuplestore.c +++ b/src/backend/utils/sort/tuplestore.c @@ -8,7 +8,7 @@ * a dumbed-down version of tuplesort.c; it does no sorting of tuples * but can only store and regurgitate a sequence of tuples. However, * because no sort is required, it is allowed to start reading the sequence - * before it has all been written. This is particularly useful for cursors, + * before it has all been written. This is particularly useful for cursors, * because it allows random access within the already-scanned portion of * a query without having to process the underlying scan to completion. * A temporary file is used to handle the data if it exceeds the @@ -27,7 +27,7 @@ * * Because we allow reading before writing is complete, there are two * interesting positions in the temp file: the current read position and - * the current write position. At any given instant, the temp file's seek + * the current write position. At any given instant, the temp file's seek * position corresponds to one of these, and the other one is remembered in * the Tuplestore's state. * @@ -36,7 +36,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplestore.c,v 1.14 2003/07/25 20:18:00 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplestore.c,v 1.15 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -114,11 +114,11 @@ struct Tuplestorestate * These variables are used to keep track of the current position. * * In state WRITEFILE, the current file seek position is the write point, - * and the read position is remembered in readpos_xxx; in state READFILE, - * the current file seek position is the read point, and the write position - * is remembered in writepos_xxx. (The write position is the same as EOF, - * but since BufFileSeek doesn't currently implement SEEK_END, we have - * to remember it explicitly.) + * and the read position is remembered in readpos_xxx; in state + * READFILE, the current file seek position is the read point, and the + * write position is remembered in writepos_xxx. (The write position + * is the same as EOF, but since BufFileSeek doesn't currently + * implement SEEK_END, we have to remember it explicitly.) * * Special case: if we are in WRITEFILE state and eof_reached is true, * then the read position is implicitly equal to the write position @@ -130,10 +130,10 @@ struct Tuplestorestate int readpos_file; /* file# (valid if WRITEFILE and not eof) */ long readpos_offset; /* offset (valid if WRITEFILE and not eof) */ int writepos_file; /* file# (valid if READFILE) */ - long writepos_offset; /* offset (valid if READFILE) */ + long writepos_offset; /* offset (valid if READFILE) */ /* markpos_xxx holds marked position for mark and restore */ - int markpos_current; /* saved "current" */ + int markpos_current; /* saved "current" */ int markpos_file; /* saved "readpos_file" */ long markpos_offset; /* saved "readpos_offset" */ }; @@ -191,8 +191,8 @@ struct Tuplestorestate static Tuplestorestate *tuplestore_begin_common(bool randomAccess, - bool interXact, - int maxKBytes); + bool interXact, + int maxKBytes); static void dumptuples(Tuplestorestate *state); static unsigned int getlen(Tuplestorestate *state, bool eofOK); static void *copytup_heap(Tuplestorestate *state, void *tup); @@ -244,7 +244,7 @@ tuplestore_begin_common(bool randomAccess, bool interXact, int maxKBytes) * tuple store are allowed. * * interXact: if true, the files used for on-disk storage persist beyond the - * end of the current transaction. NOTE: It's the caller's responsibility to + * end of the current transaction. NOTE: It's the caller's responsibility to * create such a tuplestore in a memory context that will also survive * transaction boundaries, and to ensure the tuplestore is closed when it's * no longer wanted. @@ -352,6 +352,7 @@ tuplestore_puttuple(Tuplestorestate *state, void *tuple) WRITETUP(state, tuple); break; case TSS_READFILE: + /* * Switch from reading to writing. */ @@ -421,6 +422,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward, /* Skip state change if we'll just return NULL */ if (state->eof_reached && forward) return NULL; + /* * Switch from writing to reading. */ @@ -428,7 +430,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward, &state->writepos_file, &state->writepos_offset); if (!state->eof_reached) if (BufFileSeek(state->myfile, - state->readpos_file, state->readpos_offset, + state->readpos_file, state->readpos_offset, SEEK_SET) != 0) elog(ERROR, "seek failed"); state->status = TSS_READFILE; @@ -456,9 +458,8 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward, * if all tuples are fetched already then we return last tuple, * else - tuple before last returned. * - * Back up to fetch previously-returned tuple's ending - * length word. If seek fails, assume we are at start of - * file. + * Back up to fetch previously-returned tuple's ending length + * word. If seek fails, assume we are at start of file. */ if (BufFileSeek(state->myfile, 0, -(long) sizeof(unsigned int), SEEK_CUR) != 0) @@ -524,7 +525,7 @@ dumptuples(Tuplestorestate *state) { int i; - for (i = 0; ; i++) + for (i = 0;; i++) { if (i == state->current) BufFileTell(state->myfile, diff --git a/src/backend/utils/time/tqual.c b/src/backend/utils/time/tqual.c index aec543d0ac..141381b30e 100644 --- a/src/backend/utils/time/tqual.c +++ b/src/backend/utils/time/tqual.c @@ -16,7 +16,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/time/tqual.c,v 1.65 2003/07/25 20:18:00 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/time/tqual.c,v 1.66 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -77,6 +77,7 @@ HeapTupleSatisfiesItself(HeapTupleHeader tuple) if (tuple->t_infomask & HEAP_MOVED_OFF) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return false; if (!TransactionIdIsInProgress(xvac)) @@ -92,6 +93,7 @@ HeapTupleSatisfiesItself(HeapTupleHeader tuple) else if (tuple->t_infomask & HEAP_MOVED_IN) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (!TransactionIdIsCurrentTransactionId(xvac)) { if (TransactionIdIsInProgress(xvac)) @@ -218,6 +220,7 @@ HeapTupleSatisfiesNow(HeapTupleHeader tuple) if (tuple->t_infomask & HEAP_MOVED_OFF) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return false; if (!TransactionIdIsInProgress(xvac)) @@ -233,6 +236,7 @@ HeapTupleSatisfiesNow(HeapTupleHeader tuple) else if (tuple->t_infomask & HEAP_MOVED_IN) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (!TransactionIdIsCurrentTransactionId(xvac)) { if (TransactionIdIsInProgress(xvac)) @@ -340,6 +344,7 @@ HeapTupleSatisfiesToast(HeapTupleHeader tuple) if (tuple->t_infomask & HEAP_MOVED_OFF) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return false; if (!TransactionIdIsInProgress(xvac)) @@ -355,6 +360,7 @@ HeapTupleSatisfiesToast(HeapTupleHeader tuple) else if (tuple->t_infomask & HEAP_MOVED_IN) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (!TransactionIdIsCurrentTransactionId(xvac)) { if (TransactionIdIsInProgress(xvac)) @@ -395,6 +401,7 @@ HeapTupleSatisfiesUpdate(HeapTuple htuple, CommandId curcid) if (tuple->t_infomask & HEAP_MOVED_OFF) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return HeapTupleInvisible; if (!TransactionIdIsInProgress(xvac)) @@ -410,6 +417,7 @@ HeapTupleSatisfiesUpdate(HeapTuple htuple, CommandId curcid) else if (tuple->t_infomask & HEAP_MOVED_IN) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (!TransactionIdIsCurrentTransactionId(xvac)) { if (TransactionIdIsInProgress(xvac)) @@ -531,6 +539,7 @@ HeapTupleSatisfiesDirty(HeapTupleHeader tuple) if (tuple->t_infomask & HEAP_MOVED_OFF) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return false; if (!TransactionIdIsInProgress(xvac)) @@ -546,6 +555,7 @@ HeapTupleSatisfiesDirty(HeapTupleHeader tuple) else if (tuple->t_infomask & HEAP_MOVED_IN) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (!TransactionIdIsCurrentTransactionId(xvac)) { if (TransactionIdIsInProgress(xvac)) @@ -667,6 +677,7 @@ HeapTupleSatisfiesSnapshot(HeapTupleHeader tuple, Snapshot snapshot) if (tuple->t_infomask & HEAP_MOVED_OFF) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return false; if (!TransactionIdIsInProgress(xvac)) @@ -682,6 +693,7 @@ HeapTupleSatisfiesSnapshot(HeapTupleHeader tuple, Snapshot snapshot) else if (tuple->t_infomask & HEAP_MOVED_IN) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (!TransactionIdIsCurrentTransactionId(xvac)) { if (TransactionIdIsInProgress(xvac)) @@ -827,6 +839,7 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) else if (tuple->t_infomask & HEAP_MOVED_OFF) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return HEAPTUPLE_DELETE_IN_PROGRESS; if (TransactionIdIsInProgress(xvac)) @@ -841,6 +854,7 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) else if (tuple->t_infomask & HEAP_MOVED_IN) { TransactionId xvac = HeapTupleHeaderGetXvac(tuple); + if (TransactionIdIsCurrentTransactionId(xvac)) return HEAPTUPLE_INSERT_IN_PROGRESS; if (TransactionIdIsInProgress(xvac)) @@ -860,7 +874,8 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) else { /* - * Not in Progress, Not Committed, so either Aborted or crashed + * Not in Progress, Not Committed, so either Aborted or + * crashed */ tuple->t_infomask |= HEAP_XMIN_INVALID; return HEAPTUPLE_DEAD; @@ -888,10 +903,11 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) { if (TransactionIdIsInProgress(HeapTupleHeaderGetXmax(tuple))) return HEAPTUPLE_LIVE; + /* - * We don't really care whether xmax did commit, abort or crash. - * We know that xmax did mark the tuple for update, but it did not - * and will never actually update it. + * We don't really care whether xmax did commit, abort or + * crash. We know that xmax did mark the tuple for update, but + * it did not and will never actually update it. */ tuple->t_infomask |= HEAP_XMAX_INVALID; } @@ -907,7 +923,8 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) else { /* - * Not in Progress, Not Committed, so either Aborted or crashed + * Not in Progress, Not Committed, so either Aborted or + * crashed */ tuple->t_infomask |= HEAP_XMAX_INVALID; return HEAPTUPLE_LIVE; @@ -1014,9 +1031,8 @@ void FreeXactSnapshot(void) { /* - * We do not free(QuerySnapshot->xip); - * or free(SerializableSnapshot->xip); - * they will be reused soon + * We do not free(QuerySnapshot->xip); or + * free(SerializableSnapshot->xip); they will be reused soon */ QuerySnapshot = NULL; SerializableSnapshot = NULL; diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c index 10a6ed93cc..c976e5af31 100644 --- a/src/bin/pg_controldata/pg_controldata.c +++ b/src/bin/pg_controldata/pg_controldata.c @@ -6,7 +6,7 @@ * copyright (c) Oliver Elphick , 2001; * licence: BSD * - * $Header: /cvsroot/pgsql/src/bin/pg_controldata/pg_controldata.c,v 1.10 2003/07/23 08:47:25 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_controldata/pg_controldata.c,v 1.11 2003/08/04 00:43:27 momjian Exp $ */ #include "postgres.h" @@ -27,17 +27,17 @@ usage(const char *progname) { printf(_("%s displays control information of a PostgreSQL database cluster.\n\n"), progname); printf - ( - _( - "Usage:\n" - " %s [OPTION]\n\n" - "Options:\n" - " DATADIR show cluster control information for DATADIR\n" - " --help show this help, then exit\n" - " --version output version information, then exit\n" - ), - progname - ); + ( + _( + "Usage:\n" + " %s [OPTION]\n\n" + "Options:\n" + " DATADIR show cluster control information for DATADIR\n" + " --help show this help, then exit\n" + " --version output version information, then exit\n" + ), + progname + ); printf(_("\nIf no data directory is specified, the environment variable PGDATA\nis used.\n\n")); printf(_("Report bugs to .\n")); } diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c index e404924f44..2c2537b9d8 100644 --- a/src/bin/pg_dump/common.c +++ b/src/bin/pg_dump/common.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/common.c,v 1.73 2003/07/23 08:47:30 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/common.c,v 1.74 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -290,9 +290,9 @@ flagInhAttrs(TableInfo *tblinfo, int numTables, * attr with the same name, then only dump it if: * * - it is NOT NULL and zero parents are NOT NULL - * OR + * OR * - it has a default value AND the default value does not match - * all parent default values, or no parents specify a default. + * all parent default values, or no parents specify a default. * * See discussion on -hackers around 2-Apr-2001. *---------------------------------------------------------------- @@ -364,9 +364,7 @@ flagInhAttrs(TableInfo *tblinfo, int numTables, /* Clear it if attr has local definition */ if (g_fout->remoteVersion >= 70300 && tblinfo[i].attislocal[j]) - { tblinfo[i].inhAttrs[j] = false; - } } } } diff --git a/src/bin/pg_dump/dumputils.c b/src/bin/pg_dump/dumputils.c index 095d2fc864..100f54fefc 100644 --- a/src/bin/pg_dump/dumputils.c +++ b/src/bin/pg_dump/dumputils.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/pg_dump/dumputils.c,v 1.6 2003/07/31 17:21:57 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/dumputils.c,v 1.7 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -23,9 +23,9 @@ static bool parseAclArray(const char *acls, char ***itemarray, int *nitems); static bool parseAclItem(const char *item, const char *type, const char *name, - int remoteVersion, - PQExpBuffer grantee, PQExpBuffer grantor, - PQExpBuffer privs, PQExpBuffer privswgo); + int remoteVersion, + PQExpBuffer grantee, PQExpBuffer grantor, + PQExpBuffer privs, PQExpBuffer privswgo); static char *copyAclUserName(PQExpBuffer output, char *input); static void AddAcl(PQExpBuffer aclbuf, const char *keyword); @@ -191,8 +191,12 @@ buildACLCommands(const char *name, const char *type, char **aclitems; int naclitems; int i; - PQExpBuffer grantee, grantor, privs, privswgo; - PQExpBuffer firstsql, secondsql; + PQExpBuffer grantee, + grantor, + privs, + privswgo; + PQExpBuffer firstsql, + secondsql; bool found_owner_privs = false; if (strlen(acls) == 0) @@ -209,13 +213,14 @@ buildACLCommands(const char *name, const char *type, grantor = createPQExpBuffer(); privs = createPQExpBuffer(); privswgo = createPQExpBuffer(); + /* - * At the end, these two will be pasted together to form the - * result. But the owner privileges need to go before the other - * ones to keep the dependencies valid. In recent versions this - * is normally the case, but in old versions they come after the - * PUBLIC privileges and that results in problems if we need to - * run REVOKE on the owner privileges. + * At the end, these two will be pasted together to form the result. + * But the owner privileges need to go before the other ones to keep + * the dependencies valid. In recent versions this is normally the + * case, but in old versions they come after the PUBLIC privileges and + * that results in problems if we need to run REVOKE on the owner + * privileges. */ firstsql = createPQExpBuffer(); secondsql = createPQExpBuffer(); @@ -245,9 +250,10 @@ buildACLCommands(const char *name, const char *type, && strcmp(grantor->data, owner) == 0) { found_owner_privs = true; + /* - * For the owner, the default privilege level is ALL - * WITH GRANT OPTION (only ALL prior to 7.4). + * For the owner, the default privilege level is ALL WITH + * GRANT OPTION (only ALL prior to 7.4). */ if (supports_grant_options(remoteVersion) ? strcmp(privswgo->data, "ALL") != 0 @@ -285,7 +291,7 @@ buildACLCommands(const char *name, const char *type, else if (strncmp(grantee->data, "group ", strlen("group ")) == 0) appendPQExpBuffer(secondsql, "GROUP %s;\n", - fmtId(grantee->data + strlen("group "))); + fmtId(grantee->data + strlen("group "))); else appendPQExpBuffer(secondsql, "%s;\n", fmtId(grantee->data)); } @@ -298,7 +304,7 @@ buildACLCommands(const char *name, const char *type, else if (strncmp(grantee->data, "group ", strlen("group ")) == 0) appendPQExpBuffer(secondsql, "GROUP %s", - fmtId(grantee->data + strlen("group "))); + fmtId(grantee->data + strlen("group "))); else appendPQExpBuffer(secondsql, "%s", fmtId(grantee->data)); appendPQExpBuffer(secondsql, " WITH GRANT OPTION;\n"); @@ -340,7 +346,7 @@ buildACLCommands(const char *name, const char *type, * into individual items. * * On success, returns true and sets *itemarray and *nitems to describe - * an array of individual strings. On parse failure, returns false; + * an array of individual strings. On parse failure, returns false; * *itemarray may exist or be NULL. * * NOTE: free'ing itemarray is sufficient to deallocate the working storage. @@ -354,19 +360,21 @@ parseAclArray(const char *acls, char ***itemarray, int *nitems) int curitem; /* - * We expect input in the form of "{item,item,item}" where any item - * is either raw data, or surrounded by double quotes (in which case - * embedded characters including backslashes and quotes are backslashed). + * We expect input in the form of "{item,item,item}" where any item is + * either raw data, or surrounded by double quotes (in which case + * embedded characters including backslashes and quotes are + * backslashed). * * We build the result as an array of pointers followed by the actual - * string data, all in one malloc block for convenience of deallocation. - * The worst-case storage need is not more than one pointer and one - * character for each input character (consider "{,,,,,,,,,,}"). + * string data, all in one malloc block for convenience of + * deallocation. The worst-case storage need is not more than one + * pointer and one character for each input character (consider + * "{,,,,,,,,,,}"). */ *itemarray = NULL; *nitems = 0; inputlen = strlen(acls); - if (inputlen < 2 || acls[0] != '{' || acls[inputlen-1] != '}') + if (inputlen < 2 || acls[0] != '{' || acls[inputlen - 1] != '}') return false; /* bad input */ items = (char **) malloc(inputlen * (sizeof(char *) + sizeof(char))); if (items == NULL) @@ -384,9 +392,9 @@ parseAclArray(const char *acls, char ***itemarray, int *nitems) while (*acls != '}' && *acls != ',') { if (*acls == '\0') - return false; /* premature end of string */ + return false; /* premature end of string */ if (*acls != '"') - *strings++ = *acls++; /* copy unquoted data */ + *strings++ = *acls++; /* copy unquoted data */ else { /* process quoted substring */ @@ -394,14 +402,14 @@ parseAclArray(const char *acls, char ***itemarray, int *nitems) while (*acls != '"') { if (*acls == '\0') - return false; /* premature end of string */ + return false; /* premature end of string */ if (*acls == '\\') { acls++; if (*acls == '\0') - return false; /* premature end of string */ + return false; /* premature end of string */ } - *strings++ = *acls++; /* copy quoted data */ + *strings++ = *acls++; /* copy quoted data */ } acls++; } @@ -426,7 +434,7 @@ parseAclArray(const char *acls, char ***itemarray, int *nitems) * * The returned grantee string will be the dequoted username or groupname * (preceded with "group " in the latter case). The returned grantor is - * the dequoted grantor name or empty. Privilege characters are decoded + * the dequoted grantor name or empty. Privilege characters are decoded * and split between privileges with grant option (privswgo) and without * (privs). * @@ -559,11 +567,12 @@ copyAclUserName(PQExpBuffer output, char *input) while (*input != '"') { if (*input == '\0') - return input; /* really a syntax error... */ + return input; /* really a syntax error... */ + /* * There is no quoting convention here, thus we can't cope - * with usernames containing double quotes. Keep this code - * in sync with putid() in backend's acl.c. + * with usernames containing double quotes. Keep this + * code in sync with putid() in backend's acl.c. */ appendPQExpBufferChar(output, *input++); } diff --git a/src/bin/pg_dump/dumputils.h b/src/bin/pg_dump/dumputils.h index 41946af31a..8d8d2b740d 100644 --- a/src/bin/pg_dump/dumputils.h +++ b/src/bin/pg_dump/dumputils.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: dumputils.h,v 1.5 2003/05/30 22:55:15 tgl Exp $ + * $Id: dumputils.h,v 1.6 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -22,11 +22,11 @@ extern char *simple_prompt(const char *prompt, int maxlen, bool echo); extern const char *fmtId(const char *identifier); extern void appendStringLiteral(PQExpBuffer buf, const char *str, - bool escapeAll); -extern int parse_version(const char *versionString); + bool escapeAll); +extern int parse_version(const char *versionString); extern bool buildACLCommands(const char *name, const char *type, - const char *acls, const char *owner, - int remoteVersion, - PQExpBuffer sql); + const char *acls, const char *owner, + int remoteVersion, + PQExpBuffer sql); #endif /* DUMPUTILS_H */ diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c index 5acfc08ba3..294d92682c 100644 --- a/src/bin/pg_dump/pg_backup_archiver.c +++ b/src/bin/pg_dump/pg_backup_archiver.c @@ -15,7 +15,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.73 2003/07/23 08:47:30 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.74 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -206,7 +206,7 @@ RestoreArchive(Archive *AHX, RestoreOptions *ropt) sav = SetOutput(AH, ropt->filename, ropt->compression); ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n"); - + /* * Drop the items at the start, in reverse order */ @@ -280,7 +280,7 @@ RestoreArchive(Archive *AHX, RestoreOptions *ropt) /* * If we can output the data, then restore it. */ - if (AH->PrintTocDataPtr != NULL && (reqs & REQ_DATA) != 0) + if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0) { #ifndef HAVE_LIBZ if (AH->compression != 0) @@ -1292,7 +1292,8 @@ _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_lis { _write_msg(modulename, fmt, ap); - if (AH) { + if (AH) + { if (AH->public.verbose) write_msg(NULL, "*** aborted because of error\n"); if (AH->connection) @@ -1383,7 +1384,7 @@ TocIDRequired(ArchiveHandle *AH, int id, RestoreOptions *ropt) size_t WriteOffset(ArchiveHandle *AH, off_t o, int wasSet) { - int off; + int off; /* Save the flag */ (*AH->WriteBytePtr) (AH, wasSet); @@ -1391,7 +1392,7 @@ WriteOffset(ArchiveHandle *AH, off_t o, int wasSet) /* Write out off_t smallest byte first, prevents endian mismatch */ for (off = 0; off < sizeof(off_t); off++) { - (*AH->WriteBytePtr) (AH, o & 0xFF); + (*AH->WriteBytePtr) (AH, o & 0xFF); o >>= 8; } return sizeof(off_t) + 1; @@ -1400,9 +1401,9 @@ WriteOffset(ArchiveHandle *AH, off_t o, int wasSet) int ReadOffset(ArchiveHandle *AH, off_t *o) { - int i; - int off; - int offsetFlg; + int i; + int off; + int offsetFlg; /* Initialize to zero */ *o = 0; @@ -1414,21 +1415,21 @@ ReadOffset(ArchiveHandle *AH, off_t *o) i = ReadInt(AH); /* -1 means not set */ if (i < 0) - return K_OFFSET_POS_NOT_SET; + return K_OFFSET_POS_NOT_SET; else if (i == 0) - return K_OFFSET_NO_DATA; + return K_OFFSET_NO_DATA; /* Cast to off_t because it was written as an int. */ - *o = (off_t)i; + *o = (off_t) i; return K_OFFSET_POS_SET; } /* - * Read the flag indicating the state of the data pointer. - * Check if valid and die if not. + * Read the flag indicating the state of the data pointer. Check if + * valid and die if not. * - * This used to be handled by a negative or zero pointer, - * now we use an extra byte specifically for the state. + * This used to be handled by a negative or zero pointer, now we use an + * extra byte specifically for the state. */ offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF; @@ -1438,10 +1439,10 @@ ReadOffset(ArchiveHandle *AH, off_t *o) case K_OFFSET_NO_DATA: case K_OFFSET_POS_SET: - break; + break; default: - die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg); + die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg); } /* @@ -1454,7 +1455,7 @@ ReadOffset(ArchiveHandle *AH, off_t *o) else { if ((*AH->ReadBytePtr) (AH) != 0) - die_horribly(AH, modulename, "file offset in dump file is too large\n"); + die_horribly(AH, modulename, "file offset in dump file is too large\n"); } } @@ -2121,7 +2122,7 @@ _reconnectAsUser(ArchiveHandle *AH, const char *dbname, const char *user) dbname ? fmtId(dbname) : "-"); appendPQExpBuffer(qry, " %s\n\n", fmtId(user)); - + ahprintf(AH, qry->data); destroyPQExpBuffer(qry); @@ -2304,9 +2305,9 @@ ReadHead(ArchiveHandle *AH) write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n"); if (AH->version >= K_VERS_1_7) - AH->offSize = (*AH->ReadBytePtr) (AH); + AH->offSize = (*AH->ReadBytePtr) (AH); else - AH->offSize = AH->intSize; + AH->offSize = AH->intSize; fmt = (*AH->ReadBytePtr) (AH); @@ -2363,10 +2364,11 @@ checkSeek(FILE *fp) if (fseeko(fp, 0, SEEK_CUR) != 0) return false; else if (sizeof(off_t) > sizeof(long)) - /* - * At this point, off_t is too large for long, so we return - * based on whether an off_t version of fseek is available. - */ + + /* + * At this point, off_t is too large for long, so we return based + * on whether an off_t version of fseek is available. + */ #ifdef HAVE_FSEEKO return true; #else diff --git a/src/bin/pg_dump/pg_backup_archiver.h b/src/bin/pg_dump/pg_backup_archiver.h index 078ecb9c98..f893a3ba7f 100644 --- a/src/bin/pg_dump/pg_backup_archiver.h +++ b/src/bin/pg_dump/pg_backup_archiver.h @@ -17,7 +17,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.h,v 1.50 2003/02/01 19:29:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.h,v 1.51 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -74,7 +74,8 @@ typedef z_stream *z_streamp; #define K_VERS_1_4 (( (1 * 256 + 4) * 256 + 0) * 256 + 0) /* Date & name in header */ #define K_VERS_1_5 (( (1 * 256 + 5) * 256 + 0) * 256 + 0) /* Handle dependencies */ #define K_VERS_1_6 (( (1 * 256 + 6) * 256 + 0) * 256 + 0) /* Schema field in TOCs */ -#define K_VERS_1_7 (( (1 * 256 + 7) * 256 + 0) * 256 + 0) /* File Offset size in header */ +#define K_VERS_1_7 (( (1 * 256 + 7) * 256 + 0) * 256 + 0) /* File Offset size in + * header */ #define K_VERS_MAX (( (1 * 256 + 7) * 256 + 255) * 256 + 0) /* No of BLOBs to restore in 1 TX */ @@ -155,7 +156,8 @@ typedef struct _archiveHandle int debugLevel; /* Used for logging (currently only by * --verbose) */ size_t intSize; /* Size of an integer in the archive */ - size_t offSize; /* Size of a file offset in the archive - Added V1.7 */ + size_t offSize; /* Size of a file offset in the archive - + * Added V1.7 */ ArchiveFormat format; /* Archive format */ sqlparseInfo sqlparse; @@ -296,8 +298,8 @@ extern int ReadInt(ArchiveHandle *AH); extern char *ReadStr(ArchiveHandle *AH); extern size_t WriteStr(ArchiveHandle *AH, const char *s); -int ReadOffset(ArchiveHandle*, off_t*); -size_t WriteOffset(ArchiveHandle*, off_t, int); +int ReadOffset(ArchiveHandle *, off_t *); +size_t WriteOffset(ArchiveHandle *, off_t, int); extern void StartRestoreBlobs(ArchiveHandle *AH); extern void StartRestoreBlob(ArchiveHandle *AH, Oid oid); diff --git a/src/bin/pg_dump/pg_backup_custom.c b/src/bin/pg_dump/pg_backup_custom.c index 49a2701a12..802b02811f 100644 --- a/src/bin/pg_dump/pg_backup_custom.c +++ b/src/bin/pg_dump/pg_backup_custom.c @@ -19,7 +19,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_custom.c,v 1.24 2003/07/23 08:47:30 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_custom.c,v 1.25 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -248,7 +248,7 @@ _WriteExtraToc(ArchiveHandle *AH, TocEntry *te) static void _ReadExtraToc(ArchiveHandle *AH, TocEntry *te) { - int junk; + int junk; lclTocEntry *ctx = (lclTocEntry *) te->formatData; if (ctx == NULL) @@ -257,11 +257,11 @@ _ReadExtraToc(ArchiveHandle *AH, TocEntry *te) te->formatData = (void *) ctx; } - ctx->dataState = ReadOffset(AH, &(ctx->dataPos) ); + ctx->dataState = ReadOffset(AH, &(ctx->dataPos)); /* - * Prior to V1.7 (pg7.3), we dumped the data size as an int - * now we don't dump it at all. + * Prior to V1.7 (pg7.3), we dumped the data size as an int now we + * don't dump it at all. */ if (AH->version < K_VERS_1_7) junk = ReadInt(AH); @@ -551,7 +551,7 @@ _PrintData(ArchiveHandle *AH) cnt = fread(in, 1, blkLen, AH->FH); if (cnt != blkLen) die_horribly(AH, modulename, - "could not read data block -- expected %lu, got %lu\n", + "could not read data block -- expected %lu, got %lu\n", (unsigned long) blkLen, (unsigned long) cnt); ctx->filePos += blkLen; @@ -674,7 +674,7 @@ _skipData(ArchiveHandle *AH) cnt = fread(in, 1, blkLen, AH->FH); if (cnt != blkLen) die_horribly(AH, modulename, - "could not read data block -- expected %lu, got %lu\n", + "could not read data block -- expected %lu, got %lu\n", (unsigned long) blkLen, (unsigned long) cnt); ctx->filePos += blkLen; @@ -841,10 +841,10 @@ _getFilePos(ArchiveHandle *AH, lclContext *ctx) if (pos != ctx->filePos) { write_msg(modulename, "WARNING: ftell mismatch with expected position -- ftell used\n"); + /* - * Prior to 1.7 (pg7.3) we relied on the internally maintained pointer. - * Now we rely on off_t always. - * pos = ctx->filePos; + * Prior to 1.7 (pg7.3) we relied on the internally maintained + * pointer. Now we rely on off_t always. pos = ctx->filePos; */ } } diff --git a/src/bin/pg_dump/pg_backup_tar.c b/src/bin/pg_dump/pg_backup_tar.c index 11a5eb8f01..88e1595787 100644 --- a/src/bin/pg_dump/pg_backup_tar.c +++ b/src/bin/pg_dump/pg_backup_tar.c @@ -16,7 +16,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_tar.c,v 1.36 2003/07/23 08:47:30 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_tar.c,v 1.37 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -1150,7 +1150,7 @@ _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER *th) int sum, chk; size_t len; - unsigned long ullen; + unsigned long ullen; off_t hPos; int i; bool gotBlock = false; @@ -1242,15 +1242,18 @@ _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER *th) * Utility routine to print possibly larger than 32 bit integers in a * portable fashion. Filled with zeros. */ -static void print_val(char *s, uint64 val, unsigned int base, size_t len) +static void +print_val(char *s, uint64 val, unsigned int base, size_t len) { - int i; - for (i = len; i > 0; i--) - { - int digit = val % base; - s[i - 1] = '0' + digit; - val = val / base; - } + int i; + + for (i = len; i > 0; i--) + { + int digit = val % base; + + s[i - 1] = '0' + digit; + val = val / base; + } } diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index e58c316866..e631623a32 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -12,7 +12,7 @@ * by PostgreSQL * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.340 2003/07/28 00:09:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.341 2003/08/04 00:43:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -42,7 +42,7 @@ #ifndef HAVE_GETOPT_LONG #include "getopt_long.h" -int optreset; +int optreset; #endif #include "access/attnum.h" @@ -519,12 +519,12 @@ main(int argc, char **argv) PQerrorMessage(g_conn)); PQclear(res); - /* Set the datestyle to ISO to ensure the dump's portability */ - res = PQexec(g_conn, "SET DATESTYLE = ISO"); - if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) - exit_horribly(g_fout, NULL, "could not set datestyle to ISO: %s", - PQerrorMessage(g_conn)); - PQclear(res); + /* Set the datestyle to ISO to ensure the dump's portability */ + res = PQexec(g_conn, "SET DATESTYLE = ISO"); + if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) + exit_horribly(g_fout, NULL, "could not set datestyle to ISO: %s", + PQerrorMessage(g_conn)); + PQclear(res); /* * If supported, set extra_float_digits so that we can dump float data @@ -577,10 +577,10 @@ main(int argc, char **argv) /* Now sort the output nicely */ SortTocByOID(g_fout); - /* - * Procedural languages have to be declared just after - * database and schema creation, before they are used. - */ + /* + * Procedural languages have to be declared just after database and + * schema creation, before they are used. + */ MoveToStart(g_fout, "ACL LANGUAGE"); MoveToStart(g_fout, "PROCEDURAL LANGUAGE"); MoveToStart(g_fout, "FUNC PROCEDURAL LANGUAGE"); @@ -702,8 +702,8 @@ selectDumpableNamespace(NamespaceInfo *nsinfo) { /* * If a specific table is being dumped, do not dump any complete - * namespaces. If a specific namespace is being dumped, dump just - * that namespace. Otherwise, dump all non-system namespaces. + * namespaces. If a specific namespace is being dumped, dump just + * that namespace. Otherwise, dump all non-system namespaces. */ if (selectTableName != NULL) nsinfo->dump = false; @@ -1449,8 +1449,8 @@ getNamespaces(int *numNamespaces) } /* - * If the user attempted to dump a specific namespace, check to - * ensure that the specified namespace actually exists. + * If the user attempted to dump a specific namespace, check to ensure + * that the specified namespace actually exists. */ if (selectSchemaName) { @@ -2269,9 +2269,9 @@ getTables(int *numTables) } /* - * If the user is attempting to dump a specific table, check to - * ensure that the specified table actually exists (and is a table - * or a view, not a sequence). + * If the user is attempting to dump a specific table, check to ensure + * that the specified table actually exists (and is a table or a view, + * not a sequence). */ if (selectTableName) { @@ -2424,8 +2424,8 @@ getTableAttrs(TableInfo *tblinfo, int numTables) { /* need left join here to not fail on dropped columns ... */ appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, " - "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, " - "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname " + "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, " + "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname " "from pg_catalog.pg_attribute a left join pg_catalog.pg_type t " "on a.atttypid = t.oid " "where a.attrelid = '%s'::pg_catalog.oid " @@ -2442,7 +2442,7 @@ getTableAttrs(TableInfo *tblinfo, int numTables) */ appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, -1 as attstattarget, a.attstorage, t.typstorage, " "a.attnotnull, a.atthasdef, false as attisdropped, null as attislocal, " - "format_type(t.oid,a.atttypmod) as atttypname " + "format_type(t.oid,a.atttypmod) as atttypname " "from pg_attribute a left join pg_type t " "on a.atttypid = t.oid " "where a.attrelid = '%s'::oid " @@ -2454,7 +2454,7 @@ getTableAttrs(TableInfo *tblinfo, int numTables) { /* format_type not available before 7.1 */ appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, -1 as attstattarget, attstorage, attstorage as typstorage, " - "attnotnull, atthasdef, false as attisdropped, null as attislocal, " + "attnotnull, atthasdef, false as attisdropped, null as attislocal, " "(select typname from pg_type where oid = atttypid) as atttypname " "from pg_attribute a " "where attrelid = '%s'::oid " @@ -2504,11 +2504,11 @@ getTableAttrs(TableInfo *tblinfo, int numTables) for (j = 0; j < ntups; j++) { - if (j+1 != atoi(PQgetvalue(res, j, i_attnum))) + if (j + 1 != atoi(PQgetvalue(res, j, i_attnum))) { write_msg(NULL, "invalid attribute numbering in table \"%s\"\n", tbinfo->relname); - exit_nicely(); + exit_nicely(); } tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname)); tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname)); @@ -3314,7 +3314,7 @@ dumpOneDomain(Archive *fout, TypeInfo *tinfo) */ if (g_fout->remoteVersion >= 70400) appendPQExpBuffer(chkquery, "SELECT conname, " - "pg_catalog.pg_get_constraintdef(oid) AS consrc " + "pg_catalog.pg_get_constraintdef(oid) AS consrc " "FROM pg_catalog.pg_constraint " "WHERE contypid = '%s'::pg_catalog.oid", tinfo->oid); @@ -3345,7 +3345,7 @@ dumpOneDomain(Archive *fout, TypeInfo *tinfo) appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s", fmtId(conname), consrc); } - + appendPQExpBuffer(q, ";\n"); (*deps)[depIdx++] = NULL; /* End of List */ @@ -3437,7 +3437,7 @@ dumpOneCompositeType(Archive *fout, TypeInfo *tinfo) appendPQExpBuffer(q, ","); } appendPQExpBuffer(q, "\n);\n"); - + /* * DROP must be fully qualified in case same name appears in * pg_catalog @@ -3755,7 +3755,8 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo) char *prosecdef; char *lanname; char *rettypename; - char *funcproclang; /* Boolean : is this function a PLang handler ? */ + char *funcproclang; /* Boolean : is this function a PLang + * handler ? */ if (finfo->dumped) goto done; @@ -3900,7 +3901,7 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo) ArchiveEntry(fout, finfo->oid, funcsig_tag, finfo->pronamespace->nspname, - finfo->usename, strcmp(funcproclang,"t")?"FUNCTION":"FUNC PROCEDURAL LANGUAGE", NULL, + finfo->usename, strcmp(funcproclang, "t") ? "FUNCTION" : "FUNC PROCEDURAL LANGUAGE", NULL, q->data, delqry->data, NULL, NULL, NULL); @@ -4911,7 +4912,7 @@ dumpOneAgg(Archive *fout, AggInfo *agginfo) * Write out grant/revoke information * * 'type' must be TABLE, FUNCTION, LANGUAGE, or SCHEMA. - * 'name' is the formatted name of the object. Must be quoted etc. already. + * 'name' is the formatted name of the object. Must be quoted etc. already. * 'tag' is the tag for the archive entry (typ. unquoted name of object). * 'nspname' is the namespace the object is in (NULL if none). * 'owner' is the owner, NULL if there is no owner (for languages). @@ -4927,12 +4928,15 @@ dumpACL(Archive *fout, const char *type, const char *name, { PQExpBuffer sql; - /* acl_lang is a flag only true if we are dumping language's ACL, - * so we can set 'type' to a value that is suitable to build - * SQL requests as for other types. - */ - bool acl_lang = false; - if(!strcmp(type,"ACL LANGUAGE")){ + /* + * acl_lang is a flag only true if we are dumping language's ACL, so + * we can set 'type' to a value that is suitable to build SQL requests + * as for other types. + */ + bool acl_lang = false; + + if (!strcmp(type, "ACL LANGUAGE")) + { type = "LANGUAGE"; acl_lang = true; } @@ -5275,9 +5279,9 @@ dumpOneTable(Archive *fout, TableInfo *tbinfo, TableInfo *g_tblinfo) resetPQExpBuffer(query); if (g_fout->remoteVersion >= 70400) appendPQExpBuffer(query, "SELECT conname, " - " pg_catalog.pg_get_constraintdef(c1.oid) AS consrc " + " pg_catalog.pg_get_constraintdef(c1.oid) AS consrc " " from pg_catalog.pg_constraint c1 " - " where conrelid = '%s'::pg_catalog.oid " + " where conrelid = '%s'::pg_catalog.oid " " and contype = 'c' " " and not exists " " (select 1 from " @@ -5288,7 +5292,7 @@ dumpOneTable(Archive *fout, TableInfo *tbinfo, TableInfo *g_tblinfo) " or (c2.conname[0] = '$' " " and c1.conname[0] = '$')" " )" - " and pg_catalog.pg_get_constraintdef(c2.oid) " + " and pg_catalog.pg_get_constraintdef(c2.oid) " " = pg_catalog.pg_get_constraintdef(c1.oid) " " and c2.conrelid = i.inhparent) " " order by conname ", @@ -5357,7 +5361,7 @@ dumpOneTable(Archive *fout, TableInfo *tbinfo, TableInfo *g_tblinfo) appendPQExpBuffer(q, ",\n "); appendPQExpBuffer(q, "CONSTRAINT %s ", - fmtId(name)); + fmtId(name)); appendPQExpBuffer(q, "%s", expr); } PQclear(res2); @@ -5402,9 +5406,9 @@ dumpOneTable(Archive *fout, TableInfo *tbinfo, TableInfo *g_tblinfo) for (j = 0; j < tbinfo->numatts; j++) { /* - * Dump per-column statistics information. We only issue an ALTER - * TABLE statement if the attstattarget entry for this column is - * non-negative (i.e. it's not the default value) + * Dump per-column statistics information. We only issue an + * ALTER TABLE statement if the attstattarget entry for this + * column is non-negative (i.e. it's not the default value) */ if (tbinfo->attstattarget[j] >= 0 && !tbinfo->attisdropped[j]) @@ -5418,12 +5422,14 @@ dumpOneTable(Archive *fout, TableInfo *tbinfo, TableInfo *g_tblinfo) } /* - * Dump per-column storage information. The statement is only dumped if - * the storage has been changed from the type's default. + * Dump per-column storage information. The statement is only + * dumped if the storage has been changed from the type's + * default. */ - if(!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j]) + if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j]) { - switch (tbinfo->attstorage[j]) { + switch (tbinfo->attstorage[j]) + { case 'p': storage = "PLAIN"; break; @@ -5439,8 +5445,13 @@ dumpOneTable(Archive *fout, TableInfo *tbinfo, TableInfo *g_tblinfo) default: storage = NULL; } - /* Only dump the statement if it's a storage type we recognize */ - if (storage != NULL) { + + /* + * Only dump the statement if it's a storage type we + * recognize + */ + if (storage != NULL) + { appendPQExpBuffer(q, "ALTER TABLE ONLY %s ", fmtId(tbinfo->relname)); appendPQExpBuffer(q, "ALTER COLUMN %s ", @@ -5605,7 +5616,7 @@ dumpIndexes(Archive *fout, TableInfo *tblinfo, int numTables) const char *indexrelname = PQgetvalue(res, j, i_indexrelname); const char *indexdef = PQgetvalue(res, j, i_indexdef); char contype = *(PQgetvalue(res, j, i_contype)); - bool indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't'); + bool indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't'); resetPQExpBuffer(q); resetPQExpBuffer(delq); @@ -5659,11 +5670,12 @@ dumpIndexes(Archive *fout, TableInfo *tblinfo, int numTables) appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n", fmtId(indexrelname)); /* If the index is clustered, we need to record that. */ - if (indisclustered) { - appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER", - fmtId(tbinfo->relname)); - appendPQExpBuffer(q, " ON %s;\n", - fmtId(indexrelname)); + if (indisclustered) + { + appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER", + fmtId(tbinfo->relname)); + appendPQExpBuffer(q, " ON %s;\n", + fmtId(indexrelname)); } ArchiveEntry(fout, indexreloid, @@ -5684,11 +5696,12 @@ dumpIndexes(Archive *fout, TableInfo *tblinfo, int numTables) appendPQExpBuffer(q, "%s;\n", indexdef); /* If the index is clustered, we need to record that. */ - if (indisclustered) { - appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER", - fmtId(tbinfo->relname)); - appendPQExpBuffer(q, " ON %s;\n", - fmtId(indexrelname)); + if (indisclustered) + { + appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER", + fmtId(tbinfo->relname)); + appendPQExpBuffer(q, " ON %s;\n", + fmtId(indexrelname)); } /* @@ -5889,16 +5902,16 @@ dumpOneSequence(Archive *fout, TableInfo *tbinfo, snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE); appendPQExpBuffer(query, - "SELECT sequence_name, last_value, increment_by, " - "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL " - " WHEN increment_by < 0 AND max_value = -1 THEN NULL " - " ELSE max_value " - "END AS max_value, " - "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL " - " WHEN increment_by < 0 AND min_value = %s THEN NULL " - " ELSE min_value " - "END AS min_value, " - "cache_value, is_cycled, is_called from %s", + "SELECT sequence_name, last_value, increment_by, " + "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL " + " WHEN increment_by < 0 AND max_value = -1 THEN NULL " + " ELSE max_value " + "END AS max_value, " + "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL " + " WHEN increment_by < 0 AND min_value = %s THEN NULL " + " ELSE min_value " + "END AS min_value, " + "cache_value, is_cycled, is_called from %s", bufx, bufm, fmtId(tbinfo->relname)); @@ -5962,7 +5975,7 @@ dumpOneSequence(Archive *fout, TableInfo *tbinfo, resetPQExpBuffer(query); appendPQExpBuffer(query, - "CREATE SEQUENCE %s\n", + "CREATE SEQUENCE %s\n", fmtId(tbinfo->relname)); if (!called) @@ -5981,7 +5994,7 @@ dumpOneSequence(Archive *fout, TableInfo *tbinfo, appendPQExpBuffer(query, " NO MINVALUE\n"); appendPQExpBuffer(query, - " CACHE %s%s;\n", + " CACHE %s%s;\n", cache, (cycled ? "\n CYCLE" : "")); ArchiveEntry(fout, tbinfo->oid, tbinfo->relname, @@ -6072,7 +6085,7 @@ dumpConstraints(Archive *fout, TableInfo *tblinfo, int numTables) resetPQExpBuffer(query); appendPQExpBuffer(query, "SELECT oid, conname, " - "pg_catalog.pg_get_constraintdef(oid) as condef " + "pg_catalog.pg_get_constraintdef(oid) as condef " "FROM pg_catalog.pg_constraint " "WHERE conrelid = '%s'::pg_catalog.oid " "AND contype = 'f'", diff --git a/src/bin/pg_dump/pg_dump.h b/src/bin/pg_dump/pg_dump.h index c30665a7ba..3f0d0156c5 100644 --- a/src/bin/pg_dump/pg_dump.h +++ b/src/bin/pg_dump/pg_dump.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_dump.h,v 1.101 2003/03/20 06:26:30 momjian Exp $ + * $Id: pg_dump.h,v 1.102 2003/08/04 00:43:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -128,8 +128,8 @@ typedef struct _tableInfo char **atttypnames; /* attribute type names */ int *atttypmod; /* type-specific type modifiers */ int *attstattarget; /* attribute statistics targets */ - char *attstorage; /* attribute storage scheme */ - char *typstorage; /* type storage scheme */ + char *attstorage; /* attribute storage scheme */ + char *typstorage; /* type storage scheme */ bool *attisdropped; /* true if attr is dropped; don't dump it */ bool *attislocal; /* true if attr has local definition */ bool *attisserial; /* true if attr is serial or bigserial */ diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c index a7502a7c14..4c59d5d90f 100644 --- a/src/bin/pg_dump/pg_dumpall.c +++ b/src/bin/pg_dump/pg_dumpall.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dumpall.c,v 1.24 2003/07/29 14:17:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dumpall.c,v 1.25 2003/08/04 00:43:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,7 +27,7 @@ #ifndef HAVE_GETOPT_LONG #include "getopt_long.h" -int optreset; +int optreset; #endif #include "dumputils.h" @@ -278,13 +278,13 @@ dumpUsers(PGconn *conn) if (server_version >= 70100) res = executeQuery(conn, - "SELECT usename, usesysid, passwd, usecreatedb, " + "SELECT usename, usesysid, passwd, usecreatedb, " "usesuper, valuntil " "FROM pg_shadow " "WHERE usesysid <> (SELECT datdba FROM pg_database WHERE datname = 'template0')"); else res = executeQuery(conn, - "SELECT usename, usesysid, passwd, usecreatedb, " + "SELECT usename, usesysid, passwd, usecreatedb, " "usesuper, valuntil " "FROM pg_shadow " "WHERE usesysid <> (SELECT datdba FROM pg_database WHERE datname = 'template1')"); @@ -417,13 +417,13 @@ dumpCreateDB(PGconn *conn) "coalesce(usename, (select usename from pg_shadow where usesysid=(select datdba from pg_database where datname='template0'))), " "pg_encoding_to_char(d.encoding), " "datistemplate, datpath, datacl " - "FROM pg_database d LEFT JOIN pg_shadow u ON (datdba = usesysid) " + "FROM pg_database d LEFT JOIN pg_shadow u ON (datdba = usesysid) " "WHERE datallowconn ORDER BY 1"); else if (server_version >= 70100) res = executeQuery(conn, "SELECT datname, " "coalesce(" - "(select usename from pg_shadow where usesysid=datdba), " + "(select usename from pg_shadow where usesysid=datdba), " "(select usename from pg_shadow where usesysid=(select datdba from pg_database where datname='template0'))), " "pg_encoding_to_char(d.encoding), " "datistemplate, datpath, '' as datacl " @@ -437,7 +437,7 @@ dumpCreateDB(PGconn *conn) */ res = executeQuery(conn, "SELECT datname, " - "(select usename from pg_shadow where usesysid=datdba), " + "(select usename from pg_shadow where usesysid=datdba), " "pg_encoding_to_char(d.encoding), " "'f' as datistemplate, datpath, '' as datacl " "FROM pg_database d " diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c index 0a7b0f1d3b..0598c9c451 100644 --- a/src/bin/pg_dump/pg_restore.c +++ b/src/bin/pg_dump/pg_restore.c @@ -34,7 +34,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_restore.c,v 1.48 2003/07/23 08:47:30 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_restore.c,v 1.49 2003/08/04 00:43:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -61,7 +61,7 @@ #ifndef HAVE_GETOPT_LONG #include "getopt_long.h" -int optreset; +int optreset; #endif #ifdef ENABLE_NLS @@ -401,7 +401,7 @@ usage(const char *progname) printf(_(" -x, --no-privileges skip restoration of access privileges (grant/revoke)\n")); printf(_(" -X use-set-session-authorization, --use-set-session-authorization\n" " use SET SESSION AUTHORIZATION commands instead\n" - " of reconnecting, if possible\n")); + " of reconnecting, if possible\n")); printf(_(" -X disable-triggers, --disable-triggers\n" " disable triggers during data-only restore\n")); diff --git a/src/bin/pg_encoding/pg_encoding.c b/src/bin/pg_encoding/pg_encoding.c index ecc0c54524..e94c8d3d87 100644 --- a/src/bin/pg_encoding/pg_encoding.c +++ b/src/bin/pg_encoding/pg_encoding.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_encoding/Attic/pg_encoding.c,v 1.11 2002/10/20 11:33:48 ishii Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_encoding/Attic/pg_encoding.c,v 1.12 2003/08/04 00:43:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -58,7 +58,11 @@ main(int argc, char **argv) { if (be_only && pg_valid_server_encoding(name) < 0) exit(1); - /* pg_encoding_to_char() returns "" if invalid encoding number is given */ + + /* + * pg_encoding_to_char() returns "" if invalid encoding number + * is given + */ else if (strcmp("", name)) printf("%s\n", name); else @@ -77,7 +81,7 @@ main(int argc, char **argv) exit(1); printf("%d\n", enc); } - else + else exit(1); exit(0); diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index bf81bc5d4a..3aa2873865 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -23,7 +23,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/pg_resetxlog/pg_resetxlog.c,v 1.10 2003/07/23 08:47:32 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_resetxlog/pg_resetxlog.c,v 1.11 2003/08/04 00:43:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -172,8 +172,8 @@ main(int argc, char *argv[]) fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } - minXlogSeg = strtoul(endptr+1, &endptr2, 0); - if (endptr2 == endptr+1 || *endptr2 != '\0') + minXlogSeg = strtoul(endptr + 1, &endptr2, 0); + if (endptr2 == endptr + 1 || *endptr2 != '\0') { fprintf(stderr, _("%s: invalid argument for option -l\n"), progname); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c index cc1c20bd11..02f083c5a6 100644 --- a/src/bin/psql/command.c +++ b/src/bin/psql/command.c @@ -3,7 +3,7 @@ * * Copyright 2000-2002 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/command.c,v 1.99 2003/07/28 00:14:42 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/command.c,v 1.100 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "command.h" @@ -1291,8 +1291,8 @@ unescape(const unsigned char *source, size_t len) case '7': case '8': case '9': - c = parse_char((char **)&p); - break; + c = parse_char((char **) &p); + break; default: c = *p; @@ -1496,13 +1496,13 @@ SyncVerbosityVariable(void) switch (SwitchVariable(pset.vars, "VERBOSITY", "default", "terse", "verbose", NULL)) { - case 1: /* default */ + case 1: /* default */ PQsetErrorVerbosity(pset.db, PQERRORS_DEFAULT); break; - case 2: /* terse */ + case 2: /* terse */ PQsetErrorVerbosity(pset.db, PQERRORS_TERSE); break; - case 3: /* verbose */ + case 3: /* verbose */ PQsetErrorVerbosity(pset.db, PQERRORS_VERBOSE); break; default: /* not set or unrecognized value */ @@ -1545,11 +1545,11 @@ editFile(const char *fname) sys = malloc(strlen(editorName) + strlen(fname) + 10 + 1); if (!sys) return false; - sprintf(sys, + sprintf(sys, #ifndef WIN32 - "exec " + "exec " #endif - "%s '%s'", editorName, fname); + "%s '%s'", editorName, fname); result = system(sys); if (result == -1) psql_error("could not start editor \"%s\"\n", editorName); @@ -1673,7 +1673,7 @@ do_edit(const char *filename_arg, PQExpBuffer query_buf) #ifdef USE_READLINE #ifdef HAVE_REPLACE_HISTORY_ENTRY - replace_history_entry(where_history(),query_buf->data,NULL); + replace_history_entry(where_history(), query_buf->data, NULL); #else add_history(query_buf->data); #endif @@ -1913,11 +1913,11 @@ do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet) else if (strcmp(param, "pager") == 0) { if (value && strcasecmp(value, "always") == 0) - popt->topt.pager = 2; + popt->topt.pager = 2; else if (popt->topt.pager == 1) - popt->topt.pager = 0; + popt->topt.pager = 0; else - popt->topt.pager = 1; + popt->topt.pager = 1; if (!quiet) { if (popt->topt.pager == 1) @@ -1978,11 +1978,11 @@ do_shell(const char *command) else exit(EXIT_FAILURE); } - sprintf(sys, + sprintf(sys, #ifndef WIN32 - "exec " + "exec " #endif - "%s", shellName); + "%s", shellName); result = system(sys); free(sys); } diff --git a/src/bin/psql/common.c b/src/bin/psql/common.c index 42299129fb..8bfa3aa139 100644 --- a/src/bin/psql/common.c +++ b/src/bin/psql/common.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/common.c,v 1.67 2003/07/31 04:23:40 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/common.c,v 1.68 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "common.h" @@ -44,15 +44,16 @@ #ifndef WIN32 typedef struct timeval TimevalStruct; + #define GETTIMEOFDAY(T) gettimeofday(T, NULL) #define DIFF_MSEC(T, U) ((((T)->tv_sec - (U)->tv_sec) * 1000000.0 + (T)->tv_usec - (U)->tv_usec) / 1000.0) #else typedef struct _timeb TimevalStruct; + #define GETTIMEOFDAY(T) _ftime(T) #define DIFF_MSEC(T, U) ((((T)->time - (U)->time) * 1000.0 + (T)->millitm - (U)->millitm)) - #endif extern bool prompt_state; @@ -187,7 +188,7 @@ NoticeProcessor(void *arg, const char *message) * so. We use write() to print to stdout because it's better to use simple * facilities in a signal handler. */ -static PGconn *volatile cancelConn = NULL; +static PGconn *volatile cancelConn = NULL; volatile bool cancel_pressed = false; @@ -227,7 +228,7 @@ handle_sigint(SIGNAL_ARGS) * * Returns whether our backend connection is still there. */ -static bool +static bool ConnectionUp() { return PQstatus(pset.db) != CONNECTION_BAD; @@ -241,15 +242,15 @@ ConnectionUp() * see if it can be restored. * * Returns true if either the connection was still there, or it could be - * restored successfully; false otherwise. If, however, there was no + * restored successfully; false otherwise. If, however, there was no * connection and the session is non-interactive, this will exit the program * with a code of EXIT_BADCONN. */ static bool CheckConnection() { - bool OK; - + bool OK; + OK = ConnectionUp(); if (!OK) { @@ -284,21 +285,23 @@ CheckConnection() * * Set cancelConn to point to the current database connection. */ -static void SetCancelConn(void) +static void +SetCancelConn(void) { - cancelConn = pset.db; + cancelConn = pset.db; } /* * ResetCancelConn * - * Set cancelConn to NULL. I don't know what this means exactly, but it saves + * Set cancelConn to NULL. I don't know what this means exactly, but it saves * having to export the variable. */ -void ResetCancelConn(void) +void +ResetCancelConn(void) { - cancelConn = NULL; + cancelConn = NULL; } @@ -314,33 +317,32 @@ void ResetCancelConn(void) static bool AcceptResult(const PGresult *result) { - bool OK = true; + bool OK = true; ResetCancelConn(); if (!result) - { - OK = false; - } - else switch (PQresultStatus(result)) - { - case PGRES_COMMAND_OK: - case PGRES_TUPLES_OK: - case PGRES_COPY_IN: - /* Fine, do nothing */ - break; + OK = false; + else + switch (PQresultStatus(result)) + { + case PGRES_COMMAND_OK: + case PGRES_TUPLES_OK: + case PGRES_COPY_IN: + /* Fine, do nothing */ + break; - case PGRES_COPY_OUT: - /* keep cancel connection for copy out state */ - SetCancelConn(); - break; + case PGRES_COPY_OUT: + /* keep cancel connection for copy out state */ + SetCancelConn(); + break; - default: - OK = false; - break; - } + default: + OK = false; + break; + } - if (!OK) + if (!OK) { CheckConnection(); psql_error("%s", PQerrorMessage(pset.db)); @@ -365,7 +367,7 @@ PGresult * PSQLexec(const char *query, bool start_xact) { PGresult *res; - int echo_hidden; + int echo_hidden; if (!pset.db) { @@ -438,41 +440,38 @@ PrintNotifications(void) * * Returns true if successful, false otherwise. */ -static bool +static bool PrintQueryTuples(const PGresult *results) { - /* write output to \g argument, if any */ - if (pset.gfname) - { - FILE *queryFout_copy = pset.queryFout; - bool queryFoutPipe_copy = pset.queryFoutPipe; + /* write output to \g argument, if any */ + if (pset.gfname) + { + FILE *queryFout_copy = pset.queryFout; + bool queryFoutPipe_copy = pset.queryFoutPipe; - pset.queryFout = stdout; /* so it doesn't get - * closed */ + pset.queryFout = stdout; /* so it doesn't get closed */ - /* open file/pipe */ - if (!setQFout(pset.gfname)) - { - pset.queryFout = queryFout_copy; - pset.queryFoutPipe = queryFoutPipe_copy; + /* open file/pipe */ + if (!setQFout(pset.gfname)) + { + pset.queryFout = queryFout_copy; + pset.queryFoutPipe = queryFoutPipe_copy; return false; - } + } - printQuery(results, &pset.popt, pset.queryFout); + printQuery(results, &pset.popt, pset.queryFout); - /* close file/pipe, restore old setting */ - setQFout(NULL); + /* close file/pipe, restore old setting */ + setQFout(NULL); - pset.queryFout = queryFout_copy; - pset.queryFoutPipe = queryFoutPipe_copy; + pset.queryFout = queryFout_copy; + pset.queryFoutPipe = queryFoutPipe_copy; - free(pset.gfname); - pset.gfname = NULL; - } - else - { - printQuery(results, &pset.popt, pset.queryFout); - } + free(pset.gfname); + pset.gfname = NULL; + } + else + printQuery(results, &pset.popt, pset.queryFout); return true; } @@ -487,65 +486,64 @@ PrintQueryTuples(const PGresult *results) * Returns true if the query executed successfully, false otherwise. */ static bool -PrintQueryResults(PGresult *results, - const TimevalStruct *before, - const TimevalStruct *after) +PrintQueryResults(PGresult *results, + const TimevalStruct * before, + const TimevalStruct * after) { - bool success = false; + bool success = false; - if (!results) - return false; + if (!results) + return false; switch (PQresultStatus(results)) { case PGRES_TUPLES_OK: success = PrintQueryTuples(results); - break; - case PGRES_EMPTY_QUERY: + break; + case PGRES_EMPTY_QUERY: + success = true; + break; + case PGRES_COMMAND_OK: + { + char buf[10]; + success = true; - break; - case PGRES_COMMAND_OK: + sprintf(buf, "%u", (unsigned int) PQoidValue(results)); + if (!QUIET()) { - char buf[10]; - - success = true; - sprintf(buf, "%u", (unsigned int) PQoidValue(results)); - if (!QUIET()) - { - if (pset.popt.topt.format == PRINT_HTML) - { - fputs("

", pset.queryFout); - html_escaped_print(PQcmdStatus(results), pset.queryFout); - fputs("

\n", pset.queryFout); - } - else - { - fprintf(pset.queryFout, "%s\n", PQcmdStatus(results)); - } - } - SetVariable(pset.vars, "LASTOID", buf); - break; + if (pset.popt.topt.format == PRINT_HTML) + { + fputs("

", pset.queryFout); + html_escaped_print(PQcmdStatus(results), pset.queryFout); + fputs("

\n", pset.queryFout); + } + else + fprintf(pset.queryFout, "%s\n", PQcmdStatus(results)); } - case PGRES_COPY_OUT: - success = handleCopyOut(pset.db, pset.queryFout); + SetVariable(pset.vars, "LASTOID", buf); break; + } + case PGRES_COPY_OUT: + success = handleCopyOut(pset.db, pset.queryFout); + break; - case PGRES_COPY_IN: - if (pset.cur_cmd_interactive && !QUIET()) - puts(gettext("Enter data to be copied followed by a newline.\n" - "End with a backslash and a period on a line by itself.")); + case PGRES_COPY_IN: + if (pset.cur_cmd_interactive && !QUIET()) + puts(gettext("Enter data to be copied followed by a newline.\n" + "End with a backslash and a period on a line by itself.")); - success = handleCopyIn(pset.db, pset.cur_cmd_source, - pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL); - break; + success = handleCopyIn(pset.db, pset.cur_cmd_source, + pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL); + break; default: - break; - } + break; + } - fflush(pset.queryFout); + fflush(pset.queryFout); - if (!CheckConnection()) return false; + if (!CheckConnection()) + return false; /* Possible microtiming output */ if (pset.timing && success) @@ -572,8 +570,9 @@ bool SendQuery(const char *query) { PGresult *results; - TimevalStruct before, after; - bool OK; + TimevalStruct before, + after; + bool OK; if (!pset.db) { @@ -599,7 +598,7 @@ SendQuery(const char *query) puts(query); fflush(stdout); } - + SetCancelConn(); if (PQtransactionStatus(pset.db) == PQTRANS_IDLE && @@ -636,7 +635,7 @@ SendQuery(const char *query) static bool is_transact_command(const char *query) { - int wordlen; + int wordlen; /* * First we must advance over any whitespace and comments. @@ -693,13 +692,14 @@ is_transact_command(const char *query) } -char parse_char(char **buf) +char +parse_char(char **buf) { - long l; + long l; - l = strtol(*buf, buf, 0); - --*buf; - return (char)l; + l = strtol(*buf, buf, 0); + --*buf; + return (char) l; } diff --git a/src/bin/psql/copy.c b/src/bin/psql/copy.c index d45fecc539..6694624cad 100644 --- a/src/bin/psql/copy.c +++ b/src/bin/psql/copy.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/copy.c,v 1.31 2003/07/23 08:47:39 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/copy.c,v 1.32 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "copy.h" @@ -28,8 +28,8 @@ #ifdef WIN32 #define strcasecmp(x,y) stricmp(x,y) -#define __S_ISTYPE(mode, mask) (((mode) & S_IFMT) == (mask)) -#define S_ISDIR(mode) __S_ISTYPE((mode), S_IFDIR) +#define __S_ISTYPE(mode, mask) (((mode) & S_IFMT) == (mask)) +#define S_ISDIR(mode) __S_ISTYPE((mode), S_IFDIR) #endif /* @@ -142,8 +142,9 @@ parse_slash_copy(const char *args) goto error; /* - * strtokx() will not have returned a multi-character token starting with - * '.', so we don't need strcmp() here. Likewise for '(', etc, below. + * strtokx() will not have returned a multi-character token starting + * with '.', so we don't need strcmp() here. Likewise for '(', etc, + * below. */ if (token[0] == '.') { @@ -188,8 +189,7 @@ parse_slash_copy(const char *args) } /* - * Allows old COPY syntax for backward compatibility - * 2002-06-19 + * Allows old COPY syntax for backward compatibility 2002-06-19 */ if (strcasecmp(token, "with") == 0) { @@ -227,8 +227,7 @@ parse_slash_copy(const char *args) 0, false, pset.encoding); /* - * Allows old COPY syntax for backward compatibility - * 2002-06-19 + * Allows old COPY syntax for backward compatibility 2002-06-19 */ if (token && strcasecmp(token, "using") == 0) { diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index 70264a4487..4679402282 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -3,7 +3,7 @@ * * Copyright 2000-2002 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/describe.c,v 1.81 2003/07/27 03:32:26 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/describe.c,v 1.82 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "describe.h" @@ -139,10 +139,10 @@ describeFunctions(const char *pattern, bool verbose) initPQExpBuffer(&buf); printfPQExpBuffer(&buf, - "SELECT CASE WHEN p.proretset THEN 'setof ' ELSE '' END ||\n" - " pg_catalog.format_type(p.prorettype, NULL) as \"%s\",\n" - " n.nspname as \"%s\",\n" - " p.proname as \"%s\",\n" + "SELECT CASE WHEN p.proretset THEN 'setof ' ELSE '' END ||\n" + " pg_catalog.format_type(p.prorettype, NULL) as \"%s\",\n" + " n.nspname as \"%s\",\n" + " p.proname as \"%s\",\n" " pg_catalog.oidvectortypes(p.proargtypes) as \"%s\"", _("Result data type"), _("Schema"), _("Name"), _("Argument data types")); @@ -723,7 +723,7 @@ describeOneTableDetails(const char *schemaname, /* Get column info (index requires additional checks) */ printfPQExpBuffer(&buf, "SELECT a.attname,"); appendPQExpBuffer(&buf, "\n pg_catalog.format_type(a.atttypid, a.atttypmod)," - "\n (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d" + "\n (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d" "\n WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)," "\n a.attnotnull, a.attnum"); if (verbose) @@ -765,7 +765,7 @@ describeOneTableDetails(const char *schemaname, { /* Name */ #ifdef WIN32 - cells[i * cols + 0] = mbvalidate(PQgetvalue(res, i, 0)); + cells[i * cols + 0] = mbvalidate(PQgetvalue(res, i, 0)); #else cells[i * cols + 0] = PQgetvalue(res, i, 0); /* don't free this * afterwards */ @@ -962,7 +962,7 @@ describeOneTableDetails(const char *schemaname, foreignkey_count = 0, rule_count = 0, trigger_count = 0, - inherits_count = 0; + inherits_count = 0; int count_footers = 0; /* count indexes */ @@ -1023,7 +1023,7 @@ describeOneTableDetails(const char *schemaname, if (tableinfo.triggers) { printfPQExpBuffer(&buf, - "SELECT t.tgname, pg_catalog.pg_get_triggerdef(t.oid)\n" + "SELECT t.tgname, pg_catalog.pg_get_triggerdef(t.oid)\n" "FROM pg_catalog.pg_trigger t\n" "WHERE t.tgrelid = '%s' " "and (not tgisconstraint " @@ -1079,7 +1079,8 @@ describeOneTableDetails(const char *schemaname, * sizeof(*footers)); /* print indexes */ - if (index_count > 0) { + if (index_count > 0) + { printfPQExpBuffer(&buf, _("Indexes:")); footers[count_footers++] = xstrdup(buf.data); for (i = 0; i < index_count; i++) @@ -1093,11 +1094,11 @@ describeOneTableDetails(const char *schemaname, /* Label as primary key or unique (but not both) */ appendPQExpBuffer(&buf, - strcmp(PQgetvalue(result1, i, 1), "t") == 0 + strcmp(PQgetvalue(result1, i, 1), "t") == 0 ? _(" primary key,") : - (strcmp(PQgetvalue(result1, i, 2), "t") == 0 - ? _(" unique,") - : "")); + (strcmp(PQgetvalue(result1, i, 2), "t") == 0 + ? _(" unique,") + : "")); /* Everything after "USING" is echoed verbatim */ indexdef = PQgetvalue(result1, i, 3); @@ -1112,7 +1113,8 @@ describeOneTableDetails(const char *schemaname, } /* print check constraints */ - if (check_count > 0) { + if (check_count > 0) + { printfPQExpBuffer(&buf, _("Check constraints:")); footers[count_footers++] = xstrdup(buf.data); for (i = 0; i < check_count; i++) @@ -1126,7 +1128,8 @@ describeOneTableDetails(const char *schemaname, } /* print foreign key constraints */ - if (foreignkey_count > 0) { + if (foreignkey_count > 0) + { printfPQExpBuffer(&buf, _("Foreign-key constraints:")); footers[count_footers++] = xstrdup(buf.data); for (i = 0; i < foreignkey_count; i++) @@ -1140,7 +1143,8 @@ describeOneTableDetails(const char *schemaname, } /* print rules */ - if (rule_count > 0) { + if (rule_count > 0) + { printfPQExpBuffer(&buf, _("Rules:")); footers[count_footers++] = xstrdup(buf.data); for (i = 0; i < rule_count; i++) @@ -1158,7 +1162,8 @@ describeOneTableDetails(const char *schemaname, } /* print triggers */ - if (trigger_count > 0) { + if (trigger_count > 0) + { printfPQExpBuffer(&buf, _("Triggers:")); footers[count_footers++] = xstrdup(buf.data); for (i = 0; i < trigger_count; i++) @@ -1368,9 +1373,9 @@ listTables(const char *tabtypes, const char *pattern, bool verbose) /* * If showSystem is specified, show only system objects (those in - * pg_catalog). Otherwise, suppress system objects, including - * those in pg_catalog and pg_toast. (We don't want to hide temp - * tables though.) + * pg_catalog). Otherwise, suppress system objects, including those + * in pg_catalog and pg_toast. (We don't want to hide temp tables + * though.) */ if (showSystem) appendPQExpBuffer(&buf, " AND n.nspname = 'pg_catalog'\n"); @@ -1476,11 +1481,11 @@ listConversions(const char *pattern) printfPQExpBuffer(&buf, "SELECT n.nspname AS \"%s\",\n" " c.conname AS \"%s\",\n" - " pg_catalog.pg_encoding_to_char(c.conforencoding) AS \"%s\",\n" - " pg_catalog.pg_encoding_to_char(c.contoencoding) AS \"%s\",\n" + " pg_catalog.pg_encoding_to_char(c.conforencoding) AS \"%s\",\n" + " pg_catalog.pg_encoding_to_char(c.contoencoding) AS \"%s\",\n" " CASE WHEN c.condefault THEN '%s'\n" " ELSE '%s' END AS \"%s\"\n" - "FROM pg_catalog.pg_conversion c, pg_catalog.pg_namespace n\n" + "FROM pg_catalog.pg_conversion c, pg_catalog.pg_namespace n\n" "WHERE n.oid = c.connamespace\n", _("Schema"), _("Name"), @@ -1525,8 +1530,8 @@ listCasts(const char *pattern) initPQExpBuffer(&buf); /* NEED LEFT JOIN FOR BINARY CASTS */ printfPQExpBuffer(&buf, - "SELECT pg_catalog.format_type(castsource, NULL) AS \"%s\",\n" - " pg_catalog.format_type(casttarget, NULL) AS \"%s\",\n" + "SELECT pg_catalog.format_type(castsource, NULL) AS \"%s\",\n" + " pg_catalog.format_type(casttarget, NULL) AS \"%s\",\n" " CASE WHEN castfunc = 0 THEN '%s'\n" " ELSE p.proname\n" " END as \"%s\",\n" @@ -1534,7 +1539,7 @@ listCasts(const char *pattern) " WHEN c.castcontext = 'a' THEN '%s'\n" " ELSE '%s'\n" " END as \"%s\"\n" - "FROM pg_catalog.pg_cast c LEFT JOIN pg_catalog.pg_proc p\n" + "FROM pg_catalog.pg_cast c LEFT JOIN pg_catalog.pg_proc p\n" " ON c.castfunc = p.oid\n" "ORDER BY 1, 2", _("Source type"), @@ -1576,7 +1581,7 @@ listSchemas(const char *pattern) printfPQExpBuffer(&buf, "SELECT n.nspname AS \"%s\",\n" " u.usename AS \"%s\"\n" - "FROM pg_catalog.pg_namespace n LEFT JOIN pg_catalog.pg_user u\n" + "FROM pg_catalog.pg_namespace n LEFT JOIN pg_catalog.pg_user u\n" " ON n.nspowner=u.usesysid\n", _("Name"), _("Owner")); diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c index a884beb2e6..4b59a3af5f 100644 --- a/src/bin/psql/help.c +++ b/src/bin/psql/help.c @@ -3,7 +3,7 @@ * * Copyright 2000-2003 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/help.c,v 1.75 2003/07/25 21:48:45 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/help.c,v 1.76 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "common.h" @@ -173,7 +173,7 @@ slashUsage(unsigned short int pager) */ fprintf(output, _("General\n")); fprintf(output, _(" \\c[onnect] [DBNAME|- [USER]]\n" - " connect to new database (currently \"%s\")\n"), + " connect to new database (currently \"%s\")\n"), PQdb(pset.db)); fprintf(output, _(" \\cd [DIR] change the current working directory\n")); fprintf(output, _(" \\copyright show PostgreSQL usage and distribution terms\n")); @@ -203,7 +203,7 @@ slashUsage(unsigned short int pager) fprintf(output, _(" \\i FILE execute commands from file\n")); fprintf(output, _(" \\o [FILE] send all query results to file or |pipe\n")); fprintf(output, _(" \\qecho [STRING]\n" - " write string to query output stream (see \\o)\n")); + " write string to query output stream (see \\o)\n")); fprintf(output, "\n"); fprintf(output, _("Informational\n")); @@ -235,7 +235,7 @@ slashUsage(unsigned short int pager) fprintf(output, _(" \\pset NAME [VALUE]\n" " set table output option\n" " (NAME := {format|border|expanded|fieldsep|null|recordsep|\n" - " tuples_only|title|tableattr|pager})\n")); + " tuples_only|title|tableattr|pager})\n")); fprintf(output, _(" \\t show only rows (currently %s)\n"), ON(pset.popt.topt.tuples_only)); fprintf(output, _(" \\T [STRING] set HTML tag attributes, or unset if none\n")); @@ -274,7 +274,7 @@ helpSQL(const char *topic, unsigned short int pager) { int i; int items_per_column = (QL_HELP_COUNT + 2) / 3; - FILE *output; + FILE *output; output = PageOutput(items_per_column + 1, pager); @@ -283,8 +283,8 @@ helpSQL(const char *topic, unsigned short int pager) for (i = 0; i < items_per_column; i++) { fprintf(output, " %-26s%-26s", - VALUE_OR_NULL(QL_HELP[i].cmd), - VALUE_OR_NULL(QL_HELP[i + items_per_column].cmd)); + VALUE_OR_NULL(QL_HELP[i].cmd), + VALUE_OR_NULL(QL_HELP[i + items_per_column].cmd)); if (i + 2 * items_per_column < QL_HELP_COUNT) fprintf(output, "%-26s", VALUE_OR_NULL(QL_HELP[i + 2 * items_per_column].cmd)); diff --git a/src/bin/psql/input.c b/src/bin/psql/input.c index b220ed8941..9ebc1dc7f8 100644 --- a/src/bin/psql/input.c +++ b/src/bin/psql/input.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/input.c,v 1.26 2003/07/27 03:32:26 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/input.c,v 1.27 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "input.h" @@ -27,12 +27,11 @@ static bool useHistory; enum histcontrol { - hctl_none = 0, - hctl_ignorespace = 1, - hctl_ignoredups = 2, - hctl_ignoreboth = hctl_ignorespace | hctl_ignoredups + hctl_none = 0, + hctl_ignorespace = 1, + hctl_ignoredups = 2, + hctl_ignoreboth = hctl_ignorespace | hctl_ignoredups }; - #endif #ifdef HAVE_ATEXIT @@ -43,16 +42,17 @@ static void finishInput(void); static void finishInput(int, void *); #endif -#define PSQLHISTORY ".psql_history" +#define PSQLHISTORY ".psql_history" #ifdef WIN32 - /* - * translate DOS console character set into ANSI, needed e.g. for - * German umlauts - */ - if (GetVariableBool(pset.vars, "WIN32_CONSOLE")) - OemToChar(s, s); + + /* + * translate DOS console character set into ANSI, needed e.g. for German + * umlauts + */ +if (GetVariableBool(pset.vars, "WIN32_CONSOLE")) + OemToChar(s, s); #endif #ifdef USE_READLINE @@ -64,11 +64,16 @@ GetHistControlConfig(void) var = GetVariable(pset.vars, "HISTCONTROL"); - if (!var) HC = hctl_none; - else if (strcmp(var, "ignorespace") == 0) HC = hctl_ignorespace; - else if (strcmp(var, "ignoredups") == 0) HC = hctl_ignoredups; - else if (strcmp(var, "ignoreboth") == 0) HC = hctl_ignoreboth; - else HC = hctl_none; + if (!var) + HC = hctl_none; + else if (strcmp(var, "ignorespace") == 0) + HC = hctl_ignorespace; + else if (strcmp(var, "ignoredups") == 0) + HC = hctl_ignoredups; + else if (strcmp(var, "ignoreboth") == 0) + HC = hctl_ignoreboth; + else + HC = hctl_none; return HC; } @@ -111,9 +116,9 @@ gets_interactive(const char *prompt) HC = GetHistControlConfig(); if (((HC & hctl_ignorespace) && s[0] == ' ') || - ((HC & hctl_ignoredups) && prev_hist && strcmp(s, prev_hist) == 0)) - { - /* Ignore this line as far as history is concerned */ + ((HC & hctl_ignoredups) && prev_hist && strcmp(s, prev_hist) == 0)) + { + /* Ignore this line as far as history is concerned */ } else { @@ -216,7 +221,7 @@ saveHistory(char *fname) if (useHistory && fname) { if (write_history(fname) == 0) - return true; + return true; psql_error("could not save history to file \"%s\": %s\n", fname, strerror(errno)); } @@ -244,11 +249,12 @@ finishInput(int exitstatus, void *arg) if (home) { psql_history = (char *) malloc(strlen(home) + 1 + - strlen(PSQLHISTORY) + 1); + strlen(PSQLHISTORY) + 1); if (psql_history) { - int hist_size; - hist_size = GetVariableNum(pset.vars,"HISTSIZE",-1,-1,true); + int hist_size; + + hist_size = GetVariableNum(pset.vars, "HISTSIZE", -1, -1, true); if (hist_size >= 0) stifle_history(hist_size); diff --git a/src/bin/psql/large_obj.c b/src/bin/psql/large_obj.c index a565d20478..720912b5b3 100644 --- a/src/bin/psql/large_obj.c +++ b/src/bin/psql/large_obj.c @@ -3,7 +3,7 @@ * * Copyright 2000-2002 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/large_obj.c,v 1.27 2003/06/28 00:12:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/large_obj.c,v 1.28 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "large_obj.h" @@ -20,7 +20,7 @@ /* - * Prepare to do a large-object operation. We *must* be inside a transaction + * Prepare to do a large-object operation. We *must* be inside a transaction * block for all these operations, so start one if needed. * * Returns TRUE if okay, FALSE if failed. *own_transaction is set to indicate @@ -241,7 +241,7 @@ do_lo_unlink(const char *loid_arg) if (is_superuser()) { snprintf(buf, sizeof(buf), - "DELETE FROM pg_catalog.pg_description WHERE objoid = '%u' " + "DELETE FROM pg_catalog.pg_description WHERE objoid = '%u' " "AND classoid = 'pg_catalog.pg_largeobject'::regclass", loid); if (!(res = PSQLexec(buf, false))) diff --git a/src/bin/psql/mainloop.c b/src/bin/psql/mainloop.c index 32c03cf24f..d41627c132 100644 --- a/src/bin/psql/mainloop.c +++ b/src/bin/psql/mainloop.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/mainloop.c,v 1.55 2003/03/21 03:28:29 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/mainloop.c,v 1.56 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "mainloop.h" @@ -43,8 +43,8 @@ MainLoop(FILE *source) volatile backslashResult slashCmdStatus = CMD_UNKNOWN; bool success; - volatile char in_quote = 0; /* == 0 for no in_quote */ - volatile int in_xcomment = 0; /* in extended comment */ + volatile char in_quote = 0; /* == 0 for no in_quote */ + volatile int in_xcomment = 0; /* in extended comment */ volatile int paren_level = 0; unsigned int query_start; volatile int count_eof = 0; @@ -152,33 +152,34 @@ MainLoop(FILE *source) paren_level = 0; slashCmdStatus = CMD_UNKNOWN; } - /* - * otherwise, set interactive prompt if necessary and get - * another line - */ + + /* + * otherwise, set interactive prompt if necessary and get another + * line + */ else if (pset.cur_cmd_interactive) - { - int prompt_status; + { + int prompt_status; fflush(stdout); - if (in_quote && in_quote == '\'') - prompt_status = PROMPT_SINGLEQUOTE; - else if (in_quote && in_quote == '"') - prompt_status = PROMPT_DOUBLEQUOTE; - else if (in_xcomment) - prompt_status = PROMPT_COMMENT; - else if (paren_level) - prompt_status = PROMPT_PAREN; - else if (query_buf->len > 0) - prompt_status = PROMPT_CONTINUE; - else - prompt_status = PROMPT_READY; - - line = gets_interactive(get_prompt(prompt_status)); - } + if (in_quote && in_quote == '\'') + prompt_status = PROMPT_SINGLEQUOTE; + else if (in_quote && in_quote == '"') + prompt_status = PROMPT_DOUBLEQUOTE; + else if (in_xcomment) + prompt_status = PROMPT_COMMENT; + else if (paren_level) + prompt_status = PROMPT_PAREN; + else if (query_buf->len > 0) + prompt_status = PROMPT_CONTINUE; else - line = gets_fromFile(source); + prompt_status = PROMPT_READY; + + line = gets_interactive(get_prompt(prompt_status)); + } + else + line = gets_fromFile(source); /* Setting this will not have effect until next line. */ @@ -199,7 +200,7 @@ MainLoop(FILE *source) /* This tries to mimic bash's IGNOREEOF feature. */ count_eof++; - if (count_eof < GetVariableNum(pset.vars,"IGNOREEOF",0,10,false)) + if (count_eof < GetVariableNum(pset.vars, "IGNOREEOF", 0, 10, false)) { if (!QUIET()) printf(gettext("Use \"\\q\" to leave %s.\n"), pset.progname); @@ -208,10 +209,10 @@ MainLoop(FILE *source) puts(QUIET() ? "" : "\\q"); } - break; + break; } - count_eof = 0; + count_eof = 0; pset.lineno++; @@ -274,7 +275,7 @@ MainLoop(FILE *source) else if (line[i] == '/' && line[i + thislen] == '*') { in_xcomment++; - if (in_xcomment == 1) + if (in_xcomment == 1) ADVANCE_1; } @@ -283,7 +284,7 @@ MainLoop(FILE *source) { if (line[i] == '*' && line[i + thislen] == '/' && !--in_xcomment) - ADVANCE_1; + ADVANCE_1; } /* start of quote? */ @@ -489,10 +490,10 @@ MainLoop(FILE *source) if (!pset.cur_cmd_interactive) { if (!success && die_on_error) - successResult = EXIT_USER; - /* Have we lost the db connection? */ + successResult = EXIT_USER; + /* Have we lost the db connection? */ else if (!pset.db) - successResult = EXIT_BADCONN; + successResult = EXIT_BADCONN; } } /* while !endoffile/session */ diff --git a/src/bin/psql/mbprint.c b/src/bin/psql/mbprint.c index 437d7271c0..f4dacd2a01 100644 --- a/src/bin/psql/mbprint.c +++ b/src/bin/psql/mbprint.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/mbprint.c,v 1.7 2003/07/27 03:32:26 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/mbprint.c,v 1.8 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" @@ -335,13 +335,15 @@ mbvalidate(unsigned char *pwcs, int encoding) else { #ifdef WIN32 + /* - * translate characters to DOS console encoding, e.g. needed - * for German umlauts + * translate characters to DOS console encoding, e.g. needed for + * German umlauts */ if (GetVariableBool(pset.vars, "WIN32_CONSOLE")) CharToOem(pwcs, pwcs); #endif + /* * other encodings needing validation should add their own * routines here diff --git a/src/bin/psql/print.c b/src/bin/psql/print.c index 2f71aad9bc..b2bc9afb6d 100644 --- a/src/bin/psql/print.c +++ b/src/bin/psql/print.c @@ -3,7 +3,7 @@ * * Copyright 2000-2003 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/print.c,v 1.40 2003/07/25 21:48:45 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/print.c,v 1.41 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "common.h" @@ -306,7 +306,7 @@ print_aligned_text(const char *title, const char *const * headers, for (i = 0; i < col_count; i++) { - unsigned int nbspace; + unsigned int nbspace; nbspace = widths[i] - head_w[i]; @@ -396,7 +396,7 @@ print_aligned_text(const char *title, const char *const * headers, static void print_aligned_vertical(const char *title, const char *const * headers, - const char *const * cells, const char *const * footers, + const char *const * cells, const char *const * footers, bool opt_barebones, unsigned short int opt_border, int encoding, FILE *fout) { @@ -660,7 +660,8 @@ const char *opt_align, bool opt_barebones, unsigned short int opt_border, fputs(" \n", fout); fprintf(fout, "
", opt_align[(i) % col_count] == 'r' ? "right" : "left"); - if ((*ptr)[strspn(*ptr, " \t")] == '\0') /* is string only whitespace? */ + if ((*ptr)[strspn(*ptr, " \t")] == '\0') /* is string only + * whitespace? */ fputs("  ", fout); else html_escaped_print(*ptr, fout); @@ -734,7 +735,8 @@ const char *opt_align, bool opt_barebones, unsigned short int opt_border, fputs("\n", fout); fprintf(fout, " ", opt_align[i % col_count] == 'r' ? "right" : "left"); - if ((*ptr)[strspn(*ptr, " \t")] == '\0') /* is string only whitespace? */ + if ((*ptr)[strspn(*ptr, " \t")] == '\0') /* is string only + * whitespace? */ fputs("  ", fout); else html_escaped_print(*ptr, fout); @@ -1036,7 +1038,7 @@ printTable(const char *title, { const char *default_footer[] = {NULL}; unsigned short int border = opt->border; - FILE *output; + FILE *output; if (opt->format == PRINT_NOTHING) return; @@ -1049,9 +1051,9 @@ printTable(const char *title, if (fout == stdout) { - int col_count = 0, - row_count = 0, - lines; + int col_count = 0, + row_count = 0, + lines; const char *const * ptr; /* rough estimate of columns and rows */ diff --git a/src/bin/psql/print.h b/src/bin/psql/print.h index a70e7858bb..7d6377fd36 100644 --- a/src/bin/psql/print.h +++ b/src/bin/psql/print.h @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/print.h,v 1.17 2003/06/12 07:52:51 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/print.h,v 1.18 2003/08/04 00:43:29 momjian Exp $ */ #ifndef PRINT_H #define PRINT_H @@ -32,8 +32,7 @@ typedef struct _printTableOpt bool expanded; /* expanded/vertical output (if supported * by output format) */ unsigned short int pager; /* use pager for output (if to stdout and - * stdout is a tty) - * 0=off 1=on 2=always */ + * stdout is a tty) 0=off 1=on 2=always */ bool tuples_only; /* don't output headers, row counts, etc. */ unsigned short int border; /* Print a border around the table. * 0=none, 1=dividing lines, 2=full */ diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c index 0df16d4b0c..a202806926 100644 --- a/src/bin/psql/prompt.c +++ b/src/bin/psql/prompt.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/prompt.c,v 1.26 2003/06/28 00:12:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/prompt.c,v 1.27 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "prompt.h" @@ -86,14 +86,14 @@ get_prompt(promptStatus_t status) case PROMPT_PAREN: prompt_name = "PROMPT2"; break; - + case PROMPT_COPY: prompt_name = "PROMPT3"; break; } if (prompt_name) - prompt_string = GetVariable(pset.vars, prompt_name); + prompt_string = GetVariable(pset.vars, prompt_name); destination[0] = '\0'; @@ -112,16 +112,17 @@ get_prompt(promptStatus_t status) strncpy(buf, PQdb(pset.db), MAX_PROMPT_SIZE); break; case '~': - if (pset.db) - { + if (pset.db) + { const char *var; - if (strcmp(PQdb(pset.db), PQuser(pset.db)) == 0 || - ((var = getenv("PGDATABASE")) && strcmp(var, PQdb(pset.db)) == 0)) - strcpy(buf, "~"); - else - strncpy(buf, PQdb(pset.db), MAX_PROMPT_SIZE); - } - break; + + if (strcmp(PQdb(pset.db), PQuser(pset.db)) == 0 || + ((var = getenv("PGDATABASE")) && strcmp(var, PQdb(pset.db)) == 0)) + strcpy(buf, "~"); + else + strncpy(buf, PQdb(pset.db), MAX_PROMPT_SIZE); + } + break; /* DB server hostname (long/short) */ case 'M': @@ -172,7 +173,7 @@ get_prompt(promptStatus_t status) case '7': case '8': case '9': - *buf = parse_char((char **)&p); + *buf = parse_char((char **) &p); break; case 'R': @@ -210,22 +211,23 @@ get_prompt(promptStatus_t status) case 'T': if (!pset.db) buf[0] = '?'; - else switch (PQtransactionStatus(pset.db)) - { - case PQTRANS_IDLE: - buf[0] = '\0'; - break; - case PQTRANS_ACTIVE: - case PQTRANS_INTRANS: - buf[0] = '*'; - break; - case PQTRANS_INERROR: - buf[0] = '!'; - break; - default: - buf[0] = '?'; - break; - } + else + switch (PQtransactionStatus(pset.db)) + { + case PQTRANS_IDLE: + buf[0] = '\0'; + break; + case PQTRANS_ACTIVE: + case PQTRANS_INTRANS: + buf[0] = '*'; + break; + case PQTRANS_INERROR: + buf[0] = '!'; + break; + default: + buf[0] = '?'; + break; + } break; case '?': diff --git a/src/bin/psql/sprompt.c b/src/bin/psql/sprompt.c index 0a9eed182b..e08cb94c88 100644 --- a/src/bin/psql/sprompt.c +++ b/src/bin/psql/sprompt.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/Attic/sprompt.c,v 1.5 2003/07/27 03:32:26 momjian Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/Attic/sprompt.c,v 1.6 2003/08/04 00:43:29 momjian Exp $ */ @@ -46,10 +46,11 @@ simple_prompt(const char *prompt, int maxlen, bool echo) #ifdef HAVE_TERMIOS_H struct termios t_orig, t; + #else #ifdef WIN32 - HANDLE t; - LPDWORD t_orig; + HANDLE t; + LPDWORD t_orig; #endif #endif @@ -88,14 +89,14 @@ simple_prompt(const char *prompt, int maxlen, bool echo) if (!echo) { /* get a new handle to turn echo off */ - t_orig=(LPDWORD)malloc(sizeof(DWORD)); - t=GetStdHandle(STD_INPUT_HANDLE); + t_orig = (LPDWORD) malloc(sizeof(DWORD)); + t = GetStdHandle(STD_INPUT_HANDLE); /* save the old configuration first */ GetConsoleMode(t, t_orig); /* set to the new mode */ - SetConsoleMode(t, ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT); + SetConsoleMode(t, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT); } #endif #endif diff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c index ab33c7f417..c608ea6d45 100644 --- a/src/bin/psql/startup.c +++ b/src/bin/psql/startup.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/startup.c,v 1.76 2003/07/28 00:14:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/startup.c,v 1.77 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" @@ -23,7 +23,7 @@ #ifndef HAVE_GETOPT_LONG #include "getopt_long.h" -int optreset; +int optreset; #endif #include @@ -75,7 +75,7 @@ struct adhoc_opts }; static void parse_psql_options(int argc, char *argv[], - struct adhoc_opts * options); + struct adhoc_opts * options); static void process_psqlrc(void); static void showVersion(void); @@ -564,7 +564,7 @@ process_psqlrc(void) if (home) { psqlrc = malloc(strlen(home) + 1 + strlen(PSQLRC) + 1 + - strlen(PG_VERSION) + 1); + strlen(PG_VERSION) + 1); if (!psqlrc) { fprintf(stderr, gettext("%s: out of memory\n"), pset.progname); diff --git a/src/bin/psql/stringutils.c b/src/bin/psql/stringutils.c index b6ecf114fe..2e6ad05e8b 100644 --- a/src/bin/psql/stringutils.c +++ b/src/bin/psql/stringutils.c @@ -3,7 +3,7 @@ * * Copyright 2000-2002 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/stringutils.c,v 1.32 2003/03/10 22:28:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/stringutils.c,v 1.33 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" @@ -28,11 +28,11 @@ static void strip_quotes(char *source, char quote, char escape, int encoding); * frammishes. * * s - string to parse, if NULL continue parsing the last string - * whitespace - set of whitespace characters that separate tokens + * whitespace - set of whitespace characters that separate tokens * delim - set of non-whitespace separator characters (or NULL) * quote - set of characters that can quote a token (NULL if none) * escape - character that can quote quotes (0 if none) - * del_quotes - if TRUE, strip quotes from the returned token, else return + * del_quotes - if TRUE, strip quotes from the returned token, else return * it exactly as found in the string * encoding - the active character-set encoding * @@ -71,9 +71,10 @@ strtokx(const char *s, if (s) { free(storage); + /* * We may need extra space to insert delimiter nulls for adjacent - * tokens. 2X the space is a gross overestimate, but it's + * tokens. 2X the space is a gross overestimate, but it's * unlikely that this code will be used on huge strings anyway. */ storage = (char *) malloc(2 * strlen(s) + 1); @@ -105,10 +106,10 @@ strtokx(const char *s, { /* * If not at end of string, we need to insert a null to terminate - * the returned token. We can just overwrite the next character - * if it happens to be in the whitespace set ... otherwise move over - * the rest of the string to make room. (This is why we allocated - * extra space above). + * the returned token. We can just overwrite the next character + * if it happens to be in the whitespace set ... otherwise move + * over the rest of the string to make room. (This is why we + * allocated extra space above). */ p = start + 1; if (*p != '\0') @@ -148,7 +149,7 @@ strtokx(const char *s, /* * If not at end of string, we need to insert a null to terminate - * the returned token. See notes above. + * the returned token. See notes above. */ if (*p != '\0') { @@ -171,10 +172,10 @@ strtokx(const char *s, } /* - * Otherwise no quoting character. Scan till next whitespace, - * delimiter or quote. NB: at this point, *start is known not to be - * '\0', whitespace, delim, or quote, so we will consume at least - * one character. + * Otherwise no quoting character. Scan till next whitespace, + * delimiter or quote. NB: at this point, *start is known not to be + * '\0', whitespace, delim, or quote, so we will consume at least one + * character. */ offset = strcspn(start, whitespace); @@ -197,8 +198,8 @@ strtokx(const char *s, p = start + offset; /* - * If not at end of string, we need to insert a null to terminate - * the returned token. See notes above. + * If not at end of string, we need to insert a null to terminate the + * returned token. See notes above. */ if (*p != '\0') { diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c index a7e9fbca3d..5e6abe2107 100644 --- a/src/bin/psql/tab-complete.c +++ b/src/bin/psql/tab-complete.c @@ -3,7 +3,7 @@ * * Copyright 2000-2002 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/tab-complete.c,v 1.82 2003/07/29 00:03:18 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/tab-complete.c,v 1.83 2003/08/04 00:43:29 momjian Exp $ */ /*---------------------------------------------------------------------- @@ -80,7 +80,7 @@ static char *create_command_generator(const char *text, int state); static char *complete_from_query(const char *text, int state); static char *complete_from_schema_query(const char *text, int state); static char *_complete_from_query(int is_schema_query, - const char *text, int state); + const char *text, int state); static char *complete_from_const(const char *text, int state); static char *complete_from_list(const char *text, int state); @@ -411,33 +411,34 @@ initialize_readline(void) typedef struct { char *name; - int with_schema; + int with_schema; char *query; } pgsql_thing_t; pgsql_thing_t words_after_create[] = { {"AGGREGATE", WITH_SCHEMA, Query_for_list_of_aggregates}, - {"CAST", NO_SCHEMA, NULL}, /* Casts have complex structures for namees, so skip it */ + {"CAST", NO_SCHEMA, NULL}, /* Casts have complex structures for + * namees, so skip it */ {"CONVERSION", NO_SCHEMA, "SELECT conname FROM pg_catalog.pg_conversion WHERE substr(conname,1,%d)='%s'"}, {"DATABASE", NO_SCHEMA, Query_for_list_of_databases}, {"DOMAIN", WITH_SCHEMA, Query_for_list_of_domains}, {"FUNCTION", WITH_SCHEMA, Query_for_list_of_functions}, {"GROUP", NO_SCHEMA, "SELECT groname FROM pg_catalog.pg_group WHERE substr(groname,1,%d)='%s'"}, {"LANGUAGE", NO_SCHEMA, Query_for_list_of_languages}, - {"INDEX", WITH_SCHEMA, Query_for_list_of_indexes}, - {"OPERATOR", NO_SCHEMA, NULL}, /* Querying for this is probably not such - * a good idea. */ + {"INDEX", WITH_SCHEMA, Query_for_list_of_indexes}, + {"OPERATOR", NO_SCHEMA, NULL}, /* Querying for this is probably + * not such a good idea. */ {"RULE", NO_SCHEMA, "SELECT rulename FROM pg_catalog.pg_rules WHERE substr(rulename,1,%d)='%s'"}, {"SCHEMA", NO_SCHEMA, Query_for_list_of_schemas}, {"SEQUENCE", WITH_SCHEMA, Query_for_list_of_sequences}, {"TABLE", WITH_SCHEMA, Query_for_list_of_tables}, - {"TEMP", NO_SCHEMA, NULL}, /* for CREATE TEMP TABLE ... */ + {"TEMP", NO_SCHEMA, NULL}, /* for CREATE TEMP TABLE ... */ {"TRIGGER", NO_SCHEMA, "SELECT tgname FROM pg_catalog.pg_trigger WHERE substr(tgname,1,%d)='%s'"}, - {"TYPE", WITH_SCHEMA, Query_for_list_of_datatypes }, - {"UNIQUE", NO_SCHEMA, NULL}, /* for CREATE UNIQUE INDEX ... */ - {"USER", NO_SCHEMA, Query_for_list_of_users}, + {"TYPE", WITH_SCHEMA, Query_for_list_of_datatypes}, + {"UNIQUE", NO_SCHEMA, NULL}, /* for CREATE UNIQUE INDEX ... */ + {"USER", NO_SCHEMA, Query_for_list_of_users}, {"VIEW", WITH_SCHEMA, Query_for_list_of_views}, - {NULL, NO_SCHEMA, NULL} /* end of list */ + {NULL, NO_SCHEMA, NULL} /* end of list */ }; @@ -594,9 +595,9 @@ psql_completion(char *text, int start, int end) }; static char *backslash_commands[] = { - "\\a", "\\connect", "\\C", "\\cd", "\\copy", "\\copyright", - "\\d", "\\da", "\\dc", "\\dC", "\\dd", "\\dD", "\\df", "\\di", - "\\dl", "\\dn", "\\do", "\\dp", "\\ds", "\\dS", "\\dt", "\\dT", + "\\a", "\\connect", "\\C", "\\cd", "\\copy", "\\copyright", + "\\d", "\\da", "\\dc", "\\dC", "\\dd", "\\dD", "\\df", "\\di", + "\\dl", "\\dn", "\\do", "\\dp", "\\ds", "\\dS", "\\dt", "\\dT", "\\dv", "\\du", "\\e", "\\echo", "\\encoding", "\\f", "\\g", "\\h", "\\help", "\\H", "\\i", "\\l", @@ -637,19 +638,22 @@ psql_completion(char *text, int start, int end) /* CREATE or DROP but not ALTER TABLE sth DROP */ /* complete with something you can create or drop */ - else if (strcasecmp(prev_wd, "CREATE") == 0 || + else if (strcasecmp(prev_wd, "CREATE") == 0 || (strcasecmp(prev_wd, "DROP") == 0 && - strcasecmp(prev3_wd,"TABLE") != 0 )) - matches = completion_matches(text, create_command_generator); + strcasecmp(prev3_wd, "TABLE") != 0)) + matches = completion_matches(text, create_command_generator); /* ALTER */ - /* complete with what you can alter (TABLE, GROUP, USER, ...) - * unless we're in ALTER TABLE sth ALTER*/ - else if (strcasecmp(prev_wd, "ALTER") == 0 && - strcasecmp(prev3_wd, "TABLE") != 0 ) + + /* + * complete with what you can alter (TABLE, GROUP, USER, ...) unless + * we're in ALTER TABLE sth ALTER + */ + else if (strcasecmp(prev_wd, "ALTER") == 0 && + strcasecmp(prev3_wd, "TABLE") != 0) { char *list_ALTER[] = {"DATABASE", "GROUP", "SCHEMA", "TABLE", - "TRIGGER", "USER", NULL}; + "TRIGGER", "USER", NULL}; COMPLETE_WITH_LIST(list_ALTER); } @@ -683,7 +687,7 @@ psql_completion(char *text, int start, int end) strcasecmp(prev2_wd, "TABLE") == 0) { char *list_ALTER2[] = {"ADD", "ALTER", "DROP", "RENAME", - "OWNER TO", NULL}; + "OWNER TO", NULL}; COMPLETE_WITH_LIST(list_ALTER2); } @@ -695,14 +699,15 @@ psql_completion(char *text, int start, int end) /* If we have TABLE DROP, provide COLUMN or CONSTRAINT */ else if (strcasecmp(prev3_wd, "TABLE") == 0 && - strcasecmp(prev_wd, "DROP") == 0) + strcasecmp(prev_wd, "DROP") == 0) { char *list_TABLEDROP[] = {"COLUMN", "CONSTRAINT", NULL}; + COMPLETE_WITH_LIST(list_TABLEDROP); } /* If we have TABLE DROP COLUMN, provide list of columns */ else if (strcasecmp(prev4_wd, "TABLE") == 0 && - strcasecmp(prev2_wd, "DROP") == 0 && + strcasecmp(prev2_wd, "DROP") == 0 && strcasecmp(prev_wd, "COLUMN") == 0) COMPLETE_WITH_ATTR(prev3_wd); @@ -769,8 +774,8 @@ psql_completion(char *text, int start, int end) { char *list_COMMENT[] = {"DATABASE", "INDEX", "RULE", "SCHEMA", "SEQUENCE", "TABLE", - "TYPE", "VIEW", "COLUMN", "AGGREGATE", "FUNCTION", "OPERATOR", - "TRIGGER", "CONSTRAINT", "DOMAIN", NULL}; + "TYPE", "VIEW", "COLUMN", "AGGREGATE", "FUNCTION", "OPERATOR", + "TRIGGER", "CONSTRAINT", "DOMAIN", NULL}; COMPLETE_WITH_LIST(list_COMMENT); } @@ -849,7 +854,7 @@ psql_completion(char *text, int start, int end) strcasecmp(prev_wd, "ON") == 0) { char *rule_events[] = {"SELECT", "UPDATE", "INSERT", - "DELETE", NULL}; + "DELETE", NULL}; COMPLETE_WITH_LIST(rule_events); } @@ -966,10 +971,11 @@ psql_completion(char *text, int start, int end) * sequences, and indexes * * keywords DATABASE, FUNCTION, LANGUAGE, SCHEMA added to query result - * via UNION; seems to work intuitively - * - * Note: GRANT/REVOKE can get quite complex; tab-completion as implemented - * here will only work if the privilege list contains exactly one privilege + * via UNION; seems to work intuitively + * + * Note: GRANT/REVOKE can get quite complex; tab-completion as + * implemented here will only work if the privilege list contains + * exactly one privilege */ else if ((strcasecmp(prev3_wd, "GRANT") == 0 || strcasecmp(prev3_wd, "REVOKE") == 0) && @@ -977,30 +983,30 @@ psql_completion(char *text, int start, int end) COMPLETE_WITH_QUERY("SELECT relname FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n " " WHERE relkind in ('r','S','v') " " AND substr(relname,1,%d)='%s' " - " AND pg_catalog.pg_table_is_visible(c.oid) " + " AND pg_catalog.pg_table_is_visible(c.oid) " " AND relnamespace = n.oid " - " AND n.nspname NOT IN ('pg_catalog', 'pg_toast') " - " UNION " - "SELECT 'DATABASE' AS relname " - " UNION " - "SELECT 'FUNCTION' AS relname " - " UNION " - "SELECT 'LANGUAGE' AS relname " - " UNION " - "SELECT 'SCHEMA' AS relname "); + " AND n.nspname NOT IN ('pg_catalog', 'pg_toast') " + " UNION " + "SELECT 'DATABASE' AS relname " + " UNION " + "SELECT 'FUNCTION' AS relname " + " UNION " + "SELECT 'LANGUAGE' AS relname " + " UNION " + "SELECT 'SCHEMA' AS relname "); /* Complete "GRANT/REVOKE * ON * " with "TO" */ - else if ((strcasecmp(prev4_wd, "GRANT") == 0 || + else if ((strcasecmp(prev4_wd, "GRANT") == 0 || strcasecmp(prev4_wd, "REVOKE") == 0) && strcasecmp(prev2_wd, "ON") == 0) { - if(strcasecmp(prev_wd, "DATABASE") == 0) + if (strcasecmp(prev_wd, "DATABASE") == 0) COMPLETE_WITH_QUERY(Query_for_list_of_databases); - else if(strcasecmp(prev_wd, "FUNCTION") == 0) + else if (strcasecmp(prev_wd, "FUNCTION") == 0) COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions); - else if(strcasecmp(prev_wd, "LANGUAGE") == 0) + else if (strcasecmp(prev_wd, "LANGUAGE") == 0) COMPLETE_WITH_QUERY(Query_for_list_of_languages); - else if(strcasecmp(prev_wd, "SCHEMA") == 0) + else if (strcasecmp(prev_wd, "SCHEMA") == 0) COMPLETE_WITH_QUERY(Query_for_list_of_schemas); else COMPLETE_WITH_CONST("TO"); @@ -1008,8 +1014,8 @@ psql_completion(char *text, int start, int end) /* * TODO: to complete with user name we need prev5_wd -- wait for a - * more general solution there - * same for GRANT ON { DATABASE | FUNCTION | LANGUAGE | SCHEMA } xxx TO + * more general solution there same for GRANT ON { DATABASE | + * FUNCTION | LANGUAGE | SCHEMA } xxx TO */ /* INSERT */ @@ -1055,7 +1061,7 @@ psql_completion(char *text, int start, int end) /* LOCK */ /* Complete LOCK [TABLE] with a list of tables */ else if (strcasecmp(prev_wd, "LOCK") == 0 || - (strcasecmp(prev_wd, "TABLE") == 0 && + (strcasecmp(prev_wd, "TABLE") == 0 && strcasecmp(prev2_wd, "LOCK") == 0)) COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables); @@ -1078,7 +1084,7 @@ psql_completion(char *text, int start, int end) "ROW SHARE MODE", "ROW EXCLUSIVE MODE", "SHARE UPDATE EXCLUSIVE MODE", "SHARE MODE", "SHARE ROW EXCLUSIVE MODE", - "EXCLUSIVE MODE", "ACCESS EXCLUSIVE MODE", NULL}; + "EXCLUSIVE MODE", "ACCESS EXCLUSIVE MODE", NULL}; COMPLETE_WITH_LIST(lock_modes); } @@ -1188,9 +1194,9 @@ psql_completion(char *text, int start, int end) if (strcasecmp(prev2_wd, "DateStyle") == 0) { char *my_list[] = {"ISO", "SQL", "Postgres", "German", - "YMD", "DMY", "MDY", - "US", "European", "NonEuropean", - "DEFAULT", NULL}; + "YMD", "DMY", "MDY", + "US", "European", "NonEuropean", + "DEFAULT", NULL}; COMPLETE_WITH_LIST(my_list); } @@ -1289,7 +1295,7 @@ psql_completion(char *text, int start, int end) { char *my_list[] = {"format", "border", "expanded", "null", "fieldsep", "tuples_only", "title", "tableattr", "pager", - "recordsep", NULL}; + "recordsep", NULL}; COMPLETE_WITH_LIST(my_list); } @@ -1316,7 +1322,7 @@ psql_completion(char *text, int start, int end) for (i = 0; words_after_create[i].name; i++) if (strcasecmp(prev_wd, words_after_create[i].name) == 0) { - if(words_after_create[i].with_schema == WITH_SCHEMA) + if (words_after_create[i].with_schema == WITH_SCHEMA) COMPLETE_WITH_SCHEMA_QUERY(words_after_create[i].query); else COMPLETE_WITH_QUERY(words_after_create[i].query); @@ -1397,27 +1403,27 @@ create_command_generator(const char *text, int state) static char * complete_from_query(const char *text, int state) { - return _complete_from_query(0, text, state); + return _complete_from_query(0, text, state); } static char * complete_from_schema_query(const char *text, int state) { - return _complete_from_query(1, text, state); + return _complete_from_query(1, text, state); } /* This creates a list of matching things, according to a query pointed to by completion_charp. The query can be one of two kinds: - - A simple query which must contain a %d and a %s, which will be replaced + - A simple query which must contain a %d and a %s, which will be replaced by the string length of the text and the text itself. The query may also - have another %s in it, which will be replaced by the value of + have another %s in it, which will be replaced by the value of completion_info_charp. - or: + or: - A schema query used for completion of both schema and relation names; these are more complex and must contain in the following order: - %d %s %d %s %d %s %s %d %s + %d %s %d %s %d %s %s %d %s where %d is the string length of the text and %s the text itself. See top of file for examples of both kinds of query. @@ -1445,20 +1451,21 @@ _complete_from_query(int is_schema_query, const char *text, int state) if (completion_charp == NULL) return NULL; - if(is_schema_query) + if (is_schema_query) { - if (snprintf(query_buffer, BUF_SIZE, completion_charp, string_length, text, string_length, text, string_length, text, text, string_length, text,string_length,text) == -1) - { - ERROR_QUERY_TOO_LONG; - return NULL; - } + if (snprintf(query_buffer, BUF_SIZE, completion_charp, string_length, text, string_length, text, string_length, text, text, string_length, text, string_length, text) == -1) + { + ERROR_QUERY_TOO_LONG; + return NULL; + } } - else { - if (snprintf(query_buffer, BUF_SIZE, completion_charp, string_length, text, completion_info_charp) == -1) - { - ERROR_QUERY_TOO_LONG; - return NULL; - } + else + { + if (snprintf(query_buffer, BUF_SIZE, completion_charp, string_length, text, completion_info_charp) == -1) + { + ERROR_QUERY_TOO_LONG; + return NULL; + } } result = exec_query(query_buffer); @@ -1488,7 +1495,7 @@ complete_from_list(const char *text, int state) static int string_length, list_index, matches; - static bool casesensitive; + static bool casesensitive; char *item; /* need to have a list */ @@ -1520,8 +1527,8 @@ complete_from_list(const char *text, int state) } /* - * No matches found. If we're not case insensitive already, lets switch - * to being case insensitive and try again + * No matches found. If we're not case insensitive already, lets + * switch to being case insensitive and try again */ if (casesensitive && matches == 0) { diff --git a/src/bin/psql/variables.c b/src/bin/psql/variables.c index 6b4c42786e..0f3b74a12c 100644 --- a/src/bin/psql/variables.c +++ b/src/bin/psql/variables.c @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/variables.c,v 1.11 2003/06/28 00:12:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/variables.c,v 1.12 2003/08/04 00:43:29 momjian Exp $ */ #include "postgres_fe.h" #include "variables.h" @@ -67,7 +67,11 @@ GetVariableBool(VariableSpace space, const char *name) return false; /* not set -> assume "off" */ if (strcmp(val, "off") == 0) return false; - /* for backwards compatibility, anything except "off" is taken as "true" */ + + /* + * for backwards compatibility, anything except "off" is taken as + * "true" + */ return true; } @@ -75,65 +79,69 @@ bool VariableEquals(VariableSpace space, const char name[], const char value[]) { const char *var; + var = GetVariable(space, name); return var && (strcmp(var, value) == 0); } -int -GetVariableNum(VariableSpace space, - const char name[], - int defaultval, - int faultval, - bool allowtrail) +int +GetVariableNum(VariableSpace space, + const char name[], + int defaultval, + int faultval, + bool allowtrail) { const char *var; - int result; + int result; var = GetVariable(space, name); if (!var) - result = defaultval; + result = defaultval; else if (!var[0]) - result = faultval; + result = faultval; else { - char *end; + char *end; + result = strtol(var, &end, 0); if (!allowtrail && *end) - result = faultval; + result = faultval; } return result; } int -SwitchVariable(VariableSpace space, const char name[], const char *opt, ...) +SwitchVariable(VariableSpace space, const char name[], const char *opt,...) { - int result; + int result; const char *var; var = GetVariable(space, name); - if (var) + if (var) { - va_list args; + va_list args; + va_start(args, opt); - for (result=1; opt && (strcmp(var, opt) != 0); result++) - opt = va_arg(args,const char *); + for (result = 1; opt && (strcmp(var, opt) != 0); result++) + opt = va_arg(args, const char *); if (!opt) result = VAR_NOTFOUND; va_end(args); } else - result = VAR_NOTSET; + result = VAR_NOTSET; return result; } -void +void PrintVariables(VariableSpace space) { - struct _variable *ptr; - for (ptr = space->next; ptr; ptr = ptr->next) - printf("%s = '%s'\n", ptr->name, ptr->value); + struct _variable *ptr; + + for (ptr = space->next; ptr; ptr = ptr->next) + printf("%s = '%s'\n", ptr->name, ptr->value); } bool diff --git a/src/bin/psql/variables.h b/src/bin/psql/variables.h index ce239975ef..e69df16a7c 100644 --- a/src/bin/psql/variables.h +++ b/src/bin/psql/variables.h @@ -3,7 +3,7 @@ * * Copyright 2000 by PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/psql/variables.h,v 1.12 2003/06/28 00:12:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/psql/variables.h,v 1.13 2003/08/04 00:43:29 momjian Exp $ */ /* @@ -30,33 +30,36 @@ typedef struct _variable *VariableSpace; VariableSpace CreateVariableSpace(void); const char *GetVariable(VariableSpace space, const char *name); -bool GetVariableBool(VariableSpace space, const char *name); -bool VariableEquals(VariableSpace space, const char name[], const char *opt); +bool GetVariableBool(VariableSpace space, const char *name); +bool VariableEquals(VariableSpace space, const char name[], const char *opt); /* Read numeric variable, or defaultval if it is not set, or faultval if its - * value is not a valid numeric string. If allowtrail is false, this will + * value is not a valid numeric string. If allowtrail is false, this will * include the case where there are trailing characters after the number. */ -int GetVariableNum(VariableSpace space, - const char name[], - int defaultval, - int faultval, - bool allowtrail); +int GetVariableNum(VariableSpace space, + const char name[], + int defaultval, + int faultval, + bool allowtrail); -/* Find value of variable among NULL-terminated list of alternative +/* Find value of variable among NULL-terminated list of alternative * options. Returns VAR_NOTSET if the variable was not set, VAR_NOTFOUND * if its value did not occur in the list of options, or the number of the * matching option. The first option is 1, the second is 2 and so on. */ -enum { VAR_NOTSET = 0, VAR_NOTFOUND = -1 }; -int SwitchVariable(VariableSpace space, const char name[], - const char *opt, ...); +enum +{ +VAR_NOTSET = 0, VAR_NOTFOUND = -1}; +int +SwitchVariable(VariableSpace space, const char name[], + const char *opt,...); -void PrintVariables(VariableSpace space); +void PrintVariables(VariableSpace space); -bool SetVariable(VariableSpace space, const char *name, const char *value); -bool SetVariableBool(VariableSpace space, const char *name); -bool DeleteVariable(VariableSpace space, const char *name); +bool SetVariable(VariableSpace space, const char *name, const char *value); +bool SetVariableBool(VariableSpace space, const char *name); +bool DeleteVariable(VariableSpace space, const char *name); #endif /* VARIABLES_H */ diff --git a/src/bin/scripts/clusterdb.c b/src/bin/scripts/clusterdb.c index 3f491ac9e7..cd91ad0cb7 100644 --- a/src/bin/scripts/clusterdb.c +++ b/src/bin/scripts/clusterdb.c @@ -4,7 +4,7 @@ * * Portions Copyright (c) 2002-2003, PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/bin/scripts/clusterdb.c,v 1.2 2003/07/23 08:47:41 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/clusterdb.c,v 1.3 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -15,12 +15,14 @@ static -void cluster_one_database(const char *dbname, const char *table, - const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet); +void +cluster_one_database(const char *dbname, const char *table, + const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet); static -void cluster_all_databases(const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet); +void +cluster_all_databases(const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet); static void help(const char *progname); @@ -104,7 +106,7 @@ main(int argc, char *argv[]) dbname = argv[optind]; break; default: - fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), + fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind + 1]); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); @@ -124,7 +126,7 @@ main(int argc, char *argv[]) progname); exit(1); } - + cluster_all_databases(host, port, username, password, progname, echo, quiet); } @@ -150,9 +152,10 @@ main(int argc, char *argv[]) static -void cluster_one_database(const char *dbname, const char *table, - const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet) +void +cluster_one_database(const char *dbname, const char *table, + const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet) { PQExpBufferData sql; @@ -194,8 +197,9 @@ void cluster_one_database(const char *dbname, const char *table, static -void cluster_all_databases(const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet) +void +cluster_all_databases(const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet) { PGconn *conn; PGresult *result; diff --git a/src/bin/scripts/common.c b/src/bin/scripts/common.c index 2e0612a8e7..dc27a94477 100644 --- a/src/bin/scripts/common.c +++ b/src/bin/scripts/common.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/scripts/common.c,v 1.3 2003/05/27 19:36:54 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/common.c,v 1.4 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -78,7 +78,7 @@ handle_help_version_opts(int argc, char *argv[], const char *fixed_progname, hel */ PGconn * connectDatabase(const char *dbname, const char *pghost, const char *pgport, - const char *pguser, bool require_password, const char *progname) + const char *pguser, bool require_password, const char *progname) { PGconn *conn; char *password = NULL; @@ -156,7 +156,7 @@ executeQuery(PGconn *conn, const char *query, const char *progname, bool echo) /* - * Check yes/no answer in a localized way. 1=yes, 0=no, -1=neither. + * Check yes/no answer in a localized way. 1=yes, 0=no, -1=neither. */ /* translator: Make sure the (y/n) prompts match the translation of this. */ diff --git a/src/bin/scripts/common.h b/src/bin/scripts/common.h index 8fb33dfd03..8a6431e724 100644 --- a/src/bin/scripts/common.h +++ b/src/bin/scripts/common.h @@ -1,7 +1,7 @@ #include "postgres_fe.h" #ifdef HAVE_GETOPT_H -# include +#include #endif #ifndef HAVE_GETOPT_LONG @@ -12,26 +12,25 @@ #include "pqexpbuffer.h" #ifndef HAVE_OPTRESET -int optreset; +int optreset; #endif const char *get_user_name(const char *progname); #define _(x) gettext((x)) -void init_nls(void); +void init_nls(void); -typedef void (*help_handler)(const char *); +typedef void (*help_handler) (const char *); -void handle_help_version_opts(int argc, char *argv[], const char *fixed_progname, help_handler hlp); +void handle_help_version_opts(int argc, char *argv[], const char *fixed_progname, help_handler hlp); extern char *simple_prompt(const char *prompt, int maxlen, bool echo); -PGconn * -connectDatabase(const char *dbname, const char *pghost, const char *pgport, - const char *pguser, bool require_password, const char *progname); +PGconn *connectDatabase(const char *dbname, const char *pghost, const char *pgport, + const char *pguser, bool require_password, const char *progname); PGresult * -executeQuery(PGconn *conn, const char *command, const char *progname, bool echo); + executeQuery(PGconn *conn, const char *command, const char *progname, bool echo); int -check_yesno_response(const char *string); + check_yesno_response(const char *string); diff --git a/src/bin/scripts/createdb.c b/src/bin/scripts/createdb.c index 7677c2cc7e..1f7df9104d 100644 --- a/src/bin/scripts/createdb.c +++ b/src/bin/scripts/createdb.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/scripts/createdb.c,v 1.4 2003/07/23 08:47:41 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/createdb.c,v 1.5 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -115,7 +115,7 @@ main(int argc, char *argv[]) comment = argv[optind + 1]; break; default: - fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), + fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind + 2]); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); diff --git a/src/bin/scripts/createlang.c b/src/bin/scripts/createlang.c index 01df2a3275..3b4a9b060d 100644 --- a/src/bin/scripts/createlang.c +++ b/src/bin/scripts/createlang.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/scripts/createlang.c,v 1.5 2003/07/23 08:47:41 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/createlang.c,v 1.6 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -110,9 +110,9 @@ main(int argc, char *argv[]) if (argc - optind > 0) { - fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), + fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]); - fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); + fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } @@ -154,7 +154,7 @@ main(int argc, char *argv[]) if (langname == NULL) { fprintf(stderr, _("%s: missing required argument language name\n"), progname); - fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); + fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } @@ -165,37 +165,37 @@ main(int argc, char *argv[]) if (*p >= 'A' && *p <= 'Z') *p += ('a' - 'A'); - if (strcmp(langname, "plpgsql")==0) + if (strcmp(langname, "plpgsql") == 0) { trusted = true; handler = "plpgsql_call_handler"; object = "plpgsql"; } - else if (strcmp(langname, "pltcl")==0) + else if (strcmp(langname, "pltcl") == 0) { trusted = true; handler = "pltcl_call_handler"; object = "pltcl"; } - else if (strcmp(langname, "pltclu")==0) + else if (strcmp(langname, "pltclu") == 0) { trusted = false; handler = "pltclu_call_handler"; object = "pltcl"; } - else if (strcmp(langname, "plperl")==0) + else if (strcmp(langname, "plperl") == 0) { trusted = true; handler = "plperl_call_handler"; object = "plperl"; } - else if (strcmp(langname, "plperlu")==0) + else if (strcmp(langname, "plperlu") == 0) { trusted = false; handler = "plperl_call_handler"; object = "plperl"; } - else if (strcmp(langname, "plpythonu")==0) + else if (strcmp(langname, "plpythonu") == 0) { trusted = false; handler = "plpython_call_handler"; diff --git a/src/bin/scripts/createuser.c b/src/bin/scripts/createuser.c index 0da4e78318..f113456fbc 100644 --- a/src/bin/scripts/createuser.c +++ b/src/bin/scripts/createuser.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/scripts/createuser.c,v 1.5 2003/07/23 08:47:41 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/createuser.c,v 1.6 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -148,11 +148,12 @@ main(int argc, char *argv[]) if (pwprompt) { - char *pw1, *pw2; + char *pw1, + *pw2; pw1 = simple_prompt("Enter password for new user: ", 100, false); pw2 = simple_prompt("Enter it again: ", 100, false); - if (strcmp(pw1, pw2)!=0) + if (strcmp(pw1, pw2) != 0) { fprintf(stderr, _("Passwords didn't match.\n")); exit(1); @@ -242,9 +243,9 @@ help(const char *progname) printf(_(" -P, --pwprompt assign a password to new user\n")); printf(_(" -E, --encrypted encrypt stored password\n")); printf(_(" -N, --unencrypted do no encrypt stored password\n")); - printf(_(" -i, --sysid=SYSID select sysid for new user\n" )); + printf(_(" -i, --sysid=SYSID select sysid for new user\n")); printf(_(" -e, --echo show the commands being sent to the server\n")); - printf(_(" -q, --quiet don't write any messages\n")); + printf(_(" -q, --quiet don't write any messages\n")); printf(_(" --help show this help, then exit\n")); printf(_(" --version output version information, then exit\n")); printf(_("\nConnection options:\n")); diff --git a/src/bin/scripts/dropdb.c b/src/bin/scripts/dropdb.c index a8bcc1a8f7..5e53defd6b 100644 --- a/src/bin/scripts/dropdb.c +++ b/src/bin/scripts/dropdb.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/scripts/dropdb.c,v 1.5 2003/07/23 08:47:41 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/dropdb.c,v 1.6 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -88,7 +88,7 @@ main(int argc, char *argv[]) switch (argc - optind) { case 0: - fprintf(stderr, _("%s: missing required argument database name\n"), progname); + fprintf(stderr, _("%s: missing required argument database name\n"), progname); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); case 1: diff --git a/src/bin/scripts/droplang.c b/src/bin/scripts/droplang.c index 64d0fb0f42..08a588e348 100644 --- a/src/bin/scripts/droplang.c +++ b/src/bin/scripts/droplang.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/scripts/droplang.c,v 1.4 2003/07/23 08:47:41 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/droplang.c,v 1.5 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -104,9 +104,9 @@ main(int argc, char *argv[]) if (argc - optind > 0) { - fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), + fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]); - fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); + fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } @@ -148,7 +148,7 @@ main(int argc, char *argv[]) if (langname == NULL) { fprintf(stderr, _("%s: missing required argument language name\n"), progname); - fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); + fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } @@ -159,7 +159,8 @@ main(int argc, char *argv[]) conn = connectDatabase(dbname, host, port, username, password, progname); /* - * Make sure the language is installed and find the OID of the handler function + * Make sure the language is installed and find the OID of the handler + * function */ printfPQExpBuffer(&sql, "SELECT lanplcallfoid FROM pg_language WHERE lanname = '%s' AND lanispl;", langname); result = executeQuery(conn, sql.data, progname, echo); @@ -178,7 +179,7 @@ main(int argc, char *argv[]) */ printfPQExpBuffer(&sql, "SELECT count(proname) FROM pg_proc P, pg_language L WHERE P.prolang = L.oid AND L.lanname = '%s';", langname); result = executeQuery(conn, sql.data, progname, echo); - if (strcmp(PQgetvalue(result, 0, 0), "0")!=0) + if (strcmp(PQgetvalue(result, 0, 0), "0") != 0) { PQfinish(conn); fprintf(stderr, @@ -193,7 +194,7 @@ main(int argc, char *argv[]) */ printfPQExpBuffer(&sql, "SELECT count(*) FROM pg_language WHERE lanplcallfoid = %s AND lanname <> '%s';", lanplcallfoid, langname); result = executeQuery(conn, sql.data, progname, echo); - if (strcmp(PQgetvalue(result, 0, 0), "0")==0) + if (strcmp(PQgetvalue(result, 0, 0), "0") == 0) keephandler = false; else keephandler = true; diff --git a/src/bin/scripts/vacuumdb.c b/src/bin/scripts/vacuumdb.c index 8018a3f122..2d17be40d1 100644 --- a/src/bin/scripts/vacuumdb.c +++ b/src/bin/scripts/vacuumdb.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/bin/scripts/vacuumdb.c,v 1.2 2003/07/23 08:47:41 petere Exp $ + * $Header: /cvsroot/pgsql/src/bin/scripts/vacuumdb.c,v 1.3 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -15,13 +15,15 @@ static -void vacuum_one_database(const char *dbname, bool full, bool verbose, bool analyze, const char *table, - const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet); +void +vacuum_one_database(const char *dbname, bool full, bool verbose, bool analyze, const char *table, + const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet); static -void vacuum_all_databases(bool full, bool verbose, bool analyze, - const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet); +void +vacuum_all_databases(bool full, bool verbose, bool analyze, + const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet); static void help(const char *progname); @@ -120,7 +122,7 @@ main(int argc, char *argv[]) dbname = argv[optind]; break; default: - fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), + fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind + 1]); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); @@ -140,7 +142,7 @@ main(int argc, char *argv[]) progname); exit(1); } - + vacuum_all_databases(full, verbose, analyze, host, port, username, password, progname, echo, quiet); @@ -167,9 +169,10 @@ main(int argc, char *argv[]) static -void vacuum_one_database(const char *dbname, bool full, bool verbose, bool analyze, const char *table, - const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet) +void +vacuum_one_database(const char *dbname, bool full, bool verbose, bool analyze, const char *table, + const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet) { PQExpBufferData sql; @@ -217,9 +220,10 @@ void vacuum_one_database(const char *dbname, bool full, bool verbose, bool analy static -void vacuum_all_databases(bool full, bool verbose, bool analyze, - const char *host, const char *port, const char *username, bool password, - const char *progname, bool echo, bool quiet) +void +vacuum_all_databases(bool full, bool verbose, bool analyze, + const char *host, const char *port, const char *username, bool password, + const char *progname, bool echo, bool quiet) { PGconn *conn; PGresult *result; diff --git a/src/include/access/genam.h b/src/include/access/genam.h index 934defb8a7..ac61ec35ac 100644 --- a/src/include/access/genam.h +++ b/src/include/access/genam.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: genam.h,v 1.40 2003/07/27 17:10:06 tgl Exp $ + * $Id: genam.h,v 1.41 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -34,8 +34,8 @@ typedef struct IndexBulkDeleteResult BlockNumber num_pages; /* pages remaining in index */ double num_index_tuples; /* tuples remaining */ double tuples_removed; /* # removed by bulk-delete operation */ - BlockNumber pages_deleted; /* # unused pages in index */ - BlockNumber pages_free; /* # pages available for reuse */ + BlockNumber pages_deleted; /* # unused pages in index */ + BlockNumber pages_free; /* # pages available for reuse */ } IndexBulkDeleteResult; /* Typedef for callback function to determine if a tuple is bulk-deletable */ @@ -46,7 +46,7 @@ typedef struct IndexVacuumCleanupInfo { bool vacuum_full; /* VACUUM FULL (we have exclusive lock) */ int message_level; /* ereport level for progress messages */ -} IndexVacuumCleanupInfo; +} IndexVacuumCleanupInfo; /* Struct for heap-or-index scans of system tables */ typedef struct SysScanDescData @@ -89,8 +89,8 @@ extern IndexBulkDeleteResult *index_bulk_delete(Relation indexRelation, IndexBulkDeleteCallback callback, void *callback_state); extern IndexBulkDeleteResult *index_vacuum_cleanup(Relation indexRelation, - IndexVacuumCleanupInfo *info, - IndexBulkDeleteResult *stats); + IndexVacuumCleanupInfo * info, + IndexBulkDeleteResult *stats); extern RegProcedure index_cost_estimator(Relation indexRelation); extern RegProcedure index_getprocid(Relation irel, AttrNumber attnum, uint16 procnum); diff --git a/src/include/access/heapam.h b/src/include/access/heapam.h index 06a0772bba..b6df722086 100644 --- a/src/include/access/heapam.h +++ b/src/include/access/heapam.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: heapam.h,v 1.81 2003/02/23 20:32:12 tgl Exp $ + * $Id: heapam.h,v 1.82 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -173,7 +173,7 @@ extern void heap_redo(XLogRecPtr lsn, XLogRecord *rptr); extern void heap_undo(XLogRecPtr lsn, XLogRecord *rptr); extern void heap_desc(char *buf, uint8 xl_info, char *rec); extern XLogRecPtr log_heap_clean(Relation reln, Buffer buffer, - OffsetNumber *unused, int uncnt); + OffsetNumber *unused, int uncnt); extern XLogRecPtr log_heap_move(Relation reln, Buffer oldbuf, ItemPointerData from, Buffer newbuf, HeapTuple newtup); diff --git a/src/include/access/nbtree.h b/src/include/access/nbtree.h index d6ea70cd7d..28b19c50dc 100644 --- a/src/include/access/nbtree.h +++ b/src/include/access/nbtree.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: nbtree.h,v 1.67 2003/02/23 22:43:09 tgl Exp $ + * $Id: nbtree.h,v 1.68 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -26,7 +26,7 @@ * a search has navigated to the wrong page due to concurrent page splits * or deletions; see src/backend/access/nbtree/README for more info. * - * In addition, we store the page's btree level (counting upwards from + * In addition, we store the page's btree level (counting upwards from * zero at a leaf page) as well as some flag bits indicating the page type * and status. If the page is deleted, we replace the level with the * next-transaction-ID value indicating when it is safe to reclaim the page. @@ -41,9 +41,9 @@ typedef struct BTPageOpaqueData BlockNumber btpo_next; /* right sibling, or P_NONE if rightmost */ union { - uint32 level; /* tree level --- zero for leaf pages */ + uint32 level; /* tree level --- zero for leaf pages */ TransactionId xact; /* next transaction ID, if deleted */ - } btpo; + } btpo; uint16 btpo_flags; /* flag bits, see below */ } BTPageOpaqueData; @@ -185,15 +185,16 @@ typedef BTItemData *BTItem; * record xl_info field */ #define XLOG_BTREE_INSERT_LEAF 0x00 /* add btitem without split */ -#define XLOG_BTREE_INSERT_UPPER 0x10 /* same, on a non-leaf page */ +#define XLOG_BTREE_INSERT_UPPER 0x10 /* same, on a non-leaf page */ #define XLOG_BTREE_INSERT_META 0x20 /* same, plus update metapage */ #define XLOG_BTREE_SPLIT_L 0x30 /* add btitem with split */ #define XLOG_BTREE_SPLIT_R 0x40 /* as above, new item on right */ -#define XLOG_BTREE_SPLIT_L_ROOT 0x50 /* add btitem with split of root */ -#define XLOG_BTREE_SPLIT_R_ROOT 0x60 /* as above, new item on right */ +#define XLOG_BTREE_SPLIT_L_ROOT 0x50 /* add btitem with split of root */ +#define XLOG_BTREE_SPLIT_R_ROOT 0x60 /* as above, new item on right */ #define XLOG_BTREE_DELETE 0x70 /* delete leaf btitem */ #define XLOG_BTREE_DELETE_PAGE 0x80 /* delete an entire page */ -#define XLOG_BTREE_DELETE_PAGE_META 0x90 /* same, plus update metapage */ +#define XLOG_BTREE_DELETE_PAGE_META 0x90 /* same, plus update + * metapage */ #define XLOG_BTREE_NEWROOT 0xA0 /* new root page */ #define XLOG_BTREE_NEWMETA 0xB0 /* update metadata page */ #define XLOG_BTREE_NEWPAGE 0xC0 /* new index page during build */ @@ -216,7 +217,7 @@ typedef struct xl_btree_metadata uint32 level; BlockNumber fastroot; uint32 fastlevel; -} xl_btree_metadata; +} xl_btree_metadata; /* * This is what we need to know about simple (without split) insert. @@ -245,7 +246,7 @@ typedef struct xl_btree_insert * left or right split page (and thus, whether otherblk is the right or left * page of the split pair). The _ROOT variants indicate that we are splitting * the root page, and thus that a newroot record rather than an insert or - * split record should follow. Note that a split record never carries a + * split record should follow. Note that a split record never carries a * metapage update --- we'll do that in the parent-level update. */ typedef struct xl_btree_split @@ -279,7 +280,7 @@ typedef struct xl_btree_delete /* * This is what we need to know about deletion of a btree page. The target * identifies the tuple removed from the parent page (note that we remove - * this tuple's downlink and the *following* tuple's key). Note we do not + * this tuple's downlink and the *following* tuple's key). Note we do not * store any content for the deleted page --- it is just rewritten as empty * during recovery. */ @@ -290,7 +291,7 @@ typedef struct xl_btree_delete_page BlockNumber leftblk; /* child block's left sibling, if any */ BlockNumber rightblk; /* child block's right sibling */ /* xl_btree_metadata FOLLOWS IF XLOG_BTREE_DELETE_PAGE_META */ -} xl_btree_delete_page; +} xl_btree_delete_page; #define SizeOfBtreeDeletePage (offsetof(xl_btree_delete_page, rightblk) + sizeof(BlockNumber)) @@ -320,7 +321,7 @@ typedef struct xl_btree_newmeta { RelFileNode node; xl_btree_metadata meta; -} xl_btree_newmeta; +} xl_btree_newmeta; #define SizeOfBtreeNewmeta (sizeof(xl_btree_newmeta)) @@ -332,7 +333,7 @@ typedef struct xl_btree_newpage RelFileNode node; BlockNumber blkno; /* location of new page */ /* entire page contents follow at end of record */ -} xl_btree_newpage; +} xl_btree_newpage; #define SizeOfBtreeNewpage (offsetof(xl_btree_newpage, blkno) + sizeof(BlockNumber)) @@ -442,7 +443,7 @@ extern InsertIndexResult _bt_doinsert(Relation rel, BTItem btitem, bool index_is_unique, Relation heapRel); extern Buffer _bt_getstackbuf(Relation rel, BTStack stack, int access); extern void _bt_insert_parent(Relation rel, Buffer buf, Buffer rbuf, - BTStack stack, bool is_root, bool is_only); + BTStack stack, bool is_root, bool is_only); /* * prototypes for functions in nbtpage.c @@ -458,7 +459,7 @@ extern void _bt_pageinit(Page page, Size size); extern bool _bt_page_recyclable(Page page); extern void _bt_metaproot(Relation rel, BlockNumber rootbknum, uint32 level); extern void _bt_delitems(Relation rel, Buffer buf, - OffsetNumber *itemnos, int nitems); + OffsetNumber *itemnos, int nitems); extern int _bt_pagedel(Relation rel, Buffer buf, bool vacuum_full); /* diff --git a/src/include/access/printtup.h b/src/include/access/printtup.h index 981b0f2648..69a446d657 100644 --- a/src/include/access/printtup.h +++ b/src/include/access/printtup.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: printtup.h,v 1.27 2003/05/08 18:16:37 tgl Exp $ + * $Id: printtup.h,v 1.28 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -19,16 +19,16 @@ extern DestReceiver *printtup_create_DR(CommandDest dest, Portal portal); extern void SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, - int16 *formats); + int16 *formats); extern void debugStartup(DestReceiver *self, int operation, - TupleDesc typeinfo); + TupleDesc typeinfo); extern void debugtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self); /* XXX these are really in executor/spi.c */ extern void spi_dest_startup(DestReceiver *self, int operation, - TupleDesc typeinfo); + TupleDesc typeinfo); extern void spi_printtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self); diff --git a/src/include/access/relscan.h b/src/include/access/relscan.h index 898afa64bb..1675248544 100644 --- a/src/include/access/relscan.h +++ b/src/include/access/relscan.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: relscan.h,v 1.30 2003/01/08 19:41:40 tgl Exp $ + * $Id: relscan.h,v 1.31 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -76,8 +76,8 @@ typedef struct IndexScanDescData * the logical scan position for itself. It does that using * unique_tuple_pos: -1 = before row, 0 = on row, +1 = after row. */ - int unique_tuple_pos; /* logical position */ - int unique_tuple_mark; /* logical marked position */ + int unique_tuple_pos; /* logical position */ + int unique_tuple_mark; /* logical marked position */ PgStat_Info xs_pgstat_info; /* statistics collector hook */ } IndexScanDescData; diff --git a/src/include/access/slru.h b/src/include/access/slru.h index 1386d7e201..6a8b63a3ff 100644 --- a/src/include/access/slru.h +++ b/src/include/access/slru.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: slru.h,v 1.1 2003/06/11 22:37:46 momjian Exp $ + * $Id: slru.h,v 1.2 2003/08/04 00:43:30 momjian Exp $ */ #ifndef SLRU_H #define SLRU_H @@ -18,42 +18,42 @@ typedef struct SlruLockData { - LWLockId ControlLock; + LWLockId ControlLock; /* * BufferLocks is set during CLOGShmemInit and does not change thereafter. * The value is automatically inherited by backends via fork, and * doesn't need to be in shared memory. */ - LWLockId BufferLocks[NUM_CLOG_BUFFERS]; /* Per-buffer I/O locks */ -} SlruLockData; + LWLockId BufferLocks[NUM_CLOG_BUFFERS]; /* Per-buffer I/O locks */ +} SlruLockData; typedef SlruLockData *SlruLock; typedef struct SlruCtlData { - void *shared; /* pointer to SlruSharedData */ - SlruLock locks; + void *shared; /* pointer to SlruSharedData */ + SlruLock locks; /* * Dir is set during SimpleLruShmemInit and does not change thereafter. * The value is automatically inherited by backends via fork, and * doesn't need to be in shared memory. */ - char Dir[MAXPGPATH]; - + char Dir[MAXPGPATH]; + /* * Decide which of two page numbers is "older" for truncation purposes. * We need to use comparison of TransactionIds here in order to do the right * thing with wraparound XID arithmetic. */ - bool (*PagePrecedes)(int, int); + bool (*PagePrecedes) (int, int); -} SlruCtlData; +} SlruCtlData; typedef SlruCtlData *SlruCtl; extern int SimpleLruShmemSize(void); extern void SimpleLruInit(SlruCtl ctl, const char *name, const char *subdir); extern int SimpleLruZeroPage(SlruCtl ctl, int pageno); -extern char *SimpleLruReadPage(SlruCtl ctl, int pageno, TransactionId xid, bool forwrite); +extern char *SimpleLruReadPage(SlruCtl ctl, int pageno, TransactionId xid, bool forwrite); extern void SimpleLruWritePage(SlruCtl ctl, int slotno); extern void SimpleLruSetLatestPage(SlruCtl ctl, int pageno); extern void SimpleLruFlush(SlruCtl ctl, bool checkpoint); diff --git a/src/include/access/xact.h b/src/include/access/xact.h index aa284df016..4a8c5f6772 100644 --- a/src/include/access/xact.h +++ b/src/include/access/xact.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: xact.h,v 1.52 2003/05/14 03:26:03 tgl Exp $ + * $Id: xact.h,v 1.53 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -31,8 +31,8 @@ extern int DefaultXactIsoLevel; extern int XactIsoLevel; /* Xact read-only state */ -extern bool DefaultXactReadOnly; -extern bool XactReadOnly; +extern bool DefaultXactReadOnly; +extern bool XactReadOnly; /* * transaction states - transaction state from server perspective @@ -44,7 +44,7 @@ typedef enum TransState TRANS_INPROGRESS, TRANS_COMMIT, TRANS_ABORT -} TransState; +} TransState; /* * transaction block states - transaction state of client queries @@ -57,7 +57,7 @@ typedef enum TBlockState TBLOCK_END, TBLOCK_ABORT, TBLOCK_ENDABORT -} TBlockState; +} TBlockState; /* ---------------- * transaction state structure @@ -70,7 +70,7 @@ typedef struct TransactionStateData AbsoluteTime startTime; int startTimeUsec; TransState state; - TBlockState blockState; + TBlockState blockState; } TransactionStateData; typedef TransactionStateData *TransactionState; diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h index cb2e6e523d..074e126abd 100644 --- a/src/include/access/xlog.h +++ b/src/include/access/xlog.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: xlog.h,v 1.42 2003/02/22 00:45:05 tgl Exp $ + * $Id: xlog.h,v 1.43 2003/08/04 00:43:30 momjian Exp $ */ #ifndef XLOG_H #define XLOG_H @@ -58,7 +58,7 @@ typedef struct XLogRecord /* * If we backed up any disk blocks with the XLOG record, we use flag bits in * xl_info to signal it. We support backup of up to 3 disk blocks per XLOG - * record. (Could support 4 if we cared to dedicate all the xl_info bits for + * record. (Could support 4 if we cared to dedicate all the xl_info bits for * this purpose; currently bit 0 of xl_info is unused and available.) */ #define XLR_BKP_BLOCK_MASK 0x0E /* all info bits used for bkp diff --git a/src/include/c.h b/src/include/c.h index 3f6c23c6d1..f49978725d 100644 --- a/src/include/c.h +++ b/src/include/c.h @@ -12,7 +12,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: c.h,v 1.150 2003/06/12 08:15:29 momjian Exp $ + * $Id: c.h,v 1.151 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -68,7 +68,7 @@ #include #include -#include /* ensure O_BINARY is available */ +#include /* ensure O_BINARY is available */ #ifdef HAVE_SUPPORTDEFS_H #include #endif @@ -591,7 +591,7 @@ typedef NameData *Name; * Exactly the same as standard library function memset(), but considerably * faster for zeroing small word-aligned structures (such as parsetree nodes). * This has to be a macro because the main point is to avoid function-call - * overhead. However, we have also found that the loop is faster than + * overhead. However, we have also found that the loop is faster than * native libc memset() on some platforms, even those with assembler * memset() functions. More research needs to be done, perhaps with * platform-specific MEMSET_LOOP_LIMIT values or tests in configure. @@ -707,6 +707,7 @@ typedef NameData *Name; #define FCNTL_NONBLOCK(sock) fcntl(sock, F_SETFL, O_NONBLOCK) #else extern long ioctlsocket_ret; + /* Returns non-0 on failure, while fcntl() returns -1 on failure */ #ifdef WIN32 #define FCNTL_NONBLOCK(sock) ((ioctlsocket(sock, FIONBIO, &ioctlsocket_ret) == 0) ? 0 : -1) @@ -754,7 +755,7 @@ extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args); * because it is used in both the prototypes as well as the definitions. * Note also the long name. We expect that this won't collide with * other names causing compiler warnings. - */ + */ #ifndef SIGNAL_ARGS #define SIGNAL_ARGS int postgres_signal_arg @@ -766,25 +767,25 @@ extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args); * that case. */ #ifndef HAVE_SIGSETJMP -# define sigjmp_buf jmp_buf -# define sigsetjmp(x,y) setjmp(x) -# define siglongjmp longjmp +#define sigjmp_buf jmp_buf +#define sigsetjmp(x,y) setjmp(x) +#define siglongjmp longjmp #endif #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC -extern int fdatasync(int fildes); +extern int fdatasync(int fildes); #endif /* If strtoq() exists, rename it to the more standard strtoll() */ #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ) -# define strtoll strtoq -# define HAVE_STRTOLL 1 +#define strtoll strtoq +#define HAVE_STRTOLL 1 #endif /* If strtouq() exists, rename it to the more standard strtoull() */ #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ) -# define strtoull strtouq -# define HAVE_STRTOULL 1 +#define strtoull strtouq +#define HAVE_STRTOULL 1 #endif /* /port compatibility functions */ diff --git a/src/include/catalog/catversion.h b/src/include/catalog/catversion.h index 21ed3fbf90..c8d9511a79 100644 --- a/src/include/catalog/catversion.h +++ b/src/include/catalog/catversion.h @@ -4,7 +4,7 @@ * "Catalog version number" for PostgreSQL. * * The catalog version number is used to flag incompatible changes in - * the PostgreSQL system catalogs. Whenever anyone changes the format of + * the PostgreSQL system catalogs. Whenever anyone changes the format of * a system catalog relation, or adds, deletes, or modifies standard * catalog entries in such a way that an updated backend wouldn't work * with an old database (or vice versa), the catalog version number @@ -37,7 +37,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: catversion.h,v 1.204 2003/07/30 22:56:24 tgl Exp $ + * $Id: catversion.h,v 1.205 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ diff --git a/src/include/catalog/dependency.h b/src/include/catalog/dependency.h index 512c17a43c..b12ecb4666 100644 --- a/src/include/catalog/dependency.h +++ b/src/include/catalog/dependency.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: dependency.h,v 1.8 2003/05/28 16:03:59 tgl Exp $ + * $Id: dependency.h,v 1.9 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -85,16 +85,16 @@ extern void performDeletion(const ObjectAddress *object, DropBehavior behavior); extern void deleteWhatDependsOn(const ObjectAddress *object, - bool showNotices); + bool showNotices); extern void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior); extern void recordDependencyOnSingleRelExpr(const ObjectAddress *depender, - Node *expr, Oid relId, - DependencyType behavior, - DependencyType self_behavior); + Node *expr, Oid relId, + DependencyType behavior, + DependencyType self_behavior); /* in pg_depend.c */ diff --git a/src/include/catalog/pg_am.h b/src/include/catalog/pg_am.h index 5186d9ef5e..40162386d8 100644 --- a/src/include/catalog/pg_am.h +++ b/src/include/catalog/pg_am.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_am.h,v 1.26 2003/06/22 22:04:55 tgl Exp $ + * $Id: pg_am.h,v 1.27 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -58,7 +58,7 @@ CATALOG(pg_am) regproc amrestrpos; /* "restore marked scan position" function */ regproc ambuild; /* "build new index" function */ regproc ambulkdelete; /* bulk-delete function */ - regproc amvacuumcleanup; /* post-VACUUM cleanup function */ + regproc amvacuumcleanup; /* post-VACUUM cleanup function */ regproc amcostestimate; /* estimate cost of an indexscan */ } FormData_pg_am; diff --git a/src/include/catalog/pg_amproc.h b/src/include/catalog/pg_amproc.h index 79f181cd69..15ec04c553 100644 --- a/src/include/catalog/pg_amproc.h +++ b/src/include/catalog/pg_amproc.h @@ -14,7 +14,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_amproc.h,v 1.41 2003/06/27 00:33:25 tgl Exp $ + * $Id: pg_amproc.h,v 1.42 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -78,7 +78,7 @@ DATA(insert ( 1993 3 199 )); /* btree */ -DATA(insert ( 397 1 382 )); +DATA(insert ( 397 1 382 )); DATA(insert ( 421 1 357 )); DATA(insert ( 423 1 1596 )); DATA(insert ( 424 1 1693 )); @@ -104,7 +104,7 @@ DATA(insert ( 1996 1 1107 )); DATA(insert ( 1998 1 1314 )); DATA(insert ( 2000 1 1358 )); DATA(insert ( 2002 1 1672 )); -DATA(insert ( 2003 1 360 )); +DATA(insert ( 2003 1 360 )); DATA(insert ( 2039 1 2045 )); DATA(insert ( 2095 1 2166 )); DATA(insert ( 2096 1 2166 )); @@ -134,16 +134,16 @@ DATA(insert ( 1999 1 452 )); DATA(insert ( 2001 1 1696 )); DATA(insert ( 2004 1 400 )); DATA(insert ( 2040 1 452 )); -DATA(insert ( 2222 1 454 )); -DATA(insert ( 2223 1 456 )); -DATA(insert ( 2224 1 398 )); -DATA(insert ( 2225 1 450 )); -DATA(insert ( 2226 1 450 )); -DATA(insert ( 2227 1 450 )); -DATA(insert ( 2228 1 450 )); -DATA(insert ( 2229 1 456 )); -DATA(insert ( 2230 1 456 )); -DATA(insert ( 2231 1 456 )); -DATA(insert ( 2232 1 455 )); +DATA(insert ( 2222 1 454 )); +DATA(insert ( 2223 1 456 )); +DATA(insert ( 2224 1 398 )); +DATA(insert ( 2225 1 450 )); +DATA(insert ( 2226 1 450 )); +DATA(insert ( 2227 1 450 )); +DATA(insert ( 2228 1 450 )); +DATA(insert ( 2229 1 456 )); +DATA(insert ( 2230 1 456 )); +DATA(insert ( 2231 1 456 )); +DATA(insert ( 2232 1 455 )); #endif /* PG_AMPROC_H */ diff --git a/src/include/catalog/pg_attribute.h b/src/include/catalog/pg_attribute.h index d20938f54a..77df7446c8 100644 --- a/src/include/catalog/pg_attribute.h +++ b/src/include/catalog/pg_attribute.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_attribute.h,v 1.102 2003/05/08 22:19:56 tgl Exp $ + * $Id: pg_attribute.h,v 1.103 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -238,7 +238,7 @@ typedef FormData_pg_attribute *Form_pg_attribute; { 1247, {"typelem"}, 26, 0, 4, 10, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 }, \ { 1247, {"typinput"}, 24, 0, 4, 11, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 }, \ { 1247, {"typoutput"}, 24, 0, 4, 12, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 }, \ -{ 1247, {"typreceive"}, 24, 0, 4, 13, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 }, \ +{ 1247, {"typreceive"}, 24, 0, 4, 13, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 }, \ { 1247, {"typsend"}, 24, 0, 4, 14, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 }, \ { 1247, {"typalign"}, 18, 0, 1, 15, 0, -1, -1, true, 'p', false, 'c', true, false, false, true, 0 }, \ { 1247, {"typstorage"}, 18, 0, 1, 16, 0, -1, -1, true, 'p', false, 'c', true, false, false, true, 0 }, \ @@ -404,8 +404,8 @@ DATA(insert ( 1261 tableoid 26 0 4 -7 0 -1 -1 t p f i t f f t 0)); { 1249, {"attnotnull"}, 16, 0, 1, 14, 0, -1, -1, true, 'p', false, 'c', true, false, false, true, 0 }, \ { 1249, {"atthasdef"}, 16, 0, 1, 15, 0, -1, -1, true, 'p', false, 'c', true, false, false, true, 0 }, \ { 1249, {"attisdropped"}, 16, 0, 1, 16, 0, -1, -1, true, 'p', false, 'c', true, false, false, true, 0 }, \ -{ 1249, {"attislocal"}, 16, 0, 1, 17, 0, -1, -1, true, 'p', false, 'c', true, false, false, true, 0 }, \ -{ 1249, {"attinhcount"}, 23, 0, 4, 18, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 } +{ 1249, {"attislocal"}, 16, 0, 1, 17, 0, -1, -1, true, 'p', false, 'c', true, false, false, true, 0 }, \ +{ 1249, {"attinhcount"}, 23, 0, 4, 18, 0, -1, -1, true, 'p', false, 'i', true, false, false, true, 0 } DATA(insert ( 1249 attrelid 26 -1 4 1 0 -1 -1 t p f i t f f t 0)); DATA(insert ( 1249 attname 19 -1 NAMEDATALEN 2 0 -1 -1 f p f i t f f t 0)); diff --git a/src/include/catalog/pg_cast.h b/src/include/catalog/pg_cast.h index 6c3d47ba7f..b37eecab75 100644 --- a/src/include/catalog/pg_cast.h +++ b/src/include/catalog/pg_cast.h @@ -7,7 +7,7 @@ * * Copyright (c) 2002, PostgreSQL Global Development Group * - * $Id: pg_cast.h,v 1.7 2003/05/26 00:11:27 tgl Exp $ + * $Id: pg_cast.h,v 1.8 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -39,8 +39,10 @@ typedef FormData_pg_cast *Form_pg_cast; typedef enum CoercionCodes { - COERCION_CODE_IMPLICIT = 'i', /* coercion in context of expression */ - COERCION_CODE_ASSIGNMENT = 'a', /* coercion in context of assignment */ + COERCION_CODE_IMPLICIT = 'i', /* coercion in context of + * expression */ + COERCION_CODE_ASSIGNMENT = 'a', /* coercion in context of + * assignment */ COERCION_CODE_EXPLICIT = 'e' /* explicit cast operation */ } CoercionCodes; @@ -67,7 +69,7 @@ typedef enum CoercionCodes */ DATA(insert ( 20 21 714 a )); DATA(insert ( 20 23 480 a )); -DATA(insert ( 20 700 652 i )); +DATA(insert ( 20 700 652 i )); DATA(insert ( 20 701 482 i )); DATA(insert ( 20 1700 1781 i )); DATA(insert ( 21 20 754 i )); @@ -235,10 +237,10 @@ DATA(insert ( 869 650 0 i )); DATA(insert ( 1560 1562 0 i )); DATA(insert ( 1562 1560 0 i )); /* Cross-category casts between bit and int4, int8 */ -DATA(insert ( 20 1560 2075 e )); -DATA(insert ( 23 1560 1683 e )); -DATA(insert ( 1560 20 2076 e )); -DATA(insert ( 1560 23 1684 e )); +DATA(insert ( 20 1560 2075 e )); +DATA(insert ( 23 1560 1683 e )); +DATA(insert ( 1560 20 2076 e )); +DATA(insert ( 1560 23 1684 e )); /* * Cross-category casts to and from TEXT diff --git a/src/include/catalog/pg_constraint.h b/src/include/catalog/pg_constraint.h index ebbf96f619..80868188a8 100644 --- a/src/include/catalog/pg_constraint.h +++ b/src/include/catalog/pg_constraint.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_constraint.h,v 1.6 2003/03/10 22:28:19 tgl Exp $ + * $Id: pg_constraint.h,v 1.7 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -141,14 +141,15 @@ typedef FormData_pg_constraint *Form_pg_constraint; */ /* - * Used for constraint support functions where the + * Used for constraint support functions where the * and conrelid, contypid columns being looked up */ -typedef enum CONSTRAINTCATEGORY { +typedef enum CONSTRAINTCATEGORY +{ CONSTRAINT_RELATION, CONSTRAINT_DOMAIN, CONSTRAINT_ASSERTION -} CONSTRAINTCATEGORY; +} CONSTRAINTCATEGORY; /* * prototypes for functions in pg_constraint.c @@ -176,9 +177,9 @@ extern Oid CreateConstraintEntry(const char *constraintName, extern void RemoveConstraintById(Oid conId); extern bool ConstraintNameIsUsed(CONSTRAINTCATEGORY conCat, Oid objId, Oid objNamespace, - const char *cname); + const char *cname); extern char *GenerateConstraintName(CONSTRAINTCATEGORY conCat, Oid objId, Oid objNamespace, - int *counter); + int *counter); extern bool ConstraintNameIsGenerated(const char *cname); #endif /* PG_CONSTRAINT_H */ diff --git a/src/include/catalog/pg_opclass.h b/src/include/catalog/pg_opclass.h index 5d635523ca..4c1b78ac3f 100644 --- a/src/include/catalog/pg_opclass.h +++ b/src/include/catalog/pg_opclass.h @@ -26,7 +26,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_opclass.h,v 1.54 2003/06/27 00:33:25 tgl Exp $ + * $Id: pg_opclass.h,v 1.55 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -151,7 +151,7 @@ DATA(insert OID = 2039 ( 403 timestamp_ops PGNSP PGUID 1114 t 0 )); DATA(insert OID = 2040 ( 405 timestamp_ops PGNSP PGUID 1114 t 0 )); DATA(insert OID = 2095 ( 403 text_pattern_ops PGNSP PGUID 25 f 0 )); #define TEXT_PATTERN_BTREE_OPS_OID 2095 -DATA(insert OID = 2096 ( 403 varchar_pattern_ops PGNSP PGUID 1043 f 0 )); +DATA(insert OID = 2096 ( 403 varchar_pattern_ops PGNSP PGUID 1043 f 0 )); #define VARCHAR_PATTERN_BTREE_OPS_OID 2096 DATA(insert OID = 2097 ( 403 bpchar_pattern_ops PGNSP PGUID 1042 f 0 )); #define BPCHAR_PATTERN_BTREE_OPS_OID 2097 @@ -165,7 +165,7 @@ DATA(insert OID = 2226 ( 405 cid_ops PGNSP PGUID 29 t 0 )); DATA(insert OID = 2227 ( 405 abstime_ops PGNSP PGUID 702 t 0 )); DATA(insert OID = 2228 ( 405 reltime_ops PGNSP PGUID 703 t 0 )); DATA(insert OID = 2229 ( 405 text_pattern_ops PGNSP PGUID 25 f 0 )); -DATA(insert OID = 2230 ( 405 varchar_pattern_ops PGNSP PGUID 1043 f 0 )); +DATA(insert OID = 2230 ( 405 varchar_pattern_ops PGNSP PGUID 1043 f 0 )); DATA(insert OID = 2231 ( 405 bpchar_pattern_ops PGNSP PGUID 1042 f 0 )); DATA(insert OID = 2232 ( 405 name_pattern_ops PGNSP PGUID 19 f 0 )); diff --git a/src/include/catalog/pg_operator.h b/src/include/catalog/pg_operator.h index a964ac1b3d..85cce6db39 100644 --- a/src/include/catalog/pg_operator.h +++ b/src/include/catalog/pg_operator.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_operator.h,v 1.118 2003/06/27 00:33:25 tgl Exp $ + * $Id: pg_operator.h,v 1.119 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -116,9 +116,9 @@ DATA(insert OID = 96 ( "=" PGNSP PGUID b t 23 23 16 96 518 97 97 97 521 int DATA(insert OID = 97 ( "<" PGNSP PGUID b f 23 23 16 521 525 0 0 0 0 int4lt scalarltsel scalarltjoinsel )); DATA(insert OID = 98 ( "=" PGNSP PGUID b t 25 25 16 98 531 664 664 664 666 texteq eqsel eqjoinsel )); -DATA(insert OID = 349 ( "||" PGNSP PGUID b f 2277 2283 2277 0 0 0 0 0 0 array_append - - )); -DATA(insert OID = 374 ( "||" PGNSP PGUID b f 2283 2277 2277 0 0 0 0 0 0 array_prepend - - )); -DATA(insert OID = 375 ( "||" PGNSP PGUID b f 2277 2277 2277 0 0 0 0 0 0 array_cat - - )); +DATA(insert OID = 349 ( "||" PGNSP PGUID b f 2277 2283 2277 0 0 0 0 0 0 array_append - - )); +DATA(insert OID = 374 ( "||" PGNSP PGUID b f 2283 2277 2277 0 0 0 0 0 0 array_prepend - - )); +DATA(insert OID = 375 ( "||" PGNSP PGUID b f 2277 2277 2277 0 0 0 0 0 0 array_cat - - )); DATA(insert OID = 352 ( "=" PGNSP PGUID b t 28 28 16 352 0 0 0 0 0 xideq eqsel eqjoinsel )); DATA(insert OID = 353 ( "=" PGNSP PGUID b f 28 23 16 0 0 0 0 0 0 xideqint4 eqsel eqjoinsel )); @@ -351,7 +351,7 @@ DATA(insert OID = 708 ( "<->" PGNSP PGUID b f 628 628 701 708 0 0 0 0 DATA(insert OID = 709 ( "<->" PGNSP PGUID b f 601 601 701 709 0 0 0 0 0 lseg_distance - - )); DATA(insert OID = 712 ( "<->" PGNSP PGUID b f 604 604 701 712 0 0 0 0 0 poly_distance - - )); -DATA(insert OID = 713 ( "<>" PGNSP PGUID b f 600 600 16 713 510 0 0 0 0 point_ne neqsel neqjoinsel )); +DATA(insert OID = 713 ( "<>" PGNSP PGUID b f 600 600 16 713 510 0 0 0 0 point_ne neqsel neqjoinsel )); /* add translation/rotation/scaling operators for geometric types. - thomas 97/05/10 */ DATA(insert OID = 731 ( "+" PGNSP PGUID b f 600 600 600 731 0 0 0 0 0 point_add - - )); @@ -443,10 +443,10 @@ DATA(insert OID = 1061 ( ">=" PGNSP PGUID b f 1042 1042 16 1059 1058 0 0 0 /* generic array comparison operators */ DATA(insert OID = 1070 ( "=" PGNSP PGUID b f 2277 2277 16 1070 1071 1072 1072 1072 1073 array_eq eqsel eqjoinsel )); -#define ARRAY_EQ_OP 1070 +#define ARRAY_EQ_OP 1070 DATA(insert OID = 1071 ( "<>" PGNSP PGUID b f 2277 2277 16 1071 1070 0 0 0 0 array_ne neqsel neqjoinsel )); DATA(insert OID = 1072 ( "<" PGNSP PGUID b f 2277 2277 16 1073 1075 0 0 0 0 array_lt scalarltsel scalarltjoinsel )); -#define ARRAY_LT_OP 1072 +#define ARRAY_LT_OP 1072 DATA(insert OID = 1073 ( ">" PGNSP PGUID b f 2277 2277 16 1072 1074 0 0 0 0 array_gt scalargtsel scalargtjoinsel )); DATA(insert OID = 1074 ( "<=" PGNSP PGUID b f 2277 2277 16 1075 1073 0 0 0 0 array_le scalarltsel scalarltjoinsel )); DATA(insert OID = 1075 ( ">=" PGNSP PGUID b f 2277 2277 16 1074 1072 0 0 0 0 array_ge scalargtsel scalargtjoinsel )); @@ -801,25 +801,25 @@ DATA(insert OID = 2068 ( "-" PGNSP PGUID b f 1114 1186 1114 0 0 0 0 0 0 tim /* character-by-character (not collation order) comparison operators for character types */ DATA(insert OID = 2314 ( "~<~" PGNSP PGUID b f 25 25 16 2318 2317 0 0 0 0 text_pattern_lt scalarltsel scalarltjoinsel )); -DATA(insert OID = 2315 ( "~<=~" PGNSP PGUID b f 25 25 16 2317 2318 0 0 0 0 text_pattern_le scalarltsel scalarltjoinsel )); +DATA(insert OID = 2315 ( "~<=~" PGNSP PGUID b f 25 25 16 2317 2318 0 0 0 0 text_pattern_le scalarltsel scalarltjoinsel )); DATA(insert OID = 2316 ( "~=~" PGNSP PGUID b t 25 25 16 2316 2319 2314 2314 2314 2318 text_pattern_eq eqsel eqjoinsel )); -DATA(insert OID = 2317 ( "~>=~" PGNSP PGUID b f 25 25 16 2315 2314 0 0 0 0 text_pattern_ge scalargtsel scalargtjoinsel )); +DATA(insert OID = 2317 ( "~>=~" PGNSP PGUID b f 25 25 16 2315 2314 0 0 0 0 text_pattern_ge scalargtsel scalargtjoinsel )); DATA(insert OID = 2318 ( "~>~" PGNSP PGUID b f 25 25 16 2314 2315 0 0 0 0 text_pattern_gt scalargtsel scalargtjoinsel )); -DATA(insert OID = 2319 ( "~<>~" PGNSP PGUID b f 25 25 16 2319 2316 0 0 0 0 text_pattern_ne neqsel neqjoinsel )); +DATA(insert OID = 2319 ( "~<>~" PGNSP PGUID b f 25 25 16 2319 2316 0 0 0 0 text_pattern_ne neqsel neqjoinsel )); DATA(insert OID = 2326 ( "~<~" PGNSP PGUID b f 1042 1042 16 2330 2329 0 0 0 0 bpchar_pattern_lt scalarltsel scalarltjoinsel )); -DATA(insert OID = 2327 ( "~<=~" PGNSP PGUID b f 1042 1042 16 2329 2330 0 0 0 0 bpchar_pattern_le scalarltsel scalarltjoinsel )); +DATA(insert OID = 2327 ( "~<=~" PGNSP PGUID b f 1042 1042 16 2329 2330 0 0 0 0 bpchar_pattern_le scalarltsel scalarltjoinsel )); DATA(insert OID = 2328 ( "~=~" PGNSP PGUID b t 1042 1042 16 2328 2331 2326 2326 2326 2330 bpchar_pattern_eq eqsel eqjoinsel )); -DATA(insert OID = 2329 ( "~>=~" PGNSP PGUID b f 1042 1042 16 2327 2326 0 0 0 0 bpchar_pattern_ge scalargtsel scalargtjoinsel )); +DATA(insert OID = 2329 ( "~>=~" PGNSP PGUID b f 1042 1042 16 2327 2326 0 0 0 0 bpchar_pattern_ge scalargtsel scalargtjoinsel )); DATA(insert OID = 2330 ( "~>~" PGNSP PGUID b f 1042 1042 16 2326 2327 0 0 0 0 bpchar_pattern_gt scalargtsel scalargtjoinsel )); -DATA(insert OID = 2331 ( "~<>~" PGNSP PGUID b f 1042 1042 16 2331 2328 0 0 0 0 bpchar_pattern_ne neqsel neqjoinsel )); +DATA(insert OID = 2331 ( "~<>~" PGNSP PGUID b f 1042 1042 16 2331 2328 0 0 0 0 bpchar_pattern_ne neqsel neqjoinsel )); DATA(insert OID = 2332 ( "~<~" PGNSP PGUID b f 19 19 16 2336 2335 0 0 0 0 name_pattern_lt scalarltsel scalarltjoinsel )); -DATA(insert OID = 2333 ( "~<=~" PGNSP PGUID b f 19 19 16 2335 2336 0 0 0 0 name_pattern_le scalarltsel scalarltjoinsel )); +DATA(insert OID = 2333 ( "~<=~" PGNSP PGUID b f 19 19 16 2335 2336 0 0 0 0 name_pattern_le scalarltsel scalarltjoinsel )); DATA(insert OID = 2334 ( "~=~" PGNSP PGUID b t 19 19 16 2334 2337 2332 2332 2332 2336 name_pattern_eq eqsel eqjoinsel )); -DATA(insert OID = 2335 ( "~>=~" PGNSP PGUID b f 19 19 16 2333 2332 0 0 0 0 name_pattern_ge scalargtsel scalargtjoinsel )); +DATA(insert OID = 2335 ( "~>=~" PGNSP PGUID b f 19 19 16 2333 2332 0 0 0 0 name_pattern_ge scalargtsel scalargtjoinsel )); DATA(insert OID = 2336 ( "~>~" PGNSP PGUID b f 19 19 16 2332 2333 0 0 0 0 name_pattern_gt scalargtsel scalargtjoinsel )); -DATA(insert OID = 2337 ( "~<>~" PGNSP PGUID b f 19 19 16 2337 2334 0 0 0 0 name_pattern_ne neqsel neqjoinsel )); +DATA(insert OID = 2337 ( "~<>~" PGNSP PGUID b f 19 19 16 2337 2334 0 0 0 0 name_pattern_ne neqsel neqjoinsel )); diff --git a/src/include/catalog/pg_proc.h b/src/include/catalog/pg_proc.h index e41817a0e3..b81ad142e8 100644 --- a/src/include/catalog/pg_proc.h +++ b/src/include/catalog/pg_proc.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_proc.h,v 1.310 2003/07/30 22:56:24 tgl Exp $ + * $Id: pg_proc.h,v 1.311 2003/08/04 00:43:30 momjian Exp $ * * NOTES * The script catalog/genbki.sh reads this file and generates .bki @@ -844,7 +844,7 @@ DATA(insert OID = 456 ( hashvarlena PGNSP PGUID 12 f f t f i 1 23 "2281" has DESCR("hash any varlena type"); DATA(insert OID = 457 ( hashoidvector PGNSP PGUID 12 f f t f i 1 23 "30" hashoidvector - _null_ )); DESCR("hash"); -DATA(insert OID = 398 ( hashint2vector PGNSP PGUID 12 f f t f i 1 23 "22" hashint2vector - _null_ )); +DATA(insert OID = 398 ( hashint2vector PGNSP PGUID 12 f f t f i 1 23 "22" hashint2vector - _null_ )); DESCR("hash"); DATA(insert OID = 399 ( hashmacaddr PGNSP PGUID 12 f f t f i 1 23 "829" hashmacaddr - _null_ )); DESCR("hash"); @@ -931,9 +931,9 @@ DESCR("greater-than-or-equal"); DATA(insert OID = 659 ( namene PGNSP PGUID 12 f f t f i 2 16 "19 19" namene - _null_ )); DESCR("not equal"); -DATA(insert OID = 668 ( bpchar PGNSP PGUID 12 f f t f i 3 1042 "1042 23 16" bpchar - _null_ )); +DATA(insert OID = 668 ( bpchar PGNSP PGUID 12 f f t f i 3 1042 "1042 23 16" bpchar - _null_ )); DESCR("adjust char() to typmod length"); -DATA(insert OID = 669 ( varchar PGNSP PGUID 12 f f t f i 3 1043 "1043 23 16" varchar - _null_ )); +DATA(insert OID = 669 ( varchar PGNSP PGUID 12 f f t f i 3 1043 "1043 23 16" varchar - _null_ )); DESCR("adjust varchar() to typmod length"); DATA(insert OID = 676 ( mktinterval PGNSP PGUID 12 f f t f i 2 704 "702 702" mktinterval - _null_ )); @@ -1021,7 +1021,7 @@ DATA(insert OID = 378 ( array_append PGNSP PGUID 12 f f t f i 2 2277 "2277 2 DESCR("append element onto end of array"); DATA(insert OID = 379 ( array_prepend PGNSP PGUID 12 f f t f i 2 2277 "2283 2277" array_push - _null_ )); DESCR("prepend element onto front of array"); -DATA(insert OID = 383 ( array_cat PGNSP PGUID 12 f f t f i 2 2277 "2277 2277" array_cat - _null_ )); +DATA(insert OID = 383 ( array_cat PGNSP PGUID 12 f f t f i 2 2277 "2277 2277" array_cat - _null_ )); DESCR("concatenate two arrays"); DATA(insert OID = 384 ( array_coerce PGNSP PGUID 12 f f t f i 1 2277 "2277" array_type_coerce - _null_ )); DESCR("coerce array type to another array type"); @@ -1329,9 +1329,9 @@ DATA(insert OID = 1036 ( aclremove PGNSP PGUID 12 f f t f s 2 1034 "1034 10 DESCR("remove ACL item"); DATA(insert OID = 1037 ( aclcontains PGNSP PGUID 12 f f t f s 2 16 "1034 1033" aclcontains - _null_ )); DESCR("does ACL contain item?"); -DATA(insert OID = 1062 ( aclitemeq PGNSP PGUID 12 f f t f s 2 16 "1033 1033" aclitem_eq - _null_ )); +DATA(insert OID = 1062 ( aclitemeq PGNSP PGUID 12 f f t f s 2 16 "1033 1033" aclitem_eq - _null_ )); DESCR("equality operator for ACL items"); -DATA(insert OID = 1365 ( makeaclitem PGNSP PGUID 12 f f t f s 5 1033 "23 23 23 25 16" makeaclitem - _null_ )); +DATA(insert OID = 1365 ( makeaclitem PGNSP PGUID 12 f f t f s 5 1033 "23 23 23 25 16" makeaclitem - _null_ )); DESCR("make ACL item"); DATA(insert OID = 1038 ( seteval PGNSP PGUID 12 f f t t v 1 23 "26" seteval - _null_ )); DESCR("internal function supporting PostQuel-style sets"); @@ -1404,7 +1404,7 @@ DATA(insert OID = 1141 ( date_pli PGNSP PGUID 12 f f t f i 2 1082 "1082 23" DESCR("add"); DATA(insert OID = 1142 ( date_mii PGNSP PGUID 12 f f t f i 2 1082 "1082 23" date_mii - _null_ )); DESCR("subtract"); -DATA(insert OID = 1143 ( time_in PGNSP PGUID 12 f f t f s 3 1083 "2275 26 23" time_in - _null_ )); +DATA(insert OID = 1143 ( time_in PGNSP PGUID 12 f f t f s 3 1083 "2275 26 23" time_in - _null_ )); DESCR("I/O"); DATA(insert OID = 1144 ( time_out PGNSP PGUID 12 f f t f i 1 2275 "1083" time_out - _null_ )); DESCR("I/O"); @@ -1420,7 +1420,7 @@ DESCR("multiply"); DATA(insert OID = 1149 ( circle_div_pt PGNSP PGUID 12 f f t f i 2 718 "718 600" circle_div_pt - _null_ )); DESCR("divide"); -DATA(insert OID = 1150 ( timestamptz_in PGNSP PGUID 12 f f t f s 3 1184 "2275 26 23" timestamptz_in - _null_ )); +DATA(insert OID = 1150 ( timestamptz_in PGNSP PGUID 12 f f t f s 3 1184 "2275 26 23" timestamptz_in - _null_ )); DESCR("I/O"); DATA(insert OID = 1151 ( timestamptz_out PGNSP PGUID 12 f f t f s 1 2275 "1184" timestamptz_out - _null_ )); DESCR("I/O"); @@ -1439,7 +1439,7 @@ DESCR("greater-than"); DATA(insert OID = 1159 ( timezone PGNSP PGUID 12 f f t f s 2 1114 "25 1184" timestamptz_zone - _null_ )); DESCR("adjust timestamp to new time zone"); -DATA(insert OID = 1160 ( interval_in PGNSP PGUID 12 f f t f s 3 1186 "2275 26 23" interval_in - _null_ )); +DATA(insert OID = 1160 ( interval_in PGNSP PGUID 12 f f t f s 3 1186 "2275 26 23" interval_in - _null_ )); DESCR("I/O"); DATA(insert OID = 1161 ( interval_out PGNSP PGUID 12 f f t f i 1 2275 "1186" interval_out - _null_ )); DESCR("I/O"); @@ -1681,7 +1681,7 @@ DATA(insert OID = 1349 ( oidvectortypes PGNSP PGUID 12 f f t f s 1 25 "30" oi DESCR("print type names of oidvector field"); -DATA(insert OID = 1350 ( timetz_in PGNSP PGUID 12 f f t f s 3 1266 "2275 26 23" timetz_in - _null_ )); +DATA(insert OID = 1350 ( timetz_in PGNSP PGUID 12 f f t f s 3 1266 "2275 26 23" timetz_in - _null_ )); DESCR("I/O"); DATA(insert OID = 1351 ( timetz_out PGNSP PGUID 12 f f t f i 1 2275 "1266" timetz_out - _null_ )); DESCR("I/O"); @@ -2120,13 +2120,13 @@ DESCR("does not match LIKE expression, case-insensitive"); DATA(insert OID = 1637 ( like_escape PGNSP PGUID 12 f f t f i 2 25 "25 25" like_escape - _null_ )); DESCR("convert LIKE pattern to use backslash escapes"); -DATA(insert OID = 1656 ( bpcharicregexeq PGNSP PGUID 12 f f t f i 2 16 "1042 25" texticregexeq - _null_ )); +DATA(insert OID = 1656 ( bpcharicregexeq PGNSP PGUID 12 f f t f i 2 16 "1042 25" texticregexeq - _null_ )); DESCR("matches regex., case-insensitive"); -DATA(insert OID = 1657 ( bpcharicregexne PGNSP PGUID 12 f f t f i 2 16 "1042 25" texticregexne - _null_ )); +DATA(insert OID = 1657 ( bpcharicregexne PGNSP PGUID 12 f f t f i 2 16 "1042 25" texticregexne - _null_ )); DESCR("does not match regex., case-insensitive"); -DATA(insert OID = 1658 ( bpcharregexeq PGNSP PGUID 12 f f t f i 2 16 "1042 25" textregexeq - _null_ )); +DATA(insert OID = 1658 ( bpcharregexeq PGNSP PGUID 12 f f t f i 2 16 "1042 25" textregexeq - _null_ )); DESCR("matches regex., case-sensitive"); -DATA(insert OID = 1659 ( bpcharregexne PGNSP PGUID 12 f f t f i 2 16 "1042 25" textregexne - _null_ )); +DATA(insert OID = 1659 ( bpcharregexne PGNSP PGUID 12 f f t f i 2 16 "1042 25" textregexne - _null_ )); DESCR("does not match regex., case-sensitive"); DATA(insert OID = 1660 ( bpchariclike PGNSP PGUID 12 f f t f i 2 16 "1042 25" texticlike - _null_ )); DESCR("matches LIKE expression, case-insensitive"); @@ -2201,7 +2201,7 @@ DESCR("convert string with specified destination encoding name"); DATA(insert OID = 1813 ( convert PGNSP PGUID 12 f f t f s 3 25 "25 19 19" pg_convert2 - _null_ )); DESCR("convert string with specified encoding names"); -DATA(insert OID = 1619 ( convert_using PGNSP PGUID 12 f f t f s 2 25 "25 25" pg_convert_using - _null_ )); +DATA(insert OID = 1619 ( convert_using PGNSP PGUID 12 f f t f s 2 25 "25 25" pg_convert_using - _null_ )); DESCR("convert string with specified conversion name"); DATA(insert OID = 1264 ( pg_char_to_encoding PGNSP PGUID 12 f f t f s 1 23 "19" PG_char_to_encoding - _null_ )); @@ -2226,7 +2226,7 @@ DATA(insert OID = 1642 ( pg_get_userbyid PGNSP PGUID 12 f f t f s 1 19 "23" DESCR("user name by UID (with fallback)"); DATA(insert OID = 1643 ( pg_get_indexdef PGNSP PGUID 12 f f t f s 1 25 "26" pg_get_indexdef - _null_ )); DESCR("index description"); -DATA(insert OID = 1662 ( pg_get_triggerdef PGNSP PGUID 12 f f t f s 1 25 "26" pg_get_triggerdef - _null_ )); +DATA(insert OID = 1662 ( pg_get_triggerdef PGNSP PGUID 12 f f t f s 1 25 "26" pg_get_triggerdef - _null_ )); DESCR("trigger description"); DATA(insert OID = 1387 ( pg_get_constraintdef PGNSP PGUID 12 f f t f s 1 25 "26" pg_get_constraintdef - _null_ )); DESCR("constraint description"); @@ -2300,9 +2300,9 @@ DESCR("int4 to bitstring"); DATA(insert OID = 1684 ( int4 PGNSP PGUID 12 f f t f i 1 23 "1560" bittoint4 - _null_ )); DESCR("bitstring to int4"); -DATA(insert OID = 1685 ( bit PGNSP PGUID 12 f f t f i 3 1560 "1560 23 16" bit - _null_ )); +DATA(insert OID = 1685 ( bit PGNSP PGUID 12 f f t f i 3 1560 "1560 23 16" bit - _null_ )); DESCR("adjust bit() to typmod length"); -DATA(insert OID = 1687 ( varbit PGNSP PGUID 12 f f t f i 3 1562 "1562 23 16" varbit - _null_ )); +DATA(insert OID = 1687 ( varbit PGNSP PGUID 12 f f t f i 3 1562 "1562 23 16" varbit - _null_ )); DESCR("adjust varbit() to typmod length"); DATA(insert OID = 1698 ( position PGNSP PGUID 12 f f t f i 2 23 "1560 1560" bitposition - _null_ )); @@ -3042,29 +3042,29 @@ DATA(insert OID = 2157 ( stddev PGNSP PGUID 12 t f f f i 1 701 "700" aggrega DATA(insert OID = 2158 ( stddev PGNSP PGUID 12 t f f f i 1 701 "701" aggregate_dummy - _null_ )); DATA(insert OID = 2159 ( stddev PGNSP PGUID 12 t f f f i 1 1700 "1700" aggregate_dummy - _null_ )); -DATA(insert OID = 2160 ( text_pattern_lt PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_lt - _null_ )); -DATA(insert OID = 2161 ( text_pattern_le PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_le - _null_ )); -DATA(insert OID = 2162 ( text_pattern_eq PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_eq - _null_ )); -DATA(insert OID = 2163 ( text_pattern_ge PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_ge - _null_ )); -DATA(insert OID = 2164 ( text_pattern_gt PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_gt - _null_ )); -DATA(insert OID = 2165 ( text_pattern_ne PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_ne - _null_ )); +DATA(insert OID = 2160 ( text_pattern_lt PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_lt - _null_ )); +DATA(insert OID = 2161 ( text_pattern_le PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_le - _null_ )); +DATA(insert OID = 2162 ( text_pattern_eq PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_eq - _null_ )); +DATA(insert OID = 2163 ( text_pattern_ge PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_ge - _null_ )); +DATA(insert OID = 2164 ( text_pattern_gt PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_gt - _null_ )); +DATA(insert OID = 2165 ( text_pattern_ne PGNSP PGUID 12 f f t f i 2 16 "25 25" text_pattern_ne - _null_ )); DATA(insert OID = 2166 ( bttext_pattern_cmp PGNSP PGUID 12 f f t f i 2 23 "25 25" bttext_pattern_cmp - _null_ )); /* We use the same procedures here as above since the types are binary compatible. */ -DATA(insert OID = 2174 ( bpchar_pattern_lt PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_lt - _null_ )); -DATA(insert OID = 2175 ( bpchar_pattern_le PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_le - _null_ )); -DATA(insert OID = 2176 ( bpchar_pattern_eq PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_eq - _null_ )); -DATA(insert OID = 2177 ( bpchar_pattern_ge PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_ge - _null_ )); -DATA(insert OID = 2178 ( bpchar_pattern_gt PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_gt - _null_ )); -DATA(insert OID = 2179 ( bpchar_pattern_ne PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_ne - _null_ )); +DATA(insert OID = 2174 ( bpchar_pattern_lt PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_lt - _null_ )); +DATA(insert OID = 2175 ( bpchar_pattern_le PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_le - _null_ )); +DATA(insert OID = 2176 ( bpchar_pattern_eq PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_eq - _null_ )); +DATA(insert OID = 2177 ( bpchar_pattern_ge PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_ge - _null_ )); +DATA(insert OID = 2178 ( bpchar_pattern_gt PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_gt - _null_ )); +DATA(insert OID = 2179 ( bpchar_pattern_ne PGNSP PGUID 12 f f t f i 2 16 "1042 1042" text_pattern_ne - _null_ )); DATA(insert OID = 2180 ( btbpchar_pattern_cmp PGNSP PGUID 12 f f t f i 2 23 "1042 1042" bttext_pattern_cmp - _null_ )); -DATA(insert OID = 2181 ( name_pattern_lt PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_lt - _null_ )); -DATA(insert OID = 2182 ( name_pattern_le PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_le - _null_ )); -DATA(insert OID = 2183 ( name_pattern_eq PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_eq - _null_ )); -DATA(insert OID = 2184 ( name_pattern_ge PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_ge - _null_ )); -DATA(insert OID = 2185 ( name_pattern_gt PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_gt - _null_ )); -DATA(insert OID = 2186 ( name_pattern_ne PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_ne - _null_ )); +DATA(insert OID = 2181 ( name_pattern_lt PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_lt - _null_ )); +DATA(insert OID = 2182 ( name_pattern_le PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_le - _null_ )); +DATA(insert OID = 2183 ( name_pattern_eq PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_eq - _null_ )); +DATA(insert OID = 2184 ( name_pattern_ge PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_ge - _null_ )); +DATA(insert OID = 2185 ( name_pattern_gt PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_gt - _null_ )); +DATA(insert OID = 2186 ( name_pattern_ne PGNSP PGUID 12 f f t f i 2 16 "19 19" name_pattern_ne - _null_ )); DATA(insert OID = 2187 ( btname_pattern_cmp PGNSP PGUID 12 f f t f i 2 23 "19 19" btname_pattern_cmp - _null_ )); @@ -3198,7 +3198,7 @@ DESCR("calculates md5 hash"); DATA(insert OID = 2400 ( array_recv PGNSP PGUID 12 f f t f s 2 2277 "2281 26" array_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2401 ( array_send PGNSP PGUID 12 f f t f s 2 17 "2277 26" array_send - _null_ )); +DATA(insert OID = 2401 ( array_send PGNSP PGUID 12 f f t f s 2 17 "2277 26" array_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2402 ( record_recv PGNSP PGUID 12 f f t f i 1 2249 "2281" record_recv - _null_ )); DESCR("I/O"); @@ -3230,7 +3230,7 @@ DATA(insert OID = 2415 ( textsend PGNSP PGUID 12 f f t f s 1 17 "25" text DESCR("I/O"); DATA(insert OID = 2416 ( unknownrecv PGNSP PGUID 12 f f t f i 1 705 "2281" unknownrecv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2417 ( unknownsend PGNSP PGUID 12 f f t f i 1 17 "705" unknownsend - _null_ )); +DATA(insert OID = 2417 ( unknownsend PGNSP PGUID 12 f f t f i 1 17 "705" unknownsend - _null_ )); DESCR("I/O"); DATA(insert OID = 2418 ( oidrecv PGNSP PGUID 12 f f t f i 1 26 "2281" oidrecv - _null_ )); DESCR("I/O"); @@ -3246,15 +3246,15 @@ DATA(insert OID = 2423 ( namesend PGNSP PGUID 12 f f t f s 1 17 "19" name DESCR("I/O"); DATA(insert OID = 2424 ( float4recv PGNSP PGUID 12 f f t f i 1 700 "2281" float4recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2425 ( float4send PGNSP PGUID 12 f f t f i 1 17 "700" float4send - _null_ )); +DATA(insert OID = 2425 ( float4send PGNSP PGUID 12 f f t f i 1 17 "700" float4send - _null_ )); DESCR("I/O"); DATA(insert OID = 2426 ( float8recv PGNSP PGUID 12 f f t f i 1 701 "2281" float8recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2427 ( float8send PGNSP PGUID 12 f f t f i 1 17 "701" float8send - _null_ )); +DATA(insert OID = 2427 ( float8send PGNSP PGUID 12 f f t f i 1 17 "701" float8send - _null_ )); DESCR("I/O"); DATA(insert OID = 2428 ( point_recv PGNSP PGUID 12 f f t f i 1 600 "2281" point_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2429 ( point_send PGNSP PGUID 12 f f t f i 1 17 "600" point_send - _null_ )); +DATA(insert OID = 2429 ( point_send PGNSP PGUID 12 f f t f i 1 17 "600" point_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2430 ( bpcharrecv PGNSP PGUID 12 f f t f s 1 1042 "2281" bpcharrecv - _null_ )); DESCR("I/O"); @@ -3322,15 +3322,15 @@ DATA(insert OID = 2461 ( numeric_send PGNSP PGUID 12 f f t f i 1 17 "1700" DESCR("I/O"); DATA(insert OID = 2462 ( abstimerecv PGNSP PGUID 12 f f t f i 1 702 "2281" abstimerecv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2463 ( abstimesend PGNSP PGUID 12 f f t f i 1 17 "702" abstimesend - _null_ )); +DATA(insert OID = 2463 ( abstimesend PGNSP PGUID 12 f f t f i 1 17 "702" abstimesend - _null_ )); DESCR("I/O"); DATA(insert OID = 2464 ( reltimerecv PGNSP PGUID 12 f f t f i 1 703 "2281" reltimerecv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2465 ( reltimesend PGNSP PGUID 12 f f t f i 1 17 "703" reltimesend - _null_ )); +DATA(insert OID = 2465 ( reltimesend PGNSP PGUID 12 f f t f i 1 17 "703" reltimesend - _null_ )); DESCR("I/O"); DATA(insert OID = 2466 ( tintervalrecv PGNSP PGUID 12 f f t f i 1 704 "2281" tintervalrecv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2467 ( tintervalsend PGNSP PGUID 12 f f t f i 1 17 "704" tintervalsend - _null_ )); +DATA(insert OID = 2467 ( tintervalsend PGNSP PGUID 12 f f t f i 1 17 "704" tintervalsend - _null_ )); DESCR("I/O"); DATA(insert OID = 2468 ( date_recv PGNSP PGUID 12 f f t f i 1 1082 "2281" date_recv - _null_ )); DESCR("I/O"); @@ -3358,43 +3358,43 @@ DATA(insert OID = 2479 ( interval_send PGNSP PGUID 12 f f t f i 1 17 "1186" DESCR("I/O"); DATA(insert OID = 2480 ( lseg_recv PGNSP PGUID 12 f f t f i 1 601 "2281" lseg_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2481 ( lseg_send PGNSP PGUID 12 f f t f i 1 17 "601" lseg_send - _null_ )); +DATA(insert OID = 2481 ( lseg_send PGNSP PGUID 12 f f t f i 1 17 "601" lseg_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2482 ( path_recv PGNSP PGUID 12 f f t f i 1 602 "2281" path_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2483 ( path_send PGNSP PGUID 12 f f t f i 1 17 "602" path_send - _null_ )); +DATA(insert OID = 2483 ( path_send PGNSP PGUID 12 f f t f i 1 17 "602" path_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2484 ( box_recv PGNSP PGUID 12 f f t f i 1 603 "2281" box_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2485 ( box_send PGNSP PGUID 12 f f t f i 1 17 "603" box_send - _null_ )); +DATA(insert OID = 2485 ( box_send PGNSP PGUID 12 f f t f i 1 17 "603" box_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2486 ( poly_recv PGNSP PGUID 12 f f t f i 1 604 "2281" poly_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2487 ( poly_send PGNSP PGUID 12 f f t f i 1 17 "604" poly_send - _null_ )); +DATA(insert OID = 2487 ( poly_send PGNSP PGUID 12 f f t f i 1 17 "604" poly_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2488 ( line_recv PGNSP PGUID 12 f f t f i 1 628 "2281" line_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2489 ( line_send PGNSP PGUID 12 f f t f i 1 17 "628" line_send - _null_ )); +DATA(insert OID = 2489 ( line_send PGNSP PGUID 12 f f t f i 1 17 "628" line_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2490 ( circle_recv PGNSP PGUID 12 f f t f i 1 718 "2281" circle_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2491 ( circle_send PGNSP PGUID 12 f f t f i 1 17 "718" circle_send - _null_ )); +DATA(insert OID = 2491 ( circle_send PGNSP PGUID 12 f f t f i 1 17 "718" circle_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2492 ( cash_recv PGNSP PGUID 12 f f t f i 1 790 "2281" cash_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2493 ( cash_send PGNSP PGUID 12 f f t f i 1 17 "790" cash_send - _null_ )); +DATA(insert OID = 2493 ( cash_send PGNSP PGUID 12 f f t f i 1 17 "790" cash_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2494 ( macaddr_recv PGNSP PGUID 12 f f t f i 1 829 "2281" macaddr_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2495 ( macaddr_send PGNSP PGUID 12 f f t f i 1 17 "829" macaddr_send - _null_ )); +DATA(insert OID = 2495 ( macaddr_send PGNSP PGUID 12 f f t f i 1 17 "829" macaddr_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2496 ( inet_recv PGNSP PGUID 12 f f t f i 1 869 "2281" inet_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2497 ( inet_send PGNSP PGUID 12 f f t f i 1 17 "869" inet_send - _null_ )); +DATA(insert OID = 2497 ( inet_send PGNSP PGUID 12 f f t f i 1 17 "869" inet_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2498 ( cidr_recv PGNSP PGUID 12 f f t f i 1 650 "2281" cidr_recv - _null_ )); DESCR("I/O"); -DATA(insert OID = 2499 ( cidr_send PGNSP PGUID 12 f f t f i 1 17 "650" cidr_send - _null_ )); +DATA(insert OID = 2499 ( cidr_send PGNSP PGUID 12 f f t f i 1 17 "650" cidr_send - _null_ )); DESCR("I/O"); DATA(insert OID = 2500 ( cstring_recv PGNSP PGUID 12 f f t f s 1 2275 "2281" cstring_recv - _null_ )); DESCR("I/O"); @@ -3416,7 +3416,7 @@ DATA(insert OID = 2507 ( pg_get_indexdef PGNSP PGUID 12 f f t f s 3 25 "26 2 DESCR("index description (full create statement or single expression) with pretty-print option"); DATA(insert OID = 2508 ( pg_get_constraintdef PGNSP PGUID 12 f f t f s 2 25 "26 16" pg_get_constraintdef_ext - _null_ )); DESCR("constraint description with pretty-print option"); -DATA(insert OID = 2509 ( pg_get_expr PGNSP PGUID 12 f f t f s 3 25 "25 26 16" pg_get_expr_ext - _null_ )); +DATA(insert OID = 2509 ( pg_get_expr PGNSP PGUID 12 f f t f s 3 25 "25 26 16" pg_get_expr_ext - _null_ )); DESCR("deparse an encoded expression with pretty-print option"); @@ -3453,6 +3453,6 @@ extern Oid ProcedureCreate(const char *procedureName, const Oid *parameterTypes); extern void check_sql_fn_retval(Oid rettype, char fn_typtype, - List *queryTreeList); + List *queryTreeList); #endif /* PG_PROC_H */ diff --git a/src/include/catalog/pg_statistic.h b/src/include/catalog/pg_statistic.h index c72c68265d..b752bc9c60 100644 --- a/src/include/catalog/pg_statistic.h +++ b/src/include/catalog/pg_statistic.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_statistic.h,v 1.20 2003/03/23 05:14:37 tgl Exp $ + * $Id: pg_statistic.h,v 1.21 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -27,7 +27,7 @@ */ /* - * Keep C compiler happy with anyarray, below. This will need to go elsewhere + * Keep C compiler happy with anyarray, below. This will need to go elsewhere * if we ever use anyarray for more than pg_statistic. */ typedef struct varlena anyarray; @@ -116,8 +116,8 @@ CATALOG(pg_statistic) BKI_WITHOUT_OIDS /* * Values in these arrays are values of the column's data type. We - * presently have to cheat quite a bit to allow polymorphic arrays - * of this kind, but perhaps someday it'll be a less bogus facility. + * presently have to cheat quite a bit to allow polymorphic arrays of + * this kind, but perhaps someday it'll be a less bogus facility. */ anyarray stavalues1; anyarray stavalues2; diff --git a/src/include/catalog/pg_type.h b/src/include/catalog/pg_type.h index 2b4e51c450..57e24bfc48 100644 --- a/src/include/catalog/pg_type.h +++ b/src/include/catalog/pg_type.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_type.h,v 1.145 2003/05/13 18:03:08 tgl Exp $ + * $Id: pg_type.h,v 1.146 2003/08/04 00:43:30 momjian Exp $ * * NOTES * the genbki.sh script reads this file and generates .bki @@ -164,9 +164,9 @@ CATALOG(pg_type) BOOTSTRAP int4 typtypmod; /* - * typndims is the declared number of dimensions for an array domain type - * (i.e., typbasetype is an array type; the domain's typelem will match - * the base type's typelem). Otherwise zero. + * typndims is the declared number of dimensions for an array domain + * type (i.e., typbasetype is an array type; the domain's typelem will + * match the base type's typelem). Otherwise zero. */ int4 typndims; @@ -545,7 +545,7 @@ DATA(insert OID = 2283 ( anyelement PGNSP PGUID 4 t p t \054 0 0 anyelement_in */ extern Oid TypeShellMake(const char *typeName, Oid typeNamespace); -extern Oid TypeCreate(const char *typeName, +extern Oid TypeCreate(const char *typeName, Oid typeNamespace, Oid assignedTypeOid, Oid relationOid, @@ -569,17 +569,17 @@ extern Oid TypeCreate(const char *typeName, bool typeNotNull); extern void GenerateTypeDependencies(Oid typeNamespace, - Oid typeObjectId, - Oid relationOid, - char relationKind, - Oid inputProcedure, - Oid outputProcedure, - Oid receiveProcedure, - Oid sendProcedure, - Oid elementType, - Oid baseType, - Node *defaultExpr, - bool rebuild); + Oid typeObjectId, + Oid relationOid, + char relationKind, + Oid inputProcedure, + Oid outputProcedure, + Oid receiveProcedure, + Oid sendProcedure, + Oid elementType, + Oid baseType, + Node *defaultExpr, + bool rebuild); extern void TypeRename(const char *oldTypeName, Oid typeNamespace, const char *newTypeName); diff --git a/src/include/commands/alter.h b/src/include/commands/alter.h index e3b59af1af..68240e852d 100644 --- a/src/include/commands/alter.h +++ b/src/include/commands/alter.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: alter.h,v 1.1 2003/06/27 14:45:31 petere Exp $ + * $Id: alter.h,v 1.2 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -18,4 +18,4 @@ extern void ExecRenameStmt(RenameStmt *stmt); -#endif /* ALTER_H */ +#endif /* ALTER_H */ diff --git a/src/include/commands/dbcommands.h b/src/include/commands/dbcommands.h index 037859973b..5a3d91d2c4 100644 --- a/src/include/commands/dbcommands.h +++ b/src/include/commands/dbcommands.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: dbcommands.h,v 1.27 2003/06/27 14:45:31 petere Exp $ + * $Id: dbcommands.h,v 1.28 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,7 +21,7 @@ extern void dropdb(const char *dbname); extern void RenameDatabase(const char *oldname, const char *newname); extern void AlterDatabaseSet(AlterDatabaseSetStmt *stmt); -extern Oid get_database_oid(const char *dbname); -extern char * get_database_name(Oid dbid); +extern Oid get_database_oid(const char *dbname); +extern char *get_database_name(Oid dbid); #endif /* DBCOMMANDS_H */ diff --git a/src/include/commands/explain.h b/src/include/commands/explain.h index 69b2268920..60391ea0e3 100644 --- a/src/include/commands/explain.h +++ b/src/include/commands/explain.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994-5, Regents of the University of California * - * $Id: explain.h,v 1.19 2003/05/06 20:26:27 tgl Exp $ + * $Id: explain.h,v 1.20 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -23,6 +23,6 @@ extern void ExplainQuery(ExplainStmt *stmt, DestReceiver *dest); extern TupleDesc ExplainResultDesc(ExplainStmt *stmt); extern void ExplainOnePlan(QueryDesc *queryDesc, ExplainStmt *stmt, - TupOutputState *tstate); + TupOutputState *tstate); #endif /* EXPLAIN_H */ diff --git a/src/include/commands/portalcmds.h b/src/include/commands/portalcmds.h index ce874df667..25cae460b9 100644 --- a/src/include/commands/portalcmds.h +++ b/src/include/commands/portalcmds.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: portalcmds.h,v 1.10 2003/05/06 20:26:27 tgl Exp $ + * $Id: portalcmds.h,v 1.11 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -17,10 +17,10 @@ #include "utils/portal.h" -extern void PerformCursorOpen(DeclareCursorStmt *stmt); +extern void PerformCursorOpen(DeclareCursorStmt * stmt); extern void PerformPortalFetch(FetchStmt *stmt, DestReceiver *dest, - char *completionTag); + char *completionTag); extern void PerformPortalClose(const char *name); diff --git a/src/include/commands/prepare.h b/src/include/commands/prepare.h index 5b8f32dd4c..ca6bbb4d93 100644 --- a/src/include/commands/prepare.h +++ b/src/include/commands/prepare.h @@ -6,7 +6,7 @@ * * Copyright (c) 2002-2003, PostgreSQL Global Development Group * - * $Id: prepare.h,v 1.6 2003/05/06 21:51:42 tgl Exp $ + * $Id: prepare.h,v 1.7 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,7 +37,7 @@ typedef struct List *plan_list; /* list of plans */ List *argtype_list; /* list of parameter type OIDs */ MemoryContext context; /* context containing this query */ -} PreparedStatement; +} PreparedStatement; /* Utility statements PREPARE, EXECUTE, DEALLOCATE, EXPLAIN EXECUTE */ @@ -48,15 +48,15 @@ extern void ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate); /* Low-level access to stored prepared statements */ extern void StorePreparedStatement(const char *stmt_name, - const char *query_string, - const char *commandTag, - List *query_list, - List *plan_list, - List *argtype_list); + const char *query_string, + const char *commandTag, + List *query_list, + List *plan_list, + List *argtype_list); extern PreparedStatement *FetchPreparedStatement(const char *stmt_name, - bool throwError); + bool throwError); extern void DropPreparedStatement(const char *stmt_name, bool showError); extern List *FetchPreparedStatementParams(const char *stmt_name); -extern TupleDesc FetchPreparedStatementResultDesc(PreparedStatement *stmt); +extern TupleDesc FetchPreparedStatementResultDesc(PreparedStatement * stmt); #endif /* PREPARE_H */ diff --git a/src/include/commands/sequence.h b/src/include/commands/sequence.h index a0a18f0f33..3c4b6f1c4a 100644 --- a/src/include/commands/sequence.h +++ b/src/include/commands/sequence.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: sequence.h,v 1.23 2003/03/20 07:02:11 momjian Exp $ + * $Id: sequence.h,v 1.24 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -84,7 +84,7 @@ extern Datum setval(PG_FUNCTION_ARGS); extern Datum setval_and_iscalled(PG_FUNCTION_ARGS); extern void DefineSequence(CreateSeqStmt *stmt); -extern void AlterSequence(AlterSeqStmt *stmt); +extern void AlterSequence(AlterSeqStmt * stmt); extern void seq_redo(XLogRecPtr lsn, XLogRecord *rptr); extern void seq_undo(XLogRecPtr lsn, XLogRecord *rptr); diff --git a/src/include/commands/trigger.h b/src/include/commands/trigger.h index e2aa280a2e..1a2a33b3c2 100644 --- a/src/include/commands/trigger.h +++ b/src/include/commands/trigger.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: trigger.h,v 1.41 2003/03/27 14:33:11 tgl Exp $ + * $Id: trigger.h,v 1.42 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -117,9 +117,9 @@ extern TriggerDesc *CopyTriggerDesc(TriggerDesc *trigdesc); extern void FreeTriggerDesc(TriggerDesc *trigdesc); extern void ExecBSInsertTriggers(EState *estate, - ResultRelInfo *relinfo); + ResultRelInfo *relinfo); extern void ExecASInsertTriggers(EState *estate, - ResultRelInfo *relinfo); + ResultRelInfo *relinfo); extern HeapTuple ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple); @@ -127,25 +127,25 @@ extern void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple); extern void ExecBSDeleteTriggers(EState *estate, - ResultRelInfo *relinfo); + ResultRelInfo *relinfo); extern void ExecASDeleteTriggers(EState *estate, - ResultRelInfo *relinfo); + ResultRelInfo *relinfo); extern bool ExecBRDeleteTriggers(EState *estate, - ResultRelInfo *relinfo, - ItemPointer tupleid, - CommandId cid); + ResultRelInfo *relinfo, + ItemPointer tupleid, + CommandId cid); extern void ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid); extern void ExecBSUpdateTriggers(EState *estate, - ResultRelInfo *relinfo); + ResultRelInfo *relinfo); extern void ExecASUpdateTriggers(EState *estate, - ResultRelInfo *relinfo); + ResultRelInfo *relinfo); extern HeapTuple ExecBRUpdateTriggers(EState *estate, - ResultRelInfo *relinfo, - ItemPointer tupleid, - HeapTuple newtuple, - CommandId cid); + ResultRelInfo *relinfo, + ItemPointer tupleid, + HeapTuple newtuple, + CommandId cid); extern void ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, diff --git a/src/include/commands/typecmds.h b/src/include/commands/typecmds.h index 0d2e319ed4..662fa73d93 100644 --- a/src/include/commands/typecmds.h +++ b/src/include/commands/typecmds.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: typecmds.h,v 1.5 2003/02/03 21:15:44 tgl Exp $ + * $Id: typecmds.h,v 1.6 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,7 +30,7 @@ extern void AlterDomainDefault(List *names, Node *defaultRaw); extern void AlterDomainNotNull(List *names, bool notNull); extern void AlterDomainAddConstraint(List *names, Node *constr); extern void AlterDomainDropConstraint(List *names, const char *constrName, - DropBehavior behavior); + DropBehavior behavior); extern List *GetDomainConstraints(Oid typeOid); diff --git a/src/include/executor/execdesc.h b/src/include/executor/execdesc.h index 5eecb53b8d..05e04c72eb 100644 --- a/src/include/executor/execdesc.h +++ b/src/include/executor/execdesc.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: execdesc.h,v 1.24 2003/05/08 18:16:37 tgl Exp $ + * $Id: execdesc.h,v 1.25 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,9 +45,9 @@ typedef struct QueryDesc /* in pquery.c */ extern QueryDesc *CreateQueryDesc(Query *parsetree, Plan *plantree, - DestReceiver *dest, - ParamListInfo params, - bool doInstrument); + DestReceiver *dest, + ParamListInfo params, + bool doInstrument); extern void FreeQueryDesc(QueryDesc *qdesc); diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h index 741b99c75f..d68289ffe0 100644 --- a/src/include/executor/executor.h +++ b/src/include/executor/executor.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: executor.h,v 1.96 2003/07/21 17:05:10 tgl Exp $ + * $Id: executor.h,v 1.97 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -31,9 +31,9 @@ /* * prototypes from functions in execAmi.c */ -extern void ExecReScan(PlanState *node, ExprContext *exprCtxt); -extern void ExecMarkPos(PlanState *node); -extern void ExecRestrPos(PlanState *node); +extern void ExecReScan(PlanState * node, ExprContext *exprCtxt); +extern void ExecMarkPos(PlanState * node); +extern void ExecRestrPos(PlanState * node); extern bool ExecSupportsMarkRestore(NodeTag plantype); extern bool ExecSupportsBackwardScan(Plan *node); @@ -48,31 +48,31 @@ extern bool execTuplesMatch(HeapTuple tuple1, FmgrInfo *eqfunctions, MemoryContext evalContext); extern bool execTuplesUnequal(HeapTuple tuple1, - HeapTuple tuple2, - TupleDesc tupdesc, - int numCols, - AttrNumber *matchColIdx, - FmgrInfo *eqfunctions, - MemoryContext evalContext); + HeapTuple tuple2, + TupleDesc tupdesc, + int numCols, + AttrNumber *matchColIdx, + FmgrInfo *eqfunctions, + MemoryContext evalContext); extern FmgrInfo *execTuplesMatchPrepare(TupleDesc tupdesc, int numCols, AttrNumber *matchColIdx); extern void execTuplesHashPrepare(TupleDesc tupdesc, - int numCols, - AttrNumber *matchColIdx, - FmgrInfo **eqfunctions, - FmgrInfo **hashfunctions); + int numCols, + AttrNumber *matchColIdx, + FmgrInfo **eqfunctions, + FmgrInfo **hashfunctions); extern TupleHashTable BuildTupleHashTable(int numCols, AttrNumber *keyColIdx, - FmgrInfo *eqfunctions, - FmgrInfo *hashfunctions, - int nbuckets, Size entrysize, - MemoryContext tablecxt, - MemoryContext tempcxt); + FmgrInfo *eqfunctions, + FmgrInfo *hashfunctions, + int nbuckets, Size entrysize, + MemoryContext tablecxt, + MemoryContext tempcxt); extern TupleHashEntry LookupTupleHashEntry(TupleHashTable hashtable, - TupleTableSlot *slot, - bool *isnew); + TupleTableSlot *slot, + bool *isnew); extern TupleHashEntry ScanTupleHashTable(TupleHashTable hashtable, - TupleHashIterator *state); + TupleHashIterator * state); /* * prototypes from functions in execJunk.c @@ -93,7 +93,7 @@ extern TupleTableSlot *ExecutorRun(QueryDesc *queryDesc, extern void ExecutorEnd(QueryDesc *queryDesc); extern void ExecutorRewind(QueryDesc *queryDesc); extern void ExecCheckRTPerms(List *rangeTable, CmdType operation); -extern void ExecEndPlan(PlanState *planstate, EState *estate); +extern void ExecEndPlan(PlanState * planstate, EState *estate); extern void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate); extern TupleTableSlot *EvalPlanQual(EState *estate, Index rti, @@ -103,9 +103,9 @@ extern TupleTableSlot *EvalPlanQual(EState *estate, Index rti, * prototypes from functions in execProcnode.c */ extern PlanState *ExecInitNode(Plan *node, EState *estate); -extern TupleTableSlot *ExecProcNode(PlanState *node); +extern TupleTableSlot *ExecProcNode(PlanState * node); extern int ExecCountSlotsNode(Plan *node); -extern void ExecEndNode(PlanState *node); +extern void ExecEndNode(PlanState * node); /* * prototypes from functions in execQual.c @@ -114,22 +114,22 @@ extern Datum GetAttributeByNum(TupleTableSlot *slot, AttrNumber attrno, bool *isNull); extern Datum GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull); -extern void init_fcache(Oid foid, FuncExprState *fcache, - MemoryContext fcacheCxt); -extern Datum ExecMakeFunctionResult(FuncExprState *fcache, +extern void init_fcache(Oid foid, FuncExprState * fcache, + MemoryContext fcacheCxt); +extern Datum ExecMakeFunctionResult(FuncExprState * fcache, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -extern Tuplestorestate *ExecMakeTableFunctionResult(ExprState *funcexpr, +extern Tuplestorestate *ExecMakeTableFunctionResult(ExprState * funcexpr, ExprContext *econtext, TupleDesc expectedDesc, TupleDesc *returnDesc); -extern Datum ExecEvalExpr(ExprState *expression, ExprContext *econtext, +extern Datum ExecEvalExpr(ExprState * expression, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -extern Datum ExecEvalExprSwitchContext(ExprState *expression, ExprContext *econtext, +extern Datum ExecEvalExprSwitchContext(ExprState * expression, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -extern ExprState *ExecInitExpr(Expr *node, PlanState *parent); -extern SubPlanState *ExecInitExprInitPlan(SubPlan *node, PlanState *parent); +extern ExprState *ExecInitExpr(Expr *node, PlanState * parent); +extern SubPlanState *ExecInitExprInitPlan(SubPlan *node, PlanState * parent); extern ExprState *ExecPrepareExpr(Expr *node, EState *estate); extern bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull); extern int ExecTargetListLength(List *targetlist); @@ -140,10 +140,10 @@ extern TupleTableSlot *ExecProject(ProjectionInfo *projInfo, /* * prototypes from functions in execScan.c */ -typedef TupleTableSlot *(*ExecScanAccessMtd) (ScanState *node); +typedef TupleTableSlot *(*ExecScanAccessMtd) (ScanState * node); -extern TupleTableSlot *ExecScan(ScanState *node, ExecScanAccessMtd accessMtd); -extern void ExecAssignScanProjectionInfo(ScanState *node); +extern TupleTableSlot *ExecScan(ScanState * node, ExecScanAccessMtd accessMtd); +extern void ExecAssignScanProjectionInfo(ScanState * node); /* * prototypes from functions in execTuples.c @@ -160,14 +160,14 @@ extern TupleTableSlot *ExecClearTuple(TupleTableSlot *slot); extern void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc, bool shouldFree); extern void ExecSetSlotDescriptorIsNew(TupleTableSlot *slot, bool isNew); -extern void ExecInitResultTupleSlot(EState *estate, PlanState *planstate); -extern void ExecInitScanTupleSlot(EState *estate, ScanState *scanstate); +extern void ExecInitResultTupleSlot(EState *estate, PlanState * planstate); +extern void ExecInitScanTupleSlot(EState *estate, ScanState * scanstate); extern TupleTableSlot *ExecInitExtraTupleSlot(EState *estate); extern TupleTableSlot *ExecInitNullTupleSlot(EState *estate, TupleDesc tupType); extern TupleDesc ExecTypeFromTL(List *targetList, bool hasoid); extern TupleDesc ExecCleanTypeFromTL(List *targetList, bool hasoid); -extern void UpdateChangedParamSet(PlanState *node, Bitmapset *newchg); +extern void UpdateChangedParamSet(PlanState * node, Bitmapset * newchg); typedef struct TupOutputState { @@ -177,7 +177,7 @@ typedef struct TupOutputState } TupOutputState; extern TupOutputState *begin_tup_output_tupdesc(DestReceiver *dest, - TupleDesc tupdesc); + TupleDesc tupdesc); extern void do_tup_output(TupOutputState *tstate, char **values); extern void do_text_output_multiline(TupOutputState *tstate, char *text); extern void end_tup_output(TupOutputState *tstate); @@ -224,21 +224,21 @@ extern ExprContext *MakePerTupleExprContext(EState *estate); ResetExprContext((estate)->es_per_tuple_exprcontext); \ } while (0) -extern void ExecAssignExprContext(EState *estate, PlanState *planstate); -extern void ExecAssignResultType(PlanState *planstate, +extern void ExecAssignExprContext(EState *estate, PlanState * planstate); +extern void ExecAssignResultType(PlanState * planstate, TupleDesc tupDesc, bool shouldFree); -extern void ExecAssignResultTypeFromOuterPlan(PlanState *planstate); -extern void ExecAssignResultTypeFromTL(PlanState *planstate); -extern TupleDesc ExecGetResultType(PlanState *planstate); +extern void ExecAssignResultTypeFromOuterPlan(PlanState * planstate); +extern void ExecAssignResultTypeFromTL(PlanState * planstate); +extern TupleDesc ExecGetResultType(PlanState * planstate); extern ProjectionInfo *ExecBuildProjectionInfo(List *targetList, - ExprContext *econtext, - TupleTableSlot *slot); -extern void ExecAssignProjectionInfo(PlanState *planstate); -extern void ExecFreeExprContext(PlanState *planstate); -extern TupleDesc ExecGetScanType(ScanState *scanstate); -extern void ExecAssignScanType(ScanState *scanstate, + ExprContext *econtext, + TupleTableSlot *slot); +extern void ExecAssignProjectionInfo(PlanState * planstate); +extern void ExecFreeExprContext(PlanState * planstate); +extern TupleDesc ExecGetScanType(ScanState * scanstate); +extern void ExecAssignScanType(ScanState * scanstate, TupleDesc tupDesc, bool shouldFree); -extern void ExecAssignScanTypeFromOuterPlan(ScanState *scanstate); +extern void ExecAssignScanTypeFromOuterPlan(ScanState * scanstate); extern void ExecOpenIndices(ResultRelInfo *resultRelInfo); extern void ExecCloseIndices(ResultRelInfo *resultRelInfo); diff --git a/src/include/executor/hashjoin.h b/src/include/executor/hashjoin.h index da7e0bf98c..1407e53781 100644 --- a/src/include/executor/hashjoin.h +++ b/src/include/executor/hashjoin.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: hashjoin.h,v 1.28 2003/06/22 22:04:55 tgl Exp $ + * $Id: hashjoin.h,v 1.29 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -71,8 +71,9 @@ typedef struct HashTableData /* * Info about the datatype-specific hash functions for the datatypes * being hashed. We assume that the inner and outer sides of each - * hashclause are the same type, or at least share the same hash function. - * This is an array of the same length as the number of hash keys. + * hashclause are the same type, or at least share the same hash + * function. This is an array of the same length as the number of hash + * keys. */ FmgrInfo *hashfunctions; /* lookup data for hash functions */ diff --git a/src/include/executor/nodeHash.h b/src/include/executor/nodeHash.h index d6d7ea627e..4f4359c23e 100644 --- a/src/include/executor/nodeHash.h +++ b/src/include/executor/nodeHash.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: nodeHash.h,v 1.30 2003/06/22 22:04:55 tgl Exp $ + * $Id: nodeHash.h,v 1.31 2003/08/04 00:43:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,7 +30,7 @@ extern void ExecHashTableInsert(HashJoinTable hashtable, extern int ExecHashGetBucket(HashJoinTable hashtable, ExprContext *econtext, List *hashkeys); -extern int ExecHashGetBatch(int bucketno, HashJoinTable hashtable); +extern int ExecHashGetBatch(int bucketno, HashJoinTable hashtable); extern HeapTuple ExecScanHashBucket(HashJoinState *hjstate, List *hjclauses, ExprContext *econtext); extern void ExecHashTableReset(HashJoinTable hashtable, long ntuples); diff --git a/src/include/executor/nodeSeqscan.h b/src/include/executor/nodeSeqscan.h index 683c4ab7dc..593a2120a2 100644 --- a/src/include/executor/nodeSeqscan.h +++ b/src/include/executor/nodeSeqscan.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: nodeSeqscan.h,v 1.16 2002/12/05 15:50:38 tgl Exp $ + * $Id: nodeSeqscan.h,v 1.17 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -18,10 +18,10 @@ extern int ExecCountSlotsSeqScan(SeqScan *node); extern SeqScanState *ExecInitSeqScan(SeqScan *node, EState *estate); -extern TupleTableSlot *ExecSeqScan(SeqScanState *node); -extern void ExecEndSeqScan(SeqScanState *node); -extern void ExecSeqMarkPos(SeqScanState *node); -extern void ExecSeqRestrPos(SeqScanState *node); -extern void ExecSeqReScan(SeqScanState *node, ExprContext *exprCtxt); +extern TupleTableSlot *ExecSeqScan(SeqScanState * node); +extern void ExecEndSeqScan(SeqScanState * node); +extern void ExecSeqMarkPos(SeqScanState * node); +extern void ExecSeqRestrPos(SeqScanState * node); +extern void ExecSeqReScan(SeqScanState * node, ExprContext *exprCtxt); #endif /* NODESEQSCAN_H */ diff --git a/src/include/executor/nodeSubplan.h b/src/include/executor/nodeSubplan.h index 8a3e74ebd1..ccab4dd347 100644 --- a/src/include/executor/nodeSubplan.h +++ b/src/include/executor/nodeSubplan.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: nodeSubplan.h,v 1.15 2002/12/14 00:17:59 tgl Exp $ + * $Id: nodeSubplan.h,v 1.16 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -16,13 +16,13 @@ #include "nodes/execnodes.h" -extern void ExecInitSubPlan(SubPlanState *node, EState *estate); -extern Datum ExecSubPlan(SubPlanState *node, - ExprContext *econtext, - bool *isNull); -extern void ExecEndSubPlan(SubPlanState *node); -extern void ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent); +extern void ExecInitSubPlan(SubPlanState * node, EState *estate); +extern Datum ExecSubPlan(SubPlanState * node, + ExprContext *econtext, + bool *isNull); +extern void ExecEndSubPlan(SubPlanState * node); +extern void ExecReScanSetParamPlan(SubPlanState * node, PlanState * parent); -extern void ExecSetParamPlan(SubPlanState *node, ExprContext *econtext); +extern void ExecSetParamPlan(SubPlanState * node, ExprContext *econtext); #endif /* NODESUBPLAN_H */ diff --git a/src/include/executor/spi.h b/src/include/executor/spi.h index ead328da24..c7366c1af5 100644 --- a/src/include/executor/spi.h +++ b/src/include/executor/spi.h @@ -2,7 +2,7 @@ * * spi.h * - * $Id: spi.h,v 1.36 2003/03/10 03:53:51 tgl Exp $ + * $Id: spi.h,v 1.37 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -82,8 +82,8 @@ extern int SPI_finish(void); extern void SPI_push(void); extern void SPI_pop(void); extern int SPI_exec(const char *src, int tcount); -extern int SPI_execp(void *plan, Datum *values, const char *Nulls, - int tcount); +extern int SPI_execp(void *plan, Datum *values, const char *Nulls, + int tcount); extern void *SPI_prepare(const char *src, int nargs, Oid *argtypes); extern void *SPI_saveplan(void *plan); extern int SPI_freeplan(void *plan); diff --git a/src/include/executor/spi_priv.h b/src/include/executor/spi_priv.h index 5dd0ff2a6e..c4a6f65dbf 100644 --- a/src/include/executor/spi_priv.h +++ b/src/include/executor/spi_priv.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: spi_priv.h,v 1.14 2003/05/02 20:54:35 tgl Exp $ + * $Id: spi_priv.h,v 1.15 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,7 +27,10 @@ typedef struct typedef struct { - /* context containing _SPI_plan itself as well as subsidiary structures */ + /* + * context containing _SPI_plan itself as well as subsidiary + * structures + */ MemoryContext plancxt; /* List of List of querytrees; one sublist per original parsetree */ List *qtlist; diff --git a/src/include/executor/tstoreReceiver.h b/src/include/executor/tstoreReceiver.h index e7d9497ffe..b345fcbaed 100644 --- a/src/include/executor/tstoreReceiver.h +++ b/src/include/executor/tstoreReceiver.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: tstoreReceiver.h,v 1.2 2003/05/06 20:26:28 tgl Exp $ + * $Id: tstoreReceiver.h,v 1.3 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -20,6 +20,6 @@ extern DestReceiver *CreateTuplestoreDestReceiver(Tuplestorestate *tStore, - MemoryContext tContext); + MemoryContext tContext); -#endif /* TSTORE_RECEIVER_H */ +#endif /* TSTORE_RECEIVER_H */ diff --git a/src/include/getaddrinfo.h b/src/include/getaddrinfo.h index 6312482a7a..4a12cf4274 100644 --- a/src/include/getaddrinfo.h +++ b/src/include/getaddrinfo.h @@ -15,7 +15,7 @@ * * Copyright (c) 2003, PostgreSQL Global Development Group * - * $Id: getaddrinfo.h,v 1.7 2003/07/23 23:30:40 tgl Exp $ + * $Id: getaddrinfo.h,v 1.8 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,14 +30,15 @@ #ifndef HAVE_STRUCT_ADDRINFO -struct addrinfo { - int ai_flags; - int ai_family; - int ai_socktype; - int ai_protocol; - size_t ai_addrlen; +struct addrinfo +{ + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + size_t ai_addrlen; struct sockaddr *ai_addr; - char *ai_canonname; + char *ai_canonname; struct addrinfo *ai_next; }; @@ -56,10 +57,9 @@ struct addrinfo { #define NI_NUMERICHOST 1 #define NI_NUMERICSERV 2 +#endif /* HAVE_STRUCT_ADDRINFO */ -#endif /* HAVE_STRUCT_ADDRINFO */ - -#ifndef NI_MAXHOST +#ifndef NI_MAXHOST #define NI_MAXHOST 1025 #define NI_MAXSERV 32 #endif @@ -87,16 +87,15 @@ struct addrinfo { #ifdef getnameinfo #undef getnameinfo #endif -#define getnameinfo pg_getnameinfo +#define getnameinfo pg_getnameinfo extern int getaddrinfo(const char *node, const char *service, - const struct addrinfo *hints, struct addrinfo **res); -extern void freeaddrinfo(struct addrinfo *res); + const struct addrinfo * hints, struct addrinfo ** res); +extern void freeaddrinfo(struct addrinfo * res); extern const char *gai_strerror(int errcode); -extern int getnameinfo(const struct sockaddr *sa, int salen, +extern int getnameinfo(const struct sockaddr * sa, int salen, char *node, int nodelen, char *service, int servicelen, int flags); +#endif /* HAVE_GETADDRINFO */ -#endif /* HAVE_GETADDRINFO */ - -#endif /* GETADDRINFO_H */ +#endif /* GETADDRINFO_H */ diff --git a/src/include/getopt_long.h b/src/include/getopt_long.h index 5b20622cee..3651cdeee9 100644 --- a/src/include/getopt_long.h +++ b/src/include/getopt_long.h @@ -5,29 +5,29 @@ * Portions Copyright (c) 2003 * PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/include/getopt_long.h,v 1.1 2003/01/06 18:53:25 petere Exp $ + * $Header: /cvsroot/pgsql/src/include/getopt_long.h,v 1.2 2003/08/04 00:43:29 momjian Exp $ */ /* These are picked up from the system's getopt() facility. */ -extern int opterr; -extern int optind; -extern int optopt; +extern int opterr; +extern int optind; +extern int optopt; extern char *optarg; /* Some systems have this, otherwise you need to define it somewhere. */ -extern int optreset; +extern int optreset; -struct option { +struct option +{ const char *name; - int has_arg; - int *flag; - int val; + int has_arg; + int *flag; + int val; }; #define no_argument 0 #define required_argument 1 -int -getopt_long(int argc, char * const argv[], +int getopt_long(int argc, char *const argv[], const char *optstring, - const struct option *longopts, int *longindex); + const struct option * longopts, int *longindex); diff --git a/src/include/lib/stringinfo.h b/src/include/lib/stringinfo.h index 8e305ee430..587fea172e 100644 --- a/src/include/lib/stringinfo.h +++ b/src/include/lib/stringinfo.h @@ -10,7 +10,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: stringinfo.h,v 1.26 2003/04/24 21:16:44 tgl Exp $ + * $Id: stringinfo.h,v 1.27 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -85,14 +85,15 @@ extern void initStringInfo(StringInfo str); * to str if necessary. This is sort of like a combination of sprintf and * strcat. */ -extern void appendStringInfo(StringInfo str, const char *fmt, ...) +extern void +appendStringInfo(StringInfo str, const char *fmt,...) /* This extension allows gcc to check the format string */ __attribute__((format(printf, 2, 3))); /*------------------------ * appendStringInfoVA * Attempt to format text data under the control of fmt (an sprintf-style - * format string) and append it to whatever is already in str. If successful + * format string) and append it to whatever is already in str. If successful * return true; if not (because there's not enough space), return false * without modifying str. Typically the caller would enlarge str and retry * on false return --- see appendStringInfo for standard usage pattern. diff --git a/src/include/libpq/crypt.h b/src/include/libpq/crypt.h index a881e0ae0a..bde0568d48 100644 --- a/src/include/libpq/crypt.h +++ b/src/include/libpq/crypt.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: crypt.h,v 1.24 2002/12/05 18:52:43 momjian Exp $ + * $Id: crypt.h,v 1.25 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -23,7 +23,7 @@ extern int md5_crypt_verify(const Port *port, const char *user, - char *client_pass); + char *client_pass); extern bool md5_hash(const void *buff, size_t len, char *hexsum); extern bool CheckMD5Pwd(char *passwd, char *storedpwd, char *seed); diff --git a/src/include/libpq/ip.h b/src/include/libpq/ip.h index 5c614b1681..c60030ccf5 100644 --- a/src/include/libpq/ip.h +++ b/src/include/libpq/ip.h @@ -5,7 +5,7 @@ * * Copyright (c) 2003, PostgreSQL Global Development Group * - * $Id: ip.h,v 1.9 2003/07/23 23:30:41 tgl Exp $ + * $Id: ip.h,v 1.10 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -16,27 +16,27 @@ #include "libpq/pqcomm.h" -extern int getaddrinfo_all(const char *hostname, const char *servname, - const struct addrinfo *hintp, - struct addrinfo **result); -extern void freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai); +extern int getaddrinfo_all(const char *hostname, const char *servname, + const struct addrinfo * hintp, + struct addrinfo ** result); +extern void freeaddrinfo_all(int hint_ai_family, struct addrinfo * ai); -extern int getnameinfo_all(const struct sockaddr_storage *addr, int salen, - char *node, int nodelen, - char *service, int servicelen, - int flags); +extern int getnameinfo_all(const struct sockaddr_storage * addr, int salen, + char *node, int nodelen, + char *service, int servicelen, + int flags); -extern int rangeSockAddr(const struct sockaddr_storage *addr, - const struct sockaddr_storage *netaddr, - const struct sockaddr_storage *netmask); +extern int rangeSockAddr(const struct sockaddr_storage * addr, + const struct sockaddr_storage * netaddr, + const struct sockaddr_storage * netmask); -extern int SockAddr_cidr_mask(struct sockaddr_storage **mask, - char *numbits, int family); +extern int SockAddr_cidr_mask(struct sockaddr_storage ** mask, + char *numbits, int family); #ifdef HAVE_UNIX_SOCKETS -#define IS_AF_UNIX(fam) ((fam) == AF_UNIX) +#define IS_AF_UNIX(fam) ((fam) == AF_UNIX) #else -#define IS_AF_UNIX(fam) (0) +#define IS_AF_UNIX(fam) (0) #endif -#endif /* IP_H */ +#endif /* IP_H */ diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h index 19ac0402d3..44bf573313 100644 --- a/src/include/libpq/libpq-be.h +++ b/src/include/libpq/libpq-be.h @@ -11,7 +11,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: libpq-be.h,v 1.35 2003/04/17 22:26:01 tgl Exp $ + * $Id: libpq-be.h,v 1.36 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,8 +30,8 @@ /* * This is used by the postmaster in its communication with frontends. It * contains all state information needed during this communication before the - * backend is run. The Port structure is kept in malloc'd memory and is - * still available when a backend is running (see MyProcPort). The data + * backend is run. The Port structure is kept in malloc'd memory and is + * still available when a backend is running (see MyProcPort). The data * it points to must also be malloc'd, or else palloc'd in TopMemoryContext, * so that it survives into PostgresMain execution! */ @@ -44,9 +44,10 @@ typedef struct Port SockAddr raddr; /* remote addr (client) */ /* - * Information that needs to be saved from the startup packet and passed - * into backend execution. "char *" fields are NULL if not set. - * guc_options points to a List of alternating option names and values. + * Information that needs to be saved from the startup packet and + * passed into backend execution. "char *" fields are NULL if not + * set. guc_options points to a List of alternating option names and + * values. */ char *database_name; char *user_name; diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h index 9f72b7e432..82e621fcd1 100644 --- a/src/include/libpq/libpq.h +++ b/src/include/libpq/libpq.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: libpq.h,v 1.58 2003/06/12 07:36:51 momjian Exp $ + * $Id: libpq.h,v 1.59 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -46,8 +46,8 @@ typedef struct * prototypes for functions in pqcomm.c */ extern int StreamServerPort(int family, char *hostName, - unsigned short portNumber, char *unixSocketName, int ListenSocket[], - int MaxListen); + unsigned short portNumber, char *unixSocketName, int ListenSocket[], + int MaxListen); extern int StreamConnection(int server_fd, Port *port); extern void StreamClose(int sock); extern void TouchSocketFile(void); @@ -66,11 +66,11 @@ extern void pq_endcopyout(bool errorAbort); /* * prototypes for functions in be-secure.c */ -extern int secure_initialize(void); -extern void secure_destroy(void); -extern int secure_open_server(Port *port); -extern void secure_close(Port *port); -extern ssize_t secure_read(Port *port, void *ptr, size_t len); -extern ssize_t secure_write(Port *port, void *ptr, size_t len); +extern int secure_initialize(void); +extern void secure_destroy(void); +extern int secure_open_server(Port *port); +extern void secure_close(Port *port); +extern ssize_t secure_read(Port *port, void *ptr, size_t len); +extern ssize_t secure_write(Port *port, void *ptr, size_t len); #endif /* LIBPQ_H */ diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 2e41b0896a..da756fb316 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -9,7 +9,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pqcomm.h,v 1.91 2003/07/27 17:10:07 tgl Exp $ + * $Id: pqcomm.h,v 1.92 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -35,11 +35,11 @@ #ifdef HAVE_STRUCT_SOCKADDR_STORAGE #ifndef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY -# ifdef HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY -# define ss_family __ss_family -# else -# error struct sockaddr_storage does not provide an ss_family member -# endif +#ifdef HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY +#define ss_family __ss_family +#else +#error struct sockaddr_storage does not provide an ss_family member +#endif #endif #ifdef HAVE_STRUCT_SOCKADDR_STORAGE___SS_LEN @@ -47,16 +47,18 @@ #define HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN 1 #endif -#else /* !HAVE_STRUCT_SOCKADDR_STORAGE */ +#else /* !HAVE_STRUCT_SOCKADDR_STORAGE */ /* Define a struct sockaddr_storage if we don't have one. */ -struct sockaddr_storage { - union { +struct sockaddr_storage +{ + union + { struct sockaddr sa; /* get the system-dependent fields */ - int64 ss_align; /* ensures struct is properly aligned */ - char ss_pad[128]; /* ensures struct has desired size */ - } ss_stuff; + int64 ss_align; /* ensures struct is properly aligned */ + char ss_pad[128]; /* ensures struct has desired size */ + } ss_stuff; }; #define ss_family ss_stuff.sa.sa_family @@ -65,12 +67,12 @@ struct sockaddr_storage { #define ss_len ss_stuff.sa.sa_len #define HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN 1 #endif +#endif /* HAVE_STRUCT_SOCKADDR_STORAGE */ -#endif /* HAVE_STRUCT_SOCKADDR_STORAGE */ - -typedef struct { - struct sockaddr_storage addr; - ACCEPT_TYPE_ARG3 salen; +typedef struct +{ + struct sockaddr_storage addr; + ACCEPT_TYPE_ARG3 salen; } SockAddr; /* Configure the UNIX socket location for the well known port. */ @@ -148,7 +150,7 @@ extern bool Db_user_namespace; /* * In protocol 3.0 and later, the startup packet length is not fixed, but - * we set an arbitrary limit on it anyway. This is just to prevent simple + * we set an arbitrary limit on it anyway. This is just to prevent simple * denial-of-service attacks via sending enough data to run the server * out of memory. */ diff --git a/src/include/libpq/pqformat.h b/src/include/libpq/pqformat.h index 2102960e88..9f73083e10 100644 --- a/src/include/libpq/pqformat.h +++ b/src/include/libpq/pqformat.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pqformat.h,v 1.18 2003/05/09 21:19:50 tgl Exp $ + * $Id: pqformat.h,v 1.19 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -19,7 +19,7 @@ extern void pq_beginmessage(StringInfo buf, char msgtype); extern void pq_sendbyte(StringInfo buf, int byt); extern void pq_sendbytes(StringInfo buf, const char *data, int datalen); extern void pq_sendcountedtext(StringInfo buf, const char *str, int slen, - bool countincludesself); + bool countincludesself); extern void pq_sendtext(StringInfo buf, const char *str, int slen); extern void pq_sendstring(StringInfo buf, const char *str); extern void pq_sendint(StringInfo buf, int i, int b); diff --git a/src/include/mb/pg_wchar.h b/src/include/mb/pg_wchar.h index 7c7da9d199..a281c586a5 100644 --- a/src/include/mb/pg_wchar.h +++ b/src/include/mb/pg_wchar.h @@ -1,4 +1,4 @@ -/* $Id: pg_wchar.h,v 1.47 2003/07/27 04:53:11 tgl Exp $ */ +/* $Id: pg_wchar.h,v 1.48 2003/08/04 00:43:31 momjian Exp $ */ #ifndef PG_WCHAR_H #define PG_WCHAR_H @@ -295,7 +295,7 @@ extern int pg_database_encoding_max_length(void); extern void SetDefaultClientEncoding(void); extern int SetClientEncoding(int encoding, bool doit); -extern void InitializeClientEncoding(void); +extern void InitializeClientEncoding(void); extern int pg_get_client_encoding(void); extern const char *pg_get_client_encoding_name(void); diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index 7e7219ef4d..2531879417 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -12,7 +12,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: miscadmin.h,v 1.129 2003/07/29 00:03:18 tgl Exp $ + * $Id: miscadmin.h,v 1.130 2003/08/04 00:43:29 momjian Exp $ * * NOTES * some of the information in this file should be moved to @@ -54,8 +54,8 @@ * A related, but conceptually distinct, mechanism is the "critical section" * mechanism. A critical section not only holds off cancel/die interrupts, * but causes any ereport(ERROR) or ereport(FATAL) to become ereport(PANIC) - * --- that is, a system-wide reset is forced. Needless to say, only really - * *critical* code should be marked as a critical section! Currently, this + * --- that is, a system-wide reset is forced. Needless to say, only really + * *critical* code should be marked as a critical section! Currently, this * mechanism is only used for XLOG-related code. * *****************************************************************************/ @@ -196,9 +196,11 @@ extern bool NetServer; extern bool EnableSSL; extern bool SilentMode; extern int MaxBackends; + #define DEF_MAXBACKENDS 32 extern int ReservedBackends; -extern DLLIMPORT int NBuffers; +extern DLLIMPORT int NBuffers; + #define DEF_NBUFFERS (DEF_MAXBACKENDS > 8 ? DEF_MAXBACKENDS * 2 : 16) extern int PostPortNumber; extern int Unix_socket_permissions; @@ -243,7 +245,7 @@ extern char *convertstr(unsigned char *buff, int len, int dest); /* in utils/misc/superuser.c */ extern bool superuser(void); /* current user is superuser */ -extern bool superuser_arg(AclId userid); /* given user is superuser */ +extern bool superuser_arg(AclId userid); /* given user is superuser */ /***************************************************************************** diff --git a/src/include/nodes/bitmapset.h b/src/include/nodes/bitmapset.h index 7974c44aae..6c2e8ac13c 100644 --- a/src/include/nodes/bitmapset.h +++ b/src/include/nodes/bitmapset.h @@ -13,7 +13,7 @@ * * Copyright (c) 2003, PostgreSQL Global Development Group * - * $Id: bitmapset.h,v 1.2 2003/06/29 23:05:05 tgl Exp $ + * $Id: bitmapset.h,v 1.3 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,12 +27,13 @@ /* The unit size can be adjusted by changing these three declarations: */ #define BITS_PER_BITMAPWORD 32 typedef uint32 bitmapword; /* must be an unsigned type */ -typedef int32 signedbitmapword; /* must be the matching signed type */ +typedef int32 signedbitmapword; /* must be the matching signed type */ -typedef struct Bitmapset { - int nwords; /* number of words in array */ - bitmapword words[1]; /* really [nwords] */ -} Bitmapset; /* VARIABLE LENGTH STRUCT */ +typedef struct Bitmapset +{ + int nwords; /* number of words in array */ + bitmapword words[1]; /* really [nwords] */ +} Bitmapset; /* VARIABLE LENGTH STRUCT */ /* result of bms_membership */ @@ -41,41 +42,42 @@ typedef enum BMS_EMPTY_SET, /* 0 members */ BMS_SINGLETON, /* 1 member */ BMS_MULTIPLE /* >1 member */ -} BMS_Membership; +} BMS_Membership; /* * function prototypes in nodes/bitmapset.c */ -extern Bitmapset *bms_copy(const Bitmapset *a); -extern bool bms_equal(const Bitmapset *a, const Bitmapset *b); +extern Bitmapset *bms_copy(const Bitmapset * a); +extern bool bms_equal(const Bitmapset * a, const Bitmapset * b); extern Bitmapset *bms_make_singleton(int x); -extern void bms_free(Bitmapset *a); +extern void bms_free(Bitmapset * a); + +extern Bitmapset *bms_union(const Bitmapset * a, const Bitmapset * b); +extern Bitmapset *bms_intersect(const Bitmapset * a, const Bitmapset * b); +extern Bitmapset *bms_difference(const Bitmapset * a, const Bitmapset * b); +extern bool bms_is_subset(const Bitmapset * a, const Bitmapset * b); +extern bool bms_is_member(int x, const Bitmapset * a); +extern bool bms_overlap(const Bitmapset * a, const Bitmapset * b); +extern bool bms_nonempty_difference(const Bitmapset * a, const Bitmapset * b); +extern int bms_singleton_member(const Bitmapset * a); +extern int bms_num_members(const Bitmapset * a); -extern Bitmapset *bms_union(const Bitmapset *a, const Bitmapset *b); -extern Bitmapset *bms_intersect(const Bitmapset *a, const Bitmapset *b); -extern Bitmapset *bms_difference(const Bitmapset *a, const Bitmapset *b); -extern bool bms_is_subset(const Bitmapset *a, const Bitmapset *b); -extern bool bms_is_member(int x, const Bitmapset *a); -extern bool bms_overlap(const Bitmapset *a, const Bitmapset *b); -extern bool bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b); -extern int bms_singleton_member(const Bitmapset *a); -extern int bms_num_members(const Bitmapset *a); /* optimized tests when we don't need to know exact membership count: */ -extern BMS_Membership bms_membership(const Bitmapset *a); -extern bool bms_is_empty(const Bitmapset *a); +extern BMS_Membership bms_membership(const Bitmapset * a); +extern bool bms_is_empty(const Bitmapset * a); /* these routines recycle (modify or free) their non-const inputs: */ -extern Bitmapset *bms_add_member(Bitmapset *a, int x); -extern Bitmapset *bms_del_member(Bitmapset *a, int x); -extern Bitmapset *bms_add_members(Bitmapset *a, const Bitmapset *b); -extern Bitmapset *bms_int_members(Bitmapset *a, const Bitmapset *b); -extern Bitmapset *bms_del_members(Bitmapset *a, const Bitmapset *b); -extern Bitmapset *bms_join(Bitmapset *a, Bitmapset *b); +extern Bitmapset *bms_add_member(Bitmapset * a, int x); +extern Bitmapset *bms_del_member(Bitmapset * a, int x); +extern Bitmapset *bms_add_members(Bitmapset * a, const Bitmapset * b); +extern Bitmapset *bms_int_members(Bitmapset * a, const Bitmapset * b); +extern Bitmapset *bms_del_members(Bitmapset * a, const Bitmapset * b); +extern Bitmapset *bms_join(Bitmapset * a, Bitmapset * b); /* support for iterating through the integer elements of a set: */ -extern int bms_first_member(Bitmapset *a); +extern int bms_first_member(Bitmapset * a); #endif /* BITMAPSET_H */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index c6f1342343..dc68f88a62 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: execnodes.h,v 1.100 2003/06/29 00:33:44 tgl Exp $ + * $Id: execnodes.h,v 1.101 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -46,10 +46,10 @@ typedef struct IndexInfo NodeTag type; int ii_NumIndexAttrs; AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]; - List *ii_Expressions; /* list of Expr */ - List *ii_ExpressionsState; /* list of ExprState */ + List *ii_Expressions; /* list of Expr */ + List *ii_ExpressionsState; /* list of ExprState */ List *ii_Predicate; /* list of Expr */ - List *ii_PredicateState; /* list of ExprState */ + List *ii_PredicateState; /* list of ExprState */ bool ii_Unique; } IndexInfo; @@ -80,7 +80,7 @@ typedef struct ExprContext_CB * * There are two memory contexts associated with an ExprContext: * * ecxt_per_query_memory is a query-lifespan context, typically the same - * context the ExprContext node itself is allocated in. This context + * context the ExprContext node itself is allocated in. This context * can be used for purposes such as storing function call cache info. * * ecxt_per_tuple_memory is a short-term context for expression results. * As the name suggests, it will typically be reset once per tuple, @@ -176,7 +176,7 @@ typedef struct ReturnSetInfo * call ExecProject(). -cim 6/3/91 * * ExecProject() evaluates the tlist, forms a tuple, and stores it - * in the given slot. As a side-effect, the actual datum values and + * in the given slot. As a side-effect, the actual datum values and * null indicators are placed in the work arrays tupValues/tupNulls. * * targetlist target list for projection @@ -283,9 +283,9 @@ typedef struct EState NodeTag type; /* Basic state for all query types: */ - ScanDirection es_direction; /* current scan direction */ + ScanDirection es_direction; /* current scan direction */ Snapshot es_snapshot; /* time qual to use */ - List *es_range_table; /* List of RangeTableEntrys */ + List *es_range_table; /* List of RangeTableEntrys */ /* Info about target table for insert/update/delete queries: */ ResultRelInfo *es_result_relations; /* array of ResultRelInfos */ @@ -293,7 +293,7 @@ typedef struct EState ResultRelInfo *es_result_relation_info; /* currently active array * elt */ JunkFilter *es_junkFilter; /* currently active junk filter */ - Relation es_into_relation_descriptor; /* for SELECT INTO */ + Relation es_into_relation_descriptor; /* for SELECT INTO */ /* Parameter info: */ ParamListInfo es_param_list_info; /* values of external params */ @@ -309,10 +309,11 @@ typedef struct EState List *es_rowMark; /* not good place, but there is no other */ bool es_instrument; /* true requests runtime instrumentation */ - bool es_force_oids; /* true forces result tuples to have (space - * for) OIDs --- used for SELECT INTO */ + bool es_force_oids; /* true forces result tuples to have + * (space for) OIDs --- used for SELECT + * INTO */ - List *es_exprcontexts; /* List of ExprContexts within EState */ + List *es_exprcontexts; /* List of ExprContexts within EState */ /* * this ExprContext is for per-output-tuple operations, such as @@ -324,10 +325,11 @@ typedef struct EState /* Below is to re-evaluate plan qual in READ COMMITTED mode */ Plan *es_topPlan; /* link to top of plan tree */ - struct evalPlanQual *es_evalPlanQual; /* chain of PlanQual states */ - bool *es_evTupleNull; /* local array of EPQ status */ + struct evalPlanQual *es_evalPlanQual; /* chain of PlanQual + * states */ + bool *es_evTupleNull; /* local array of EPQ status */ HeapTuple *es_evTuple; /* shared array of EPQ substitute tuples */ - bool es_useEvalPlan; /* evaluating EPQ tuples? */ + bool es_useEvalPlan; /* evaluating EPQ tuples? */ } EState; @@ -346,7 +348,7 @@ typedef struct TupleHashEntryData uint32 hashkey; /* exact hash key of this entry */ HeapTuple firstTuple; /* copy of first tuple in this group */ /* there may be additional data beyond the end of this struct */ -} TupleHashEntryData; /* VARIABLE LENGTH STRUCT */ +} TupleHashEntryData; /* VARIABLE LENGTH STRUCT */ typedef struct TupleHashTableData { @@ -359,13 +361,13 @@ typedef struct TupleHashTableData Size entrysize; /* actual size to make each hash entry */ int nbuckets; /* number of buckets in hash table */ TupleHashEntry buckets[1]; /* VARIABLE LENGTH ARRAY */ -} TupleHashTableData; /* VARIABLE LENGTH STRUCT */ +} TupleHashTableData; /* VARIABLE LENGTH STRUCT */ typedef struct { TupleHashEntry next_entry; /* next entry in current chain */ int next_bucket; /* next chain */ -} TupleHashIterator; +} TupleHashIterator; #define ResetTupleHashIterator(iter) \ ((iter)->next_entry = NULL, \ @@ -397,7 +399,7 @@ typedef struct ExprState { NodeTag type; Expr *expr; /* associated Expr node */ -} ExprState; +} ExprState; /* ---------------- * GenericExprState node @@ -410,7 +412,7 @@ typedef struct GenericExprState { ExprState xprstate; ExprState *arg; /* state of my child node */ -} GenericExprState; +} GenericExprState; /* ---------------- * AggrefExprState node @@ -421,7 +423,7 @@ typedef struct AggrefExprState ExprState xprstate; ExprState *target; /* state of my child node */ int aggno; /* ID number for agg within its plan node */ -} AggrefExprState; +} AggrefExprState; /* ---------------- * ArrayRefExprState node @@ -434,7 +436,7 @@ typedef struct AggrefExprState typedef struct ArrayRefExprState { ExprState xprstate; - List *refupperindexpr; /* states for child nodes */ + List *refupperindexpr; /* states for child nodes */ List *reflowerindexpr; ExprState *refexpr; ExprState *refassgnexpr; @@ -442,7 +444,7 @@ typedef struct ArrayRefExprState int16 refelemlength; /* typlen of the array element type */ bool refelembyval; /* is the element type pass-by-value? */ char refelemalign; /* typalign of the element type */ -} ArrayRefExprState; +} ArrayRefExprState; /* ---------------- * FuncExprState node @@ -458,17 +460,17 @@ typedef struct FuncExprState List *args; /* states of argument expressions */ /* - * Function manager's lookup info for the target function. If func.fn_oid - * is InvalidOid, we haven't initialized it yet. + * Function manager's lookup info for the target function. If + * func.fn_oid is InvalidOid, we haven't initialized it yet. */ FmgrInfo func; /* - * We also need to store argument values across calls when evaluating a - * function-returning-set. + * We also need to store argument values across calls when evaluating + * a function-returning-set. * - * setArgsValid is true when we are evaluating a set-valued function - * and we are in the middle of a call series; we want to pass the same + * setArgsValid is true when we are evaluating a set-valued function and + * we are in the middle of a call series; we want to pass the same * argument values to the function again (and again, until it returns * ExprEndResult). */ @@ -486,7 +488,7 @@ typedef struct FuncExprState * data only if setArgsValid is true. */ FunctionCallInfoData setArgs; -} FuncExprState; +} FuncExprState; /* ---------------- * ScalarArrayOpExprState node @@ -496,13 +498,13 @@ typedef struct FuncExprState */ typedef struct ScalarArrayOpExprState { - FuncExprState fxprstate; + FuncExprState fxprstate; /* Cached info about array element type */ - Oid element_type; - int16 typlen; - bool typbyval; - char typalign; -} ScalarArrayOpExprState; + Oid element_type; + int16 typlen; + bool typbyval; + char typalign; +} ScalarArrayOpExprState; /* ---------------- * BoolExprState node @@ -512,7 +514,7 @@ typedef struct BoolExprState { ExprState xprstate; List *args; /* states of argument expression(s) */ -} BoolExprState; +} BoolExprState; /* ---------------- * SubPlanState node @@ -522,7 +524,7 @@ typedef struct SubPlanState { ExprState xprstate; EState *sub_estate; /* subselect plan has its own EState */ - struct PlanState *planstate; /* subselect plan's state tree */ + struct PlanState *planstate; /* subselect plan's state tree */ List *exprs; /* states of combining expression(s) */ List *args; /* states of argument expression(s) */ bool needShutdown; /* TRUE = need to shutdown subplan */ @@ -535,11 +537,11 @@ typedef struct SubPlanState bool havehashrows; /* TRUE if hashtable is not empty */ bool havenullrows; /* TRUE if hashnulls is not empty */ MemoryContext tablecxt; /* memory context containing tables */ - ExprContext *innerecontext; /* working context for comparisons */ + ExprContext *innerecontext; /* working context for comparisons */ AttrNumber *keyColIdx; /* control data for hash tables */ FmgrInfo *eqfunctions; /* comparison functions for hash tables */ FmgrInfo *hashfunctions; /* lookup data for hash functions */ -} SubPlanState; +} SubPlanState; /* ---------------- * CaseExprState node @@ -550,7 +552,7 @@ typedef struct CaseExprState ExprState xprstate; List *args; /* the arguments (list of WHEN clauses) */ ExprState *defresult; /* the default result (ELSE clause) */ -} CaseExprState; +} CaseExprState; /* ---------------- * CaseWhenState node @@ -561,7 +563,7 @@ typedef struct CaseWhenState ExprState xprstate; ExprState *expr; /* condition expression */ ExprState *result; /* substitution result */ -} CaseWhenState; +} CaseWhenState; /* ---------------- * ArrayExprState node @@ -577,7 +579,7 @@ typedef struct ArrayExprState int16 elemlength; /* typlen of the array element type */ bool elembyval; /* is the element type pass-by-value? */ char elemalign; /* typalign of the element type */ -} ArrayExprState; +} ArrayExprState; /* ---------------- * CoalesceExprState node @@ -586,8 +588,8 @@ typedef struct ArrayExprState typedef struct CoalesceExprState { ExprState xprstate; - List *args; /* the arguments */ -} CoalesceExprState; + List *args; /* the arguments */ +} CoalesceExprState; /* ---------------- * CoerceToDomainState node @@ -599,7 +601,7 @@ typedef struct CoerceToDomainState ExprState *arg; /* input expression */ /* Cached list of constraints that need to be checked */ List *constraints; /* list of DomainConstraintState nodes */ -} CoerceToDomainState; +} CoerceToDomainState; /* * DomainConstraintState - one item to check during CoerceToDomain @@ -612,15 +614,15 @@ typedef enum DomainConstraintType { DOM_CONSTRAINT_NOTNULL, DOM_CONSTRAINT_CHECK -} DomainConstraintType; +} DomainConstraintType; typedef struct DomainConstraintState { NodeTag type; - DomainConstraintType constrainttype; /* constraint type */ + DomainConstraintType constrainttype; /* constraint type */ char *name; /* name of constraint (for error msgs) */ ExprState *check_expr; /* for CHECK, a boolean expression */ -} DomainConstraintState; +} DomainConstraintState; /* ---------------------------------------------------------------- @@ -652,13 +654,14 @@ typedef struct PlanState * plan node */ /* - * Common structural data for all Plan types. These links to subsidiary - * state trees parallel links in the associated plan tree (except for - * the subPlan list, which does not exist in the plan tree). + * Common structural data for all Plan types. These links to + * subsidiary state trees parallel links in the associated plan tree + * (except for the subPlan list, which does not exist in the plan + * tree). */ List *targetlist; /* target list to be computed at this node */ List *qual; /* implicitly-ANDed qual conditions */ - struct PlanState *lefttree; /* input plan tree(s) */ + struct PlanState *lefttree; /* input plan tree(s) */ struct PlanState *righttree; List *initPlan; /* Init SubPlanState nodes (un-correlated * expr subselects) */ @@ -672,13 +675,13 @@ typedef struct PlanState /* * Other run-time state needed by most if not all node types. */ - TupleTableSlot *ps_OuterTupleSlot; /* slot for current "outer" tuple */ - TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */ - ExprContext *ps_ExprContext; /* node's expression-evaluation context */ - ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */ - bool ps_TupFromTlist; /* state flag for processing set-valued - * functions in targetlist */ -} PlanState; + TupleTableSlot *ps_OuterTupleSlot; /* slot for current "outer" tuple */ + TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */ + ExprContext *ps_ExprContext; /* node's expression-evaluation context */ + ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */ + bool ps_TupFromTlist;/* state flag for processing set-valued + * functions in targetlist */ +} PlanState; /* ---------------- * these are are defined to avoid confusion problems with "left" @@ -747,7 +750,7 @@ typedef struct ScanState Relation ss_currentRelation; HeapScanDesc ss_currentScanDesc; TupleTableSlot *ss_ScanTupleSlot; -} ScanState; +} ScanState; /* * SeqScan uses a bare ScanState as its state node, since it needs @@ -894,9 +897,9 @@ typedef struct NestLoopState typedef struct MergeJoinState { JoinState js; /* its first field is NodeTag */ - List *mergeclauses; /* list of ExprState nodes */ - List *mj_OuterSkipQual; /* list of ExprState nodes */ - List *mj_InnerSkipQual; /* list of ExprState nodes */ + List *mergeclauses; /* list of ExprState nodes */ + List *mj_OuterSkipQual; /* list of ExprState nodes */ + List *mj_InnerSkipQual; /* list of ExprState nodes */ int mj_JoinState; bool mj_MatchedOuter; bool mj_MatchedInner; @@ -934,9 +937,9 @@ typedef struct HashJoinState HashJoinTable hj_HashTable; int hj_CurBucketNo; HashJoinTuple hj_CurTuple; - List *hj_OuterHashKeys; /* list of ExprState nodes */ - List *hj_InnerHashKeys; /* list of ExprState nodes */ - List *hj_HashOperators; /* list of operator OIDs */ + List *hj_OuterHashKeys; /* list of ExprState nodes */ + List *hj_InnerHashKeys; /* list of ExprState nodes */ + List *hj_HashOperators; /* list of operator OIDs */ TupleTableSlot *hj_OuterTupleSlot; TupleTableSlot *hj_HashTupleSlot; TupleTableSlot *hj_NullInnerTupleSlot; @@ -963,8 +966,8 @@ typedef struct HashJoinState typedef struct MaterialState { ScanState ss; /* its first field is NodeTag */ - void *tuplestorestate; /* private state of tuplestore.c */ - bool eof_underlying; /* reached end of underlying plan? */ + void *tuplestorestate; /* private state of tuplestore.c */ + bool eof_underlying; /* reached end of underlying plan? */ } MaterialState; /* ---------------- @@ -975,7 +978,7 @@ typedef struct SortState { ScanState ss; /* its first field is NodeTag */ bool sort_Done; /* sort completed yet? */ - void *tuplesortstate; /* private state of tuplesort.c */ + void *tuplesortstate; /* private state of tuplesort.c */ } SortState; /* --------------------- @@ -986,7 +989,7 @@ typedef struct GroupState { ScanState ss; /* its first field is NodeTag */ FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */ - HeapTuple grp_firstTuple; /* copy of first tuple of current group */ + HeapTuple grp_firstTuple; /* copy of first tuple of current group */ bool grp_done; /* indicates completion of Group scan */ } GroupState; @@ -1019,11 +1022,11 @@ typedef struct AggState bool agg_done; /* indicates completion of Agg scan */ /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */ AggStatePerGroup pergroup; /* per-Aggref-per-group working state */ - HeapTuple grp_firstTuple; /* copy of first tuple of current group */ + HeapTuple grp_firstTuple; /* copy of first tuple of current group */ /* these fields are used in AGG_HASHED mode: */ TupleHashTable hashtable; /* hash table with one entry per group */ bool table_filled; /* hash table filled yet? */ - TupleHashIterator hashiter; /* for iterating through hash table */ + TupleHashIterator hashiter; /* for iterating through hash table */ } AggState; /* ---------------- @@ -1097,7 +1100,7 @@ typedef enum LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */ LIMIT_WINDOWEND, /* stepped off end of window */ LIMIT_WINDOWSTART /* stepped off beginning of window */ -} LimitStateCond; +} LimitStateCond; typedef struct LimitState { diff --git a/src/include/nodes/makefuncs.h b/src/include/nodes/makefuncs.h index f1b45e897b..3f0772aa19 100644 --- a/src/include/nodes/makefuncs.h +++ b/src/include/nodes/makefuncs.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: makefuncs.h,v 1.45 2003/07/01 19:10:53 tgl Exp $ + * $Id: makefuncs.h,v 1.46 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -18,10 +18,10 @@ extern A_Expr *makeA_Expr(A_Expr_Kind kind, List *name, - Node *lexpr, Node *rexpr); + Node *lexpr, Node *rexpr); extern A_Expr *makeSimpleA_Expr(A_Expr_Kind kind, const char *name, - Node *lexpr, Node *rexpr); + Node *lexpr, Node *rexpr); extern Var *makeVar(Index varno, AttrNumber varattno, @@ -50,13 +50,13 @@ extern Expr *makeBoolExpr(BoolExprType boolop, List *args); extern Alias *makeAlias(const char *aliasname, List *colnames); extern RelabelType *makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, - CoercionForm rformat); + CoercionForm rformat); extern RangeVar *makeRangeVar(char *schemaname, char *relname); extern TypeName *makeTypeName(char *typnam); extern FuncExpr *makeFuncExpr(Oid funcid, Oid rettype, - List *args, CoercionForm fformat); + List *args, CoercionForm fformat); #endif /* MAKEFUNC_H */ diff --git a/src/include/nodes/nodes.h b/src/include/nodes/nodes.h index 6e678b26b3..2bd81698d1 100644 --- a/src/include/nodes/nodes.h +++ b/src/include/nodes/nodes.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: nodes.h,v 1.144 2003/07/03 16:34:25 tgl Exp $ + * $Id: nodes.h,v 1.145 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -129,8 +129,8 @@ typedef enum NodeTag /* * TAGS FOR EXPRESSION STATE NODES (execnodes.h) * - * These correspond (not always one-for-one) to primitive nodes - * derived from Expr. + * These correspond (not always one-for-one) to primitive nodes derived + * from Expr. */ T_ExprState = 400, T_GenericExprState, diff --git a/src/include/nodes/params.h b/src/include/nodes/params.h index 8d7aa3ab32..19a2309660 100644 --- a/src/include/nodes/params.h +++ b/src/include/nodes/params.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: params.h,v 1.21 2002/12/14 00:17:59 tgl Exp $ + * $Id: params.h,v 1.22 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -51,7 +51,7 @@ * ParamListInfo * * ParamListInfo entries are used to pass parameters into the executor - * for parameterized plans. Each entry in the array defines the value + * for parameterized plans. Each entry in the array defines the value * to be substituted for a PARAM_NAMED or PARAM_NUM parameter. * * kind : the kind of parameter (PARAM_NAMED or PARAM_NUM) @@ -89,9 +89,9 @@ typedef ParamListInfoData *ParamListInfo; * es_param_exec_vals or ecxt_param_exec_vals. * * If execPlan is not NULL, it points to a SubPlanState node that needs - * to be executed to produce the value. (This is done so that we can have + * to be executed to produce the value. (This is done so that we can have * lazy evaluation of InitPlans: they aren't executed until/unless a - * result value is needed.) Otherwise the value is assumed to be valid + * result value is needed.) Otherwise the value is assumed to be valid * when needed. * ---------------- */ diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 5cfe5ec645..15de2ade0e 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: parsenodes.h,v 1.243 2003/07/03 16:34:25 tgl Exp $ + * $Id: parsenodes.h,v 1.244 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -25,7 +25,7 @@ typedef enum QuerySource QSRC_INSTEAD_RULE, /* added by unconditional INSTEAD rule */ QSRC_QUAL_INSTEAD_RULE, /* added by conditional INSTEAD rule */ QSRC_NON_INSTEAD_RULE /* added by non-INSTEAD rule */ -} QuerySource; +} QuerySource; /***************************************************************************** @@ -45,7 +45,7 @@ typedef struct Query CmdType commandType; /* select|insert|update|delete|utility */ - QuerySource querySource; /* where did I come from? */ + QuerySource querySource; /* where did I come from? */ bool canSetTag; /* do I set the command result tag? */ @@ -175,12 +175,12 @@ typedef enum A_Expr_Kind AEXPR_DISTINCT, /* IS DISTINCT FROM - name must be "=" */ AEXPR_NULLIF, /* NULLIF - name must be "=" */ AEXPR_OF /* IS (not) OF - name must be "=" or "!=" */ -} A_Expr_Kind; +} A_Expr_Kind; typedef struct A_Expr { NodeTag type; - A_Expr_Kind kind; /* see above */ + A_Expr_Kind kind; /* see above */ List *name; /* possibly-qualified name of operator */ Node *lexpr; /* left argument, or NULL if none */ Node *rexpr; /* right argument, or NULL if none */ @@ -352,7 +352,7 @@ typedef struct InhRelation NodeTag type; RangeVar *relation; bool including_defaults; -} InhRelation; +} InhRelation; /* * IndexElem - index parameters (used in CREATE INDEX) @@ -668,7 +668,8 @@ typedef struct SetOperationStmt * object type. */ -typedef enum ObjectType { +typedef enum ObjectType +{ OBJECT_AGGREGATE, OBJECT_CAST, OBJECT_COLUMN, @@ -690,7 +691,7 @@ typedef enum ObjectType { OBJECT_TYPE, OBJECT_USER, OBJECT_VIEW -} ObjectType; +} ObjectType; /* ---------------------- * Create Schema Statement @@ -739,7 +740,7 @@ typedef struct AlterTableStmt * E = create toast table * U = change owner * L = CLUSTER ON - * o = DROP OIDS + * o = DROP OIDS *------------ */ RangeVar *relation; /* table to work on */ @@ -773,7 +774,7 @@ typedef struct AlterDomainStmt * new owner */ Node *def; /* definition of default or constraint */ DropBehavior behavior; /* RESTRICT or CASCADE for DROP cases */ -} AlterDomainStmt; +} AlterDomainStmt; /* ---------------------- @@ -878,14 +879,15 @@ typedef enum OnCommitAction ONCOMMIT_PRESERVE_ROWS, /* ON COMMIT PRESERVE ROWS (do nothing) */ ONCOMMIT_DELETE_ROWS, /* ON COMMIT DELETE ROWS */ ONCOMMIT_DROP /* ON COMMIT DROP */ -} OnCommitAction; +} OnCommitAction; typedef struct CreateStmt { NodeTag type; RangeVar *relation; /* relation to create */ List *tableElts; /* column definitions (list of ColumnDef) */ - List *inhRelations; /* relations to inherit from (list of inhRelation) */ + List *inhRelations; /* relations to inherit from (list of + * inhRelation) */ List *constraints; /* constraints (list of Constraint nodes) */ bool hasoids; /* should it have OIDs? */ OnCommitAction oncommit; /* what do we do at COMMIT? */ @@ -1094,7 +1096,7 @@ typedef struct AlterSeqStmt NodeTag type; RangeVar *sequence; /* the sequence to alter */ List *options; -} AlterSeqStmt; +} AlterSeqStmt; /* ---------------------- * Create {Aggregate|Operator|Type} Statement @@ -1220,7 +1222,7 @@ typedef struct DeclareCursorStmt char *portalname; /* name of the portal (cursor) */ int options; /* bitmask of options (see above) */ Node *query; /* the SELECT query */ -} DeclareCursorStmt; +} DeclareCursorStmt; /* ---------------------- * Close Portal Statement @@ -1244,7 +1246,7 @@ typedef enum FetchDirection /* for these, howMany indicates a position; only one row is fetched */ FETCH_ABSOLUTE, FETCH_RELATIVE -} FetchDirection; +} FetchDirection; #define FETCH_ALL LONG_MAX @@ -1269,8 +1271,9 @@ typedef struct IndexStmt char *accessMethod; /* name of access method (eg. btree) */ List *indexParams; /* a list of IndexElem */ Node *whereClause; /* qualification (partial-index predicate) */ - List *rangetable; /* range table for qual and/or expressions, - * filled in by transformStmt() */ + List *rangetable; /* range table for qual and/or + * expressions, filled in by + * transformStmt() */ bool unique; /* is index unique? */ bool primary; /* is index on primary key? */ bool isconstraint; /* is it from a CONSTRAINT clause? */ @@ -1349,7 +1352,8 @@ typedef struct RenameStmt RangeVar *relation; /* in case it's a table */ List *object; /* in case it's some other object */ List *objarg; /* argument types, if applicable */ - char *subname; /* name of contained object (column, rule, trigger, etc) */ + char *subname; /* name of contained object (column, rule, + * trigger, etc) */ char *newname; /* the new name */ ObjectType renameType; /* OBJECT_TABLE, OBJECT_COLUMN, etc */ } RenameStmt; @@ -1410,7 +1414,7 @@ typedef enum TransactionStmtKind TRANS_STMT_START, /* semantically identical to BEGIN */ TRANS_STMT_COMMIT, TRANS_STMT_ROLLBACK -} TransactionStmtKind; +} TransactionStmtKind; typedef struct TransactionStmt { @@ -1602,7 +1606,8 @@ typedef struct ConstraintsSetStmt typedef struct ReindexStmt { NodeTag type; - ObjectType kind; /* OBJECT_INDEX, OBJECT_TABLE, OBJECT_DATABASE */ + ObjectType kind; /* OBJECT_INDEX, OBJECT_TABLE, + * OBJECT_DATABASE */ RangeVar *relation; /* Table or index to reindex */ const char *name; /* name of database to reindex */ bool force; diff --git a/src/include/nodes/pg_list.h b/src/include/nodes/pg_list.h index 5bf17ceb14..4c8ae3440e 100644 --- a/src/include/nodes/pg_list.h +++ b/src/include/nodes/pg_list.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_list.h,v 1.37 2003/06/15 22:51:45 tgl Exp $ + * $Id: pg_list.h,v 1.38 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -137,7 +137,7 @@ typedef struct FastList { List *head; List *tail; -} FastList; +} FastList; #define FastListInit(fl) ( (fl)->head = (fl)->tail = NIL ) #define FastListFromList(fl, l) \ @@ -160,11 +160,11 @@ extern List *lappend(List *list, void *datum); extern List *lappendi(List *list, int datum); extern List *lappendo(List *list, Oid datum); extern List *nconc(List *list1, List *list2); -extern void FastAppend(FastList *fl, void *datum); -extern void FastAppendi(FastList *fl, int datum); -extern void FastAppendo(FastList *fl, Oid datum); -extern void FastConc(FastList *fl, List *cells); -extern void FastConcFast(FastList *fl, FastList *fl2); +extern void FastAppend(FastList * fl, void *datum); +extern void FastAppendi(FastList * fl, int datum); +extern void FastAppendo(FastList * fl, Oid datum); +extern void FastConc(FastList * fl, List *cells); +extern void FastConcFast(FastList * fl, FastList * fl2); extern void *nth(int n, List *l); extern int length(List *list); extern void *llast(List *list); diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 9db779d8bf..7a76cbba73 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: plannodes.h,v 1.65 2003/05/06 00:20:33 tgl Exp $ + * $Id: plannodes.h,v 1.66 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -68,8 +68,8 @@ typedef struct Plan * Information for management of parameter-change-driven rescanning * * extParam includes the paramIDs of all external PARAM_EXEC params - * affecting this plan node or its children. setParam params from - * the node's initPlans are not included, but their extParams are. + * affecting this plan node or its children. setParam params from the + * node's initPlans are not included, but their extParams are. * * allParam includes all the extParam paramIDs, plus the IDs of local * params that affect the node (i.e., the setParams of its initplans). @@ -315,12 +315,12 @@ typedef enum AggStrategy AGG_PLAIN, /* simple agg across all input rows */ AGG_SORTED, /* grouped agg, input must be sorted */ AGG_HASHED /* grouped agg, use internal hashtable */ -} AggStrategy; +} AggStrategy; typedef struct Agg { Plan plan; - AggStrategy aggstrategy; + AggStrategy aggstrategy; int numCols; /* number of grouping columns */ AttrNumber *grpColIdx; /* their indexes in the target list */ long numGroups; /* estimated number of groups in input */ diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 522ddc5f90..c747d6dbbc 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -10,7 +10,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: primnodes.h,v 1.87 2003/07/03 16:34:26 tgl Exp $ + * $Id: primnodes.h,v 1.88 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -49,7 +49,7 @@ * associated SortClause or GroupClause lists determine the semantics. * * resorigtbl/resorigcol identify the source of the column, if it is a - * simple reference to a column of a base table (or view). If it is not + * simple reference to a column of a base table (or view). If it is not * a simple reference, these fields are zeroes. * * If resjunk is true then the column is a working column (such as a sort key) @@ -63,8 +63,8 @@ typedef struct Resdom Oid restype; /* type of the value */ int32 restypmod; /* type-specific modifier of the value */ char *resname; /* name of the column (could be NULL) */ - Index ressortgroupref; /* nonzero if referenced by a - * sort/group clause */ + Index ressortgroupref;/* nonzero if referenced by a sort/group + * clause */ Oid resorigtbl; /* OID of column's source table */ AttrNumber resorigcol; /* column's number in source table */ bool resjunk; /* set to true to eliminate the attribute @@ -181,10 +181,10 @@ typedef struct Const Datum constvalue; /* the constant's value */ bool constisnull; /* whether the constant is null (if true, * constvalue is undefined) */ - bool constbyval; /* whether this datatype is passed by value. - * If true, then all the information is - * stored in the Datum. - * If false, then the Datum contains a + bool constbyval; /* whether this datatype is passed by + * value. If true, then all the + * information is stored in the Datum. If + * false, then the Datum contains a * pointer to the information. */ } Const; @@ -201,7 +201,7 @@ typedef struct Const * i.e. something like `$1', `$2' etc. * The number is contained in the `paramid' field. * - * PARAM_EXEC: The parameter is an internal executor parameter. + * PARAM_EXEC: The parameter is an internal executor parameter. * It has a number contained in the `paramid' field. * ---------------- */ @@ -277,7 +277,7 @@ typedef enum CoercionContext COERCION_IMPLICIT, /* coercion in context of expression */ COERCION_ASSIGNMENT, /* coercion in context of assignment */ COERCION_EXPLICIT /* explicit cast operation */ -} CoercionContext; +} CoercionContext; /* * CoercionForm - information showing how to display a function-call node @@ -288,7 +288,7 @@ typedef enum CoercionForm COERCE_EXPLICIT_CAST, /* display as an explicit cast */ COERCE_IMPLICIT_CAST, /* implicit cast, so hide it */ COERCE_DONTCARE /* special case for pathkeys */ -} CoercionForm; +} CoercionForm; /* * FuncExpr - expression node for a function call @@ -301,7 +301,7 @@ typedef struct FuncExpr bool funcretset; /* true if function returns set */ CoercionForm funcformat; /* how to display this function call */ List *args; /* arguments to the function */ -} FuncExpr; +} FuncExpr; /* * OpExpr - expression node for an operator invocation @@ -320,7 +320,7 @@ typedef struct OpExpr Oid opresulttype; /* PG_TYPE OID of result value */ bool opretset; /* true if operator returns set */ List *args; /* arguments to the operator (1 or 2) */ -} OpExpr; +} OpExpr; /* * DistinctExpr - expression node for "x IS DISTINCT FROM y" @@ -351,28 +351,28 @@ typedef struct ScalarArrayOpExpr Oid opfuncid; /* PG_PROC OID of underlying function */ bool useOr; /* true for ANY, false for ALL */ List *args; /* the scalar and array operands */ -} ScalarArrayOpExpr; +} ScalarArrayOpExpr; /* * BoolExpr - expression node for the basic Boolean operators AND, OR, NOT * * Notice the arguments are given as a List. For NOT, of course the list * must always have exactly one element. For AND and OR, the executor can - * handle any number of arguments. The parser treats AND and OR as binary + * handle any number of arguments. The parser treats AND and OR as binary * and so it only produces two-element lists, but the optimizer will flatten * trees of AND and OR nodes to produce longer lists when possible. */ typedef enum BoolExprType { AND_EXPR, OR_EXPR, NOT_EXPR -} BoolExprType; +} BoolExprType; typedef struct BoolExpr { Expr xpr; BoolExprType boolop; List *args; /* arguments to this expression */ -} BoolExpr; +} BoolExpr; /* ---------------- * SubLink @@ -405,7 +405,7 @@ typedef struct BoolExpr * * NOTE: in the raw output of gram.y, lefthand contains a list of raw * expressions; useOr and operOids are not filled in yet. Also, subselect - * is a raw parsetree. During parse analysis, the parser transforms the + * is a raw parsetree. During parse analysis, the parser transforms the * lefthand expression list using normal expression transformation rules. * It fills operOids with the OIDs representing the specific operator(s) * to apply to each pair of lefthand and targetlist expressions. @@ -452,13 +452,13 @@ typedef struct SubLink * (OpExpr trees) for the combining operators; their left-hand arguments are * the original lefthand expressions, and their right-hand arguments are * PARAM_EXEC Param nodes representing the outputs of the sub-select. - * (NOTE: runtime coercion functions may be inserted as well.) But if the + * (NOTE: runtime coercion functions may be inserted as well.) But if the * sub-select becomes an initplan rather than a subplan, these executable * expressions are part of the outer plan's expression tree (and the SubPlan * node itself is not). In this case "exprs" is NIL to avoid duplication. * * The planner also derives lists of the values that need to be passed into - * and out of the subplan. Input values are represented as a list "args" of + * and out of the subplan. Input values are represented as a list "args" of * expressions to be evaluated in the outer-query context (currently these * args are always just Vars, but in principle they could be any expression). * The values are assigned to the global PARAM_EXEC params indexed by parParam @@ -487,16 +487,17 @@ typedef struct SubPlan * (TopPlan node ?)... */ List *rtable; /* range table for subselect */ /* Information about execution strategy: */ - bool useHashTable; /* TRUE to store subselect output in a hash - * table (implies we are doing "IN") */ - bool unknownEqFalse; /* TRUE if it's okay to return FALSE when + bool useHashTable; /* TRUE to store subselect output in a + * hash table (implies we are doing "IN") */ + bool unknownEqFalse; /* TRUE if it's okay to return FALSE when * the spec result is UNKNOWN; this allows * much simpler handling of null values */ /* Information for passing params into and out of the subselect: */ /* setParam and parParam are lists of integers (param IDs) */ List *setParam; /* initplan subqueries have to set these * Params for parent plan */ - List *parParam; /* indices of input Params from parent plan */ + List *parParam; /* indices of input Params from parent + * plan */ List *args; /* exprs to pass as parParam values */ } SubPlan; @@ -539,7 +540,7 @@ typedef struct RelabelType Expr *arg; /* input expression */ Oid resulttype; /* output type of coercion expression */ int32 resulttypmod; /* output typmod (usually -1) */ - CoercionForm relabelformat; /* how to display this node */ + CoercionForm relabelformat; /* how to display this node */ } RelabelType; /* @@ -574,20 +575,20 @@ typedef struct ArrayExpr { Expr xpr; Oid array_typeid; /* type of expression result */ - Oid element_typeid; /* common type of expression elements */ + Oid element_typeid; /* common type of expression elements */ List *elements; /* the array elements */ int ndims; /* number of array dimensions */ -} ArrayExpr; +} ArrayExpr; /* * CoalesceExpr - a COALESCE expression */ typedef struct CoalesceExpr { - Expr xpr; - Oid coalescetype; /* type of expression result */ - List *args; /* the arguments */ -} CoalesceExpr; + Expr xpr; + Oid coalescetype; /* type of expression result */ + List *args; /* the arguments */ +} CoalesceExpr; /* * NullIfExpr - a NULLIF expression @@ -645,8 +646,8 @@ typedef struct BooleanTest * * CoerceToDomain represents the operation of coercing a value to a domain * type. At runtime (and not before) the precise set of constraints to be - * checked will be determined. If the value passes, it is returned as the - * result; if not, an error is raised. Note that this is equivalent to + * checked will be determined. If the value passes, it is returned as the + * result; if not, an error is raised. Note that this is equivalent to * RelabelType in the scenario where no constraints are applied. */ typedef struct CoerceToDomain @@ -655,12 +656,12 @@ typedef struct CoerceToDomain Expr *arg; /* input expression */ Oid resulttype; /* domain type ID (result type) */ int32 resulttypmod; /* output typmod (currently always -1) */ - CoercionForm coercionformat; /* how to display this node */ -} CoerceToDomain; + CoercionForm coercionformat; /* how to display this node */ +} CoerceToDomain; /* * Placeholder node for the value to be processed by a domain's check - * constraint. This is effectively like a Param, but can be implemented more + * constraint. This is effectively like a Param, but can be implemented more * simply since we need only one replacement value at a time. * * Note: the typeId/typeMod will be set from the domain's base type, not @@ -672,13 +673,13 @@ typedef struct CoerceToDomainValue Expr xpr; Oid typeId; /* type for substituted value */ int32 typeMod; /* typemod for substituted value */ -} CoerceToDomainValue; +} CoerceToDomainValue; /* * Placeholder node for a DEFAULT marker in an INSERT or UPDATE command. * * This is not an executable expression: it must be replaced by the actual - * column default expression during rewriting. But it is convenient to + * column default expression during rewriting. But it is convenient to * treat it as an expression node during parsing and rewriting. */ typedef struct SetToDefault @@ -686,7 +687,7 @@ typedef struct SetToDefault Expr xpr; Oid typeId; /* type for substituted value */ int32 typeMod; /* typemod for substituted value */ -} SetToDefault; +} SetToDefault; /* * TargetEntry - diff --git a/src/include/nodes/relation.h b/src/include/nodes/relation.h index 2ab9e0f6e7..158a23427c 100644 --- a/src/include/nodes/relation.h +++ b/src/include/nodes/relation.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: relation.h,v 1.82 2003/06/29 23:05:05 tgl Exp $ + * $Id: relation.h,v 1.83 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -43,7 +43,7 @@ typedef struct QualCost { Cost startup; /* one-time cost */ Cost per_tuple; /* per-evaluation cost */ -} QualCost; +} QualCost; /*---------- * RelOptInfo @@ -218,12 +218,13 @@ typedef struct RelOptInfo Relids index_outer_relids; /* other relids in indexable join * clauses */ List *index_inner_paths; /* InnerIndexscanInfo nodes */ + /* - * Inner indexscans are not in the main pathlist because they are - * not usable except in specific join contexts. We use the + * Inner indexscans are not in the main pathlist because they are not + * usable except in specific join contexts. We use the * index_inner_paths list just to avoid recomputing the best inner - * indexscan repeatedly for similar outer relations. See comments - * for InnerIndexscanInfo. + * indexscan repeatedly for similar outer relations. See comments for + * InnerIndexscanInfo. */ } RelOptInfo; @@ -266,7 +267,8 @@ typedef struct IndexOptInfo RegProcedure amcostestimate; /* OID of the access method's cost fcn */ - List *indexprs; /* expressions for non-simple index columns */ + List *indexprs; /* expressions for non-simple index + * columns */ List *indpred; /* predicate if a partial index, else NIL */ bool unique; /* true if a unique index */ @@ -413,7 +415,7 @@ typedef struct ResultPath Path path; Path *subpath; List *constantqual; -} ResultPath; +} ResultPath; /* * MaterialPath represents use of a Material plan node, i.e., caching of @@ -425,7 +427,7 @@ typedef struct MaterialPath { Path path; Path *subpath; -} MaterialPath; +} MaterialPath; /* * UniquePath represents elimination of distinct rows from the output of @@ -442,7 +444,7 @@ typedef struct UniquePath Path *subpath; bool use_hash; double rows; /* estimated number of result tuples */ -} UniquePath; +} UniquePath; /* * All join-type paths share these fields. @@ -661,7 +663,7 @@ typedef struct JoinInfo * relation includes all other relids appearing in those joinclauses. * The set of usable joinclauses, and thus the best inner indexscan, * thus varies depending on which outer relation we consider; so we have - * to recompute the best such path for every join. To avoid lots of + * to recompute the best such path for every join. To avoid lots of * redundant computation, we cache the results of such searches. For * each index we compute the set of possible otherrelids (all relids * appearing in joinquals that could become indexquals for this index). @@ -687,8 +689,8 @@ typedef struct InnerIndexscanInfo Relids other_relids; /* a set of relevant other relids */ bool isouterjoin; /* true if join is outer */ /* Best path for this lookup key: */ - Path *best_innerpath; /* best inner indexscan, or NULL if none */ -} InnerIndexscanInfo; + Path *best_innerpath; /* best inner indexscan, or NULL if none */ +} InnerIndexscanInfo; /* * IN clause info. @@ -704,11 +706,12 @@ typedef struct InClauseInfo NodeTag type; Relids lefthand; /* base relids in lefthand expressions */ Relids righthand; /* base relids coming from the subselect */ - List *sub_targetlist; /* targetlist of original RHS subquery */ + List *sub_targetlist; /* targetlist of original RHS subquery */ + /* - * Note: sub_targetlist is just a list of Vars or expressions; - * it does not contain TargetEntry nodes. + * Note: sub_targetlist is just a list of Vars or expressions; it does + * not contain TargetEntry nodes. */ -} InClauseInfo; +} InClauseInfo; #endif /* RELATION_H */ diff --git a/src/include/optimizer/clauses.h b/src/include/optimizer/clauses.h index 04add3c6f6..0384fafe97 100644 --- a/src/include/optimizer/clauses.h +++ b/src/include/optimizer/clauses.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: clauses.h,v 1.65 2003/06/25 21:30:33 momjian Exp $ + * $Id: clauses.h,v 1.66 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -24,7 +24,7 @@ extern Expr *make_opclause(Oid opno, Oid opresulttype, bool opretset, - Expr *leftop, Expr *rightop); + Expr *leftop, Expr *rightop); extern Node *get_leftop(Expr *clause); extern Node *get_rightop(Expr *clause); @@ -60,7 +60,7 @@ extern bool has_distinct_on_clause(Query *query); extern void clause_get_relids_vars(Node *clause, Relids *relids, List **vars); extern int NumRelids(Node *clause); -extern void CommuteClause(OpExpr *clause); +extern void CommuteClause(OpExpr * clause); extern Node *eval_const_expressions(Node *node); @@ -70,18 +70,18 @@ extern Node *expression_tree_mutator(Node *node, Node *(*mutator) (), void *context); /* flags bits for query_tree_walker and query_tree_mutator */ -#define QTW_IGNORE_RT_SUBQUERIES 0x01 /* subqueries in rtable */ -#define QTW_IGNORE_JOINALIASES 0x02 /* JOIN alias var lists */ -#define QTW_DONT_COPY_QUERY 0x04 /* do not copy top Query */ +#define QTW_IGNORE_RT_SUBQUERIES 0x01 /* subqueries in rtable */ +#define QTW_IGNORE_JOINALIASES 0x02 /* JOIN alias var lists */ +#define QTW_DONT_COPY_QUERY 0x04 /* do not copy top Query */ extern bool query_tree_walker(Query *query, bool (*walker) (), - void *context, int flags); + void *context, int flags); extern Query *query_tree_mutator(Query *query, Node *(*mutator) (), - void *context, int flags); + void *context, int flags); extern bool query_or_expression_tree_walker(Node *node, bool (*walker) (), - void *context, int flags); + void *context, int flags); extern Node *query_or_expression_tree_mutator(Node *node, Node *(*mutator) (), - void *context, int flags); + void *context, int flags); #endif /* CLAUSES_H */ diff --git a/src/include/optimizer/cost.h b/src/include/optimizer/cost.h index ad2122f46e..1f70101987 100644 --- a/src/include/optimizer/cost.h +++ b/src/include/optimizer/cost.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: cost.h,v 1.54 2003/07/14 22:35:54 tgl Exp $ + * $Id: cost.h,v 1.55 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -62,20 +62,20 @@ extern void cost_functionscan(Path *path, Query *root, extern void cost_sort(Path *path, Query *root, List *pathkeys, Cost input_cost, double tuples, int width); extern void cost_material(Path *path, - Cost input_cost, double tuples, int width); + Cost input_cost, double tuples, int width); extern void cost_agg(Path *path, Query *root, - AggStrategy aggstrategy, int numAggs, - int numGroupCols, double numGroups, - Cost input_startup_cost, Cost input_total_cost, - double input_tuples); + AggStrategy aggstrategy, int numAggs, + int numGroupCols, double numGroups, + Cost input_startup_cost, Cost input_total_cost, + double input_tuples); extern void cost_group(Path *path, Query *root, - int numGroupCols, double numGroups, - Cost input_startup_cost, Cost input_total_cost, - double input_tuples); + int numGroupCols, double numGroups, + Cost input_startup_cost, Cost input_total_cost, + double input_tuples); extern void cost_nestloop(NestPath *path, Query *root); extern void cost_mergejoin(MergePath *path, Query *root); extern void cost_hashjoin(HashPath *path, Query *root); -extern void cost_qual_eval(QualCost *cost, List *quals); +extern void cost_qual_eval(QualCost * cost, List *quals); extern void set_baserel_size_estimates(Query *root, RelOptInfo *rel); extern void set_joinrel_size_estimates(Query *root, RelOptInfo *rel, RelOptInfo *outer_rel, @@ -89,16 +89,16 @@ extern void set_function_size_estimates(Query *root, RelOptInfo *rel); * routines to compute clause selectivities */ extern Selectivity restrictlist_selectivity(Query *root, - List *restrictinfo_list, - int varRelid, - JoinType jointype); + List *restrictinfo_list, + int varRelid, + JoinType jointype); extern Selectivity clauselist_selectivity(Query *root, - List *clauses, - int varRelid, - JoinType jointype); + List *clauses, + int varRelid, + JoinType jointype); extern Selectivity clause_selectivity(Query *root, - Node *clause, - int varRelid, - JoinType jointype); + Node *clause, + int varRelid, + JoinType jointype); #endif /* COST_H */ diff --git a/src/include/optimizer/geqo_misc.h b/src/include/optimizer/geqo_misc.h index 5c276c0fb2..0db5f43234 100644 --- a/src/include/optimizer/geqo_misc.h +++ b/src/include/optimizer/geqo_misc.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: geqo_misc.h,v 1.22 2002/11/06 00:00:45 tgl Exp $ + * $Id: geqo_misc.h,v 1.23 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -31,7 +31,6 @@ extern void print_pool(FILE *fp, Pool *pool, int start, int stop); extern void print_gen(FILE *fp, Pool *pool, int generation); extern void print_edge_table(FILE *fp, Edge *edge_table, int num_gene); - #endif /* GEQO_DEBUG */ #endif /* GEQO_MISC_H */ diff --git a/src/include/optimizer/joininfo.h b/src/include/optimizer/joininfo.h index 6fd806bbaf..ae26e34d2a 100644 --- a/src/include/optimizer/joininfo.h +++ b/src/include/optimizer/joininfo.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: joininfo.h,v 1.23 2003/01/24 03:58:43 tgl Exp $ + * $Id: joininfo.h,v 1.24 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,10 +21,10 @@ extern JoinInfo *find_joininfo_node(RelOptInfo *this_rel, Relids join_relids); extern JoinInfo *make_joininfo_node(RelOptInfo *this_rel, Relids join_relids); extern void add_join_clause_to_rels(Query *root, - RestrictInfo *restrictinfo, - Relids join_relids); + RestrictInfo *restrictinfo, + Relids join_relids); extern void remove_join_clause_from_rels(Query *root, - RestrictInfo *restrictinfo, - Relids join_relids); + RestrictInfo *restrictinfo, + Relids join_relids); #endif /* JOININFO_H */ diff --git a/src/include/optimizer/pathnode.h b/src/include/optimizer/pathnode.h index 6d112a5cf0..c7b3004eac 100644 --- a/src/include/optimizer/pathnode.h +++ b/src/include/optimizer/pathnode.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pathnode.h,v 1.50 2003/02/15 20:12:41 tgl Exp $ + * $Id: pathnode.h,v 1.51 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,10 +37,10 @@ extern TidPath *create_tidscan_path(Query *root, RelOptInfo *rel, List *tideval); extern AppendPath *create_append_path(RelOptInfo *rel, List *subpaths); extern ResultPath *create_result_path(RelOptInfo *rel, Path *subpath, - List *constantqual); + List *constantqual); extern MaterialPath *create_material_path(RelOptInfo *rel, Path *subpath); extern UniquePath *create_unique_path(Query *root, RelOptInfo *rel, - Path *subpath); + Path *subpath); extern Path *create_subqueryscan_path(RelOptInfo *rel, List *pathkeys); extern Path *create_functionscan_path(Query *root, RelOptInfo *rel); @@ -78,10 +78,10 @@ extern void build_base_rel(Query *root, int relid); extern RelOptInfo *build_other_rel(Query *root, int relid); extern RelOptInfo *find_base_rel(Query *root, int relid); extern RelOptInfo *build_join_rel(Query *root, - Relids joinrelids, - RelOptInfo *outer_rel, - RelOptInfo *inner_rel, - JoinType jointype, - List **restrictlist_ptr); + Relids joinrelids, + RelOptInfo *outer_rel, + RelOptInfo *inner_rel, + JoinType jointype, + List **restrictlist_ptr); #endif /* PATHNODE_H */ diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h index b36e17f91d..b9be78c390 100644 --- a/src/include/optimizer/paths.h +++ b/src/include/optimizer/paths.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: paths.h,v 1.67 2003/05/26 00:11:28 tgl Exp $ + * $Id: paths.h,v 1.68 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,12 +37,12 @@ extern void debug_print_rel(Query *root, RelOptInfo *rel); */ extern void create_index_paths(Query *root, RelOptInfo *rel); extern Path *best_inner_indexscan(Query *root, RelOptInfo *rel, - Relids outer_relids, JoinType jointype); + Relids outer_relids, JoinType jointype); extern List *extract_or_indexqual_conditions(RelOptInfo *rel, IndexOptInfo *index, Expr *orsubclause); extern List *expand_indexqual_conditions(IndexOptInfo *index, - List *clausegroups); + List *clausegroups); /* * orindxpath.c @@ -73,8 +73,8 @@ extern void add_paths_to_joinrel(Query *root, RelOptInfo *joinrel, extern List *make_rels_by_joins(Query *root, int level, List **joinrels); extern RelOptInfo *make_jointree_rel(Query *root, Node *jtnode); extern RelOptInfo *make_join_rel(Query *root, - RelOptInfo *rel1, RelOptInfo *rel2, - JoinType jointype); + RelOptInfo *rel1, RelOptInfo *rel2, + JoinType jointype); /* * pathkeys.c @@ -106,7 +106,7 @@ extern List *build_index_pathkeys(Query *root, RelOptInfo *rel, IndexOptInfo *index, ScanDirection scandir); extern List *build_subquery_pathkeys(Query *root, RelOptInfo *rel, - Query *subquery); + Query *subquery); extern List *build_join_pathkeys(Query *root, RelOptInfo *joinrel, List *outer_pathkeys); diff --git a/src/include/optimizer/plancat.h b/src/include/optimizer/plancat.h index 8f7cfbe6ce..004ba12d6e 100644 --- a/src/include/optimizer/plancat.h +++ b/src/include/optimizer/plancat.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: plancat.h,v 1.30 2003/06/29 23:05:05 tgl Exp $ + * $Id: plancat.h,v 1.31 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -33,8 +33,8 @@ extern Selectivity restriction_selectivity(Query *root, int varRelid); extern Selectivity join_selectivity(Query *root, - Oid operator, - List *args, - JoinType jointype); + Oid operator, + List *args, + JoinType jointype); #endif /* PLANCAT_H */ diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 99c9470493..8f8022dc12 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: planmain.h,v 1.72 2003/06/29 23:05:05 tgl Exp $ + * $Id: planmain.h,v 1.73 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,7 +21,7 @@ * prototypes for plan/planmain.c */ extern void query_planner(Query *root, List *tlist, double tuple_fraction, - Path **cheapest_path, Path **sorted_path); + Path **cheapest_path, Path **sorted_path); /* * prototypes for plan/createplan.c @@ -31,18 +31,18 @@ extern SubqueryScan *make_subqueryscan(List *qptlist, List *qpqual, Index scanrelid, Plan *subplan); extern Append *make_append(List *appendplans, bool isTarget, List *tlist); extern Sort *make_sort_from_sortclauses(Query *root, List *tlist, - Plan *lefttree, List *sortcls); + Plan *lefttree, List *sortcls); extern Sort *make_sort_from_groupcols(Query *root, List *groupcls, - AttrNumber *grpColIdx, Plan *lefttree); + AttrNumber *grpColIdx, Plan *lefttree); extern Agg *make_agg(Query *root, List *tlist, List *qual, - AggStrategy aggstrategy, - int numGroupCols, AttrNumber *grpColIdx, - long numGroups, int numAggs, - Plan *lefttree); + AggStrategy aggstrategy, + int numGroupCols, AttrNumber *grpColIdx, + long numGroups, int numAggs, + Plan *lefttree); extern Group *make_group(Query *root, List *tlist, - int numGroupCols, AttrNumber *grpColIdx, - double numGroups, - Plan *lefttree); + int numGroupCols, AttrNumber *grpColIdx, + double numGroups, + Plan *lefttree); extern Material *make_material(List *tlist, Plan *lefttree); extern Plan *materialize_finished_plan(Plan *subplan); extern Unique *make_unique(List *tlist, Plan *lefttree, List *distinctList); @@ -59,16 +59,16 @@ extern void add_base_rels_to_query(Query *root, Node *jtnode); extern void build_base_rel_tlists(Query *root, List *final_tlist); extern Relids distribute_quals_to_rels(Query *root, Node *jtnode); extern void process_implied_equality(Query *root, - Node *item1, Node *item2, - Oid sortop1, Oid sortop2, - Relids item1_relids, Relids item2_relids, - bool delete_it); + Node *item1, Node *item2, + Oid sortop1, Oid sortop2, + Relids item1_relids, Relids item2_relids, + bool delete_it); /* * prototypes for plan/setrefs.c */ extern void set_plan_references(Plan *plan, List *rtable); extern void fix_opfuncids(Node *node); -extern void set_opfuncid(OpExpr *opexpr); +extern void set_opfuncid(OpExpr * opexpr); #endif /* PLANMAIN_H */ diff --git a/src/include/optimizer/prep.h b/src/include/optimizer/prep.h index 52d045c51a..f25a3c79e3 100644 --- a/src/include/optimizer/prep.h +++ b/src/include/optimizer/prep.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: prep.h,v 1.39 2003/04/24 23:43:09 tgl Exp $ + * $Id: prep.h,v 1.40 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -53,7 +53,7 @@ extern Plan *plan_set_operations(Query *parse); extern List *find_all_inheritors(Oid parentrel); extern List *expand_inherited_rtentry(Query *parse, Index rti, - bool dup_parent); + bool dup_parent); extern Node *adjust_inherited_attrs(Node *node, Index old_rt_index, Oid old_relid, diff --git a/src/include/optimizer/restrictinfo.h b/src/include/optimizer/restrictinfo.h index 19c3435c3e..c4a04bf948 100644 --- a/src/include/optimizer/restrictinfo.h +++ b/src/include/optimizer/restrictinfo.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: restrictinfo.h,v 1.17 2003/06/15 22:51:45 tgl Exp $ + * $Id: restrictinfo.h,v 1.18 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,11 +21,11 @@ extern List *get_actual_clauses(List *restrictinfo_list); extern void get_actual_join_clauses(List *restrictinfo_list, List **joinquals, List **otherquals); extern List *remove_redundant_join_clauses(Query *root, - List *restrictinfo_list, - JoinType jointype); + List *restrictinfo_list, + JoinType jointype); extern List *select_nonredundant_join_clauses(Query *root, - List *restrictinfo_list, - List *reference_list, - JoinType jointype); + List *restrictinfo_list, + List *reference_list, + JoinType jointype); #endif /* RESTRICTINFO_H */ diff --git a/src/include/optimizer/tlist.h b/src/include/optimizer/tlist.h index d22c78f8d8..cdca747f7b 100644 --- a/src/include/optimizer/tlist.h +++ b/src/include/optimizer/tlist.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: tlist.h,v 1.36 2003/06/29 23:05:05 tgl Exp $ + * $Id: tlist.h,v 1.37 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,6 +30,6 @@ extern TargetEntry *get_sortgroupclause_tle(SortClause *sortClause, extern Node *get_sortgroupclause_expr(SortClause *sortClause, List *targetList); extern List *get_sortgrouplist_exprs(List *sortClauses, - List *targetList); + List *targetList); #endif /* TLIST_H */ diff --git a/src/include/parser/analyze.h b/src/include/parser/analyze.h index b7d6a7d665..1b97706e0f 100644 --- a/src/include/parser/analyze.h +++ b/src/include/parser/analyze.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: analyze.h,v 1.21 2003/04/29 22:13:11 tgl Exp $ + * $Id: analyze.h,v 1.22 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -18,7 +18,7 @@ extern List *parse_analyze(Node *parseTree, Oid *paramTypes, int numParams); extern List *parse_analyze_varparams(Node *parseTree, Oid **paramTypes, - int *numParams); + int *numParams); extern List *parse_sub_analyze(Node *parseTree, ParseState *parentParseState); extern List *analyzeCreateSchemaStmt(CreateSchemaStmt *stmt); diff --git a/src/include/parser/parse_agg.h b/src/include/parser/parse_agg.h index 79f226fb89..4b8ab5d427 100644 --- a/src/include/parser/parse_agg.h +++ b/src/include/parser/parse_agg.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: parse_agg.h,v 1.27 2003/07/01 19:10:53 tgl Exp $ + * $Id: parse_agg.h,v 1.28 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -20,11 +20,11 @@ extern void transformAggregateCall(ParseState *pstate, Aggref *agg); extern void parseCheckAggregates(ParseState *pstate, Query *qry); extern void build_aggregate_fnexprs(Oid agg_input_type, - Oid agg_state_type, - Oid agg_result_type, - Oid transfn_oid, - Oid finalfn_oid, - Expr **transfnexpr, - Expr **finalfnexpr); + Oid agg_state_type, + Oid agg_result_type, + Oid transfn_oid, + Oid finalfn_oid, + Expr **transfnexpr, + Expr **finalfnexpr); #endif /* PARSE_AGG_H */ diff --git a/src/include/parser/parse_clause.h b/src/include/parser/parse_clause.h index 6f4f87a8b6..d7d8a16e96 100644 --- a/src/include/parser/parse_clause.h +++ b/src/include/parser/parse_clause.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: parse_clause.h,v 1.33 2003/07/03 19:07:53 tgl Exp $ + * $Id: parse_clause.h,v 1.34 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -22,9 +22,9 @@ extern int setTargetTable(ParseState *pstate, RangeVar *relation, extern bool interpretInhOption(InhOption inhOpt); extern Node *transformWhereClause(ParseState *pstate, Node *clause, - const char *constructName); + const char *constructName); extern Node *transformLimitClause(ParseState *pstate, Node *clause, - const char *constructName); + const char *constructName); extern List *transformGroupClause(ParseState *pstate, List *grouplist, List *targetlist, List *sortClause); extern List *transformSortClause(ParseState *pstate, List *orderlist, @@ -33,8 +33,8 @@ extern List *transformDistinctClause(ParseState *pstate, List *distinctlist, List *targetlist, List **sortClause); extern List *addAllTargetsToSortList(ParseState *pstate, - List *sortlist, List *targetlist, - bool resolveUnknown); + List *sortlist, List *targetlist, + bool resolveUnknown); extern Index assignSortGroupRef(TargetEntry *tle, List *tlist); extern bool targetIsInSortList(TargetEntry *tle, List *sortList); diff --git a/src/include/parser/parse_coerce.h b/src/include/parser/parse_coerce.h index 88d7b614bb..36c5c7eaf2 100644 --- a/src/include/parser/parse_coerce.h +++ b/src/include/parser/parse_coerce.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: parse_coerce.h,v 1.53 2003/07/03 19:07:54 tgl Exp $ + * $Id: parse_coerce.h,v 1.54 2003/08/04 00:43:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -40,42 +40,42 @@ extern bool IsPreferredType(CATEGORY category, Oid type); extern CATEGORY TypeCategory(Oid type); extern Node *coerce_to_target_type(ParseState *pstate, - Node *expr, Oid exprtype, - Oid targettype, int32 targettypmod, - CoercionContext ccontext, - CoercionForm cformat); + Node *expr, Oid exprtype, + Oid targettype, int32 targettypmod, + CoercionContext ccontext, + CoercionForm cformat); extern bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, - CoercionContext ccontext); + CoercionContext ccontext); extern Node *coerce_type(ParseState *pstate, Node *node, - Oid inputTypeId, Oid targetTypeId, - CoercionContext ccontext, CoercionForm cformat); + Oid inputTypeId, Oid targetTypeId, + CoercionContext ccontext, CoercionForm cformat); extern Node *coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId, - CoercionForm cformat); + CoercionForm cformat); extern Node *coerce_to_boolean(ParseState *pstate, Node *node, - const char *constructName); + const char *constructName); extern Node *coerce_to_integer(ParseState *pstate, Node *node, - const char *constructName); + const char *constructName); extern Oid select_common_type(List *typeids, const char *context); extern Node *coerce_to_common_type(ParseState *pstate, Node *node, - Oid targetTypeId, - const char *context); + Oid targetTypeId, + const char *context); extern bool check_generic_type_consistency(Oid *actual_arg_types, - Oid *declared_arg_types, - int nargs); + Oid *declared_arg_types, + int nargs); extern Oid enforce_generic_type_consistency(Oid *actual_arg_types, - Oid *declared_arg_types, - int nargs, - Oid rettype); + Oid *declared_arg_types, + int nargs, + Oid rettype); extern Oid resolve_generic_type(Oid declared_type, - Oid context_actual_type, - Oid context_declared_type); + Oid context_actual_type, + Oid context_declared_type); extern bool find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, - CoercionContext ccontext, - Oid *funcid); + CoercionContext ccontext, + Oid *funcid); extern Oid find_typmod_coercion_function(Oid typeId, int *nargs); #endif /* PARSE_COERCE_H */ diff --git a/src/include/parser/parse_func.h b/src/include/parser/parse_func.h index d4046b988f..9393c1aaa4 100644 --- a/src/include/parser/parse_func.h +++ b/src/include/parser/parse_func.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: parse_func.h,v 1.48 2003/07/20 21:56:35 tgl Exp $ + * $Id: parse_func.h,v 1.49 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -50,32 +50,32 @@ extern FuncDetailCode func_get_detail(List *funcname, List *fargs, Oid *funcid, Oid *rettype, bool *retset, Oid **true_typeids); -extern int func_match_argtypes(int nargs, - Oid *input_typeids, - FuncCandidateList raw_candidates, - FuncCandidateList *candidates); +extern int func_match_argtypes(int nargs, + Oid *input_typeids, + FuncCandidateList raw_candidates, + FuncCandidateList *candidates); extern FuncCandidateList func_select_candidate(int nargs, - Oid *input_typeids, - FuncCandidateList candidates); + Oid *input_typeids, + FuncCandidateList candidates); extern bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId); extern void make_fn_arguments(ParseState *pstate, - List *fargs, - Oid *actual_arg_types, - Oid *declared_arg_types); + List *fargs, + Oid *actual_arg_types, + Oid *declared_arg_types); extern const char *funcname_signature_string(const char *funcname, - int nargs, const Oid *argtypes); + int nargs, const Oid *argtypes); extern const char *func_signature_string(List *funcname, - int nargs, const Oid *argtypes); + int nargs, const Oid *argtypes); -extern Oid find_aggregate_func(List *aggname, Oid basetype, bool noError); +extern Oid find_aggregate_func(List *aggname, Oid basetype, bool noError); -extern Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, - bool noError); +extern Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, + bool noError); extern Oid LookupFuncNameTypeNames(List *funcname, List *argtypes, - bool noError); + bool noError); #endif /* PARSE_FUNC_H */ diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index 1f52963e5c..339a07ae0c 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: parse_node.h,v 1.35 2003/04/29 22:13:11 tgl Exp $ + * $Id: parse_node.h,v 1.36 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -54,7 +54,8 @@ typedef struct ParseState int p_numparams; /* allocated size of p_paramtypes[] */ int p_next_resno; /* next targetlist resno to assign */ List *p_forUpdate; /* FOR UPDATE clause, if any (see gram.y) */ - Node *p_value_substitute; /* what to replace VALUE with, if any */ + Node *p_value_substitute; /* what to replace VALUE with, if + * any */ bool p_variableparams; bool p_hasAggs; bool p_hasSubLinks; diff --git a/src/include/parser/parse_oper.h b/src/include/parser/parse_oper.h index a53b1a5a23..e2d43f165a 100644 --- a/src/include/parser/parse_oper.h +++ b/src/include/parser/parse_oper.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: parse_oper.h,v 1.30 2003/07/04 02:51:34 tgl Exp $ + * $Id: parse_oper.h,v 1.31 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -21,10 +21,10 @@ typedef HeapTuple Operator; /* Routines to look up an operator given name and exact input type(s) */ -extern Oid LookupOperName(List *opername, Oid oprleft, Oid oprright, - bool noError); +extern Oid LookupOperName(List *opername, Oid oprleft, Oid oprright, + bool noError); extern Oid LookupOperNameTypeNames(List *opername, TypeName *oprleft, - TypeName *oprright, bool noError); + TypeName *oprright, bool noError); /* Routines to find operators matching a name and given input types */ /* NB: the selected operator may require coercion of the input types! */ @@ -54,12 +54,12 @@ extern Oid oprfuncid(Operator op); /* Build expression tree for an operator invocation */ extern Expr *make_op(ParseState *pstate, List *opname, - Node *ltree, Node *rtree); + Node *ltree, Node *rtree); extern Expr *make_scalar_array_op(ParseState *pstate, List *opname, - bool useOr, - Node *ltree, Node *rtree); + bool useOr, + Node *ltree, Node *rtree); extern Expr *make_op_expr(ParseState *pstate, Operator op, - Node *ltree, Node *rtree, - Oid ltypeId, Oid rtypeId); + Node *ltree, Node *rtree, + Oid ltypeId, Oid rtypeId); #endif /* PARSE_OPER_H */ diff --git a/src/include/pg_config_manual.h b/src/include/pg_config_manual.h index 3bf316a580..451ef351e6 100644 --- a/src/include/pg_config_manual.h +++ b/src/include/pg_config_manual.h @@ -3,10 +3,10 @@ * * This file contains various configuration symbols and limits. In * all cases, changing them is only useful in very rare situations or - * for developers. If you edit any of these, be sure to do a *full* + * for developers. If you edit any of these, be sure to do a *full* * rebuild (and an initdb if noted). * - * $Id: pg_config_manual.h,v 1.4 2003/06/12 07:36:51 momjian Exp $ + * $Id: pg_config_manual.h,v 1.5 2003/08/04 00:43:29 momjian Exp $ *------------------------------------------------------------------------ */ @@ -41,7 +41,7 @@ * * Changing RELSEG_SIZE requires an initdb. */ -#define RELSEG_SIZE (0x40000000 / BLCKSZ) +#define RELSEG_SIZE (0x40000000 / BLCKSZ) /* * Maximum number of columns in an index and maximum number of @@ -59,7 +59,7 @@ /* * Define this to make libpgtcl's "pg_result -assign" command process * C-style backslash sequences in returned tuple data and convert - * PostgreSQL array values into Tcl lists. CAUTION: This conversion + * PostgreSQL array values into Tcl lists. CAUTION: This conversion * is *wrong* unless you install the routines in * contrib/string/string_io to make the server produce C-style * backslash sequences in the first place. @@ -69,7 +69,7 @@ /* * User locks are handled totally on the application side as long term * cooperative locks which extend beyond the normal transaction - * boundaries. Their purpose is to indicate to an application that + * boundaries. Their purpose is to indicate to an application that * someone is `working' on an item. Define this flag to enable user * locks. You will need the loadable module user-locks.c to use this * feature. @@ -84,8 +84,8 @@ /* * Define this if you want to allow the lo_import and lo_export SQL - * functions to be executed by ordinary users. By default these - * functions are only available to the Postgres superuser. CAUTION: + * functions to be executed by ordinary users. By default these + * functions are only available to the Postgres superuser. CAUTION: * These functions are SECURITY HOLES since they can read and write * any file that the PostgreSQL server has permission to access. If * you turn this on, don't say we didn't warn you. @@ -130,7 +130,7 @@ * Disable UNIX sockets for those operating system. */ #if defined(__QNX__) || defined(__BEOS__) || defined(WIN32) -# undef HAVE_UNIX_SOCKETS +#undef HAVE_UNIX_SOCKETS #endif /* @@ -138,20 +138,20 @@ */ #if !defined(__QNX__) && !defined(__BEOS__) && \ !defined(__CYGWIN__) && !defined(WIN32) -# define HAVE_WORKING_LINK 1 +#define HAVE_WORKING_LINK 1 #endif - + /* * Define this if your operating system has _timezone rather than timezone */ #if defined(__CYGWIN__) || defined(WIN32) -# define HAVE_INT_TIMEZONE /* has int _timezone */ -# define HAVE_UNDERSCORE_TIMEZONE 1 +#define HAVE_INT_TIMEZONE /* has int _timezone */ +#define HAVE_UNDERSCORE_TIMEZONE 1 #endif - + /* * This is the default directory in which AF_UNIX socket files are - * placed. Caution: changing this risks breaking your existing client + * placed. Caution: changing this risks breaking your existing client * applications, which are likely to continue to look in the old * directory. But if you just hate the idea of sockets in /tmp, * here's where to twiddle it. You can also override this at runtime @@ -170,7 +170,7 @@ * MAX_RANDOM_VALUE. Currently, all known implementations yield * 0..2^31-1, so we just hardwire this constant. We could do a * configure test if it proves to be necessary. CAUTION: Think not to - * replace this with RAND_MAX. RAND_MAX defines the maximum value of + * replace this with RAND_MAX. RAND_MAX defines the maximum value of * the older rand() function, which is often different from --- and * considerably inferior to --- random(). */ @@ -187,7 +187,7 @@ /* * Define this to cause pfree()'d memory to be cleared immediately, to * facilitate catching bugs that refer to already-freed values. XXX - * Right now, this gets defined automatically if --enable-cassert. In + * Right now, this gets defined automatically if --enable-cassert. In * the long term it probably doesn't need to be on by default. */ #ifdef USE_ASSERT_CHECKING @@ -196,11 +196,11 @@ /* * Define this to check memory allocation errors (scribbling on more - * bytes than were allocated). Right now, this gets defined + * bytes than were allocated). Right now, this gets defined * automatically if --enable-cassert. In the long term it probably * doesn't need to be on by default. */ -#ifdef USE_ASSERT_CHECKING +#ifdef USE_ASSERT_CHECKING #define MEMORY_CONTEXT_CHECKING #endif @@ -221,7 +221,7 @@ */ /* #define IPORTAL_DEBUG */ /* #define HEAPDEBUGALL */ -/* #define ISTRATDEBUG */ +/* #define ISTRATDEBUG */ /* #define ACLDEBUG */ /* #define RTDEBUG */ /* #define GISTDEBUG */ diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 568cf878e4..cc76d67d64 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -5,7 +5,7 @@ * * Copyright (c) 2001-2003, PostgreSQL Global Development Group * - * $Id: pgstat.h,v 1.15 2003/04/27 20:09:44 tgl Exp $ + * $Id: pgstat.h,v 1.16 2003/08/04 00:43:29 momjian Exp $ * ---------- */ #ifndef PGSTAT_H @@ -38,7 +38,7 @@ #define PGSTAT_DESTROY_COUNT (PGSTAT_DESTROY_DELAY / PGSTAT_STAT_INTERVAL) -#define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart */ +#define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart */ /* a failed statistics collector; in seconds. */ /* ---------- diff --git a/src/include/port.h b/src/include/port.h index c1bbfd718c..972f886f40 100644 --- a/src/include/port.h +++ b/src/include/port.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: port.h,v 1.8 2003/06/24 00:44:29 momjian Exp $ + * $Id: port.h,v 1.9 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -18,14 +18,14 @@ #endif /* Portable path handling for Unix/Win32 */ -bool is_absolute_path(const char *filename); -char *first_path_separator(const char *filename); -char *last_path_separator(const char *filename); -char *get_progname(char *argv0); +bool is_absolute_path(const char *filename); +char *first_path_separator(const char *filename); +char *last_path_separator(const char *filename); +char *get_progname(char *argv0); #if defined(bsdi) || defined(netbsd) -int fseeko(FILE *stream, off_t offset, int whence); -off_t ftello(FILE *stream); +int fseeko(FILE *stream, off_t offset, int whence); +off_t ftello(FILE *stream); #endif #ifdef WIN32 @@ -33,15 +33,17 @@ off_t ftello(FILE *stream); * Win32 doesn't have reliable rename/unlink during concurrent access */ #ifndef FRONTEND -int pgrename(const char *from, const char *to); -int pgunlink(const char *path); +int pgrename(const char *from, const char *to); +int pgunlink(const char *path); + #define rename(from, to) pgrename(from, to) #define unlink(path) pgunlink(path) #endif -extern int copydir(char *fromdir,char *todir); +extern int copydir(char *fromdir, char *todir); + /* Last parameter not used */ -extern int gettimeofday(struct timeval *tp, struct timezone *tzp); +extern int gettimeofday(struct timeval * tp, struct timezone * tzp); #else @@ -49,9 +51,9 @@ extern int gettimeofday(struct timeval *tp, struct timezone *tzp); * Win32 requires a special close for sockets and pipes, while on Unix * close() does them all. */ -#define closesocket close +#define closesocket close #endif - + /* * Default "extern" declarations or macro substitutes for library routines. * When necessary, these routines are provided by files in src/port/. @@ -66,15 +68,15 @@ extern char *crypt(const char *key, const char *setting); #endif #ifndef HAVE_GETOPT -extern int getopt(int nargc, char *const *nargv, const char *ostr); +extern int getopt(int nargc, char *const * nargv, const char *ostr); #endif #ifndef HAVE_ISINF -extern int isinf(double x); +extern int isinf(double x); #endif #if !defined(HAVE_GETHOSTNAME) && defined(KRB4) -extern int gethostname(char *name, int namelen); +extern int gethostname(char *name, int namelen); #endif #ifndef HAVE_RINT @@ -83,14 +85,14 @@ extern double rint(double x); #ifndef HAVE_INET_ATON #if !defined(_MSC_VER) && !defined(__BORLANDC__) -# include -# include +#include +#include #endif -extern int inet_aton(const char *cp, struct in_addr * addr); +extern int inet_aton(const char *cp, struct in_addr * addr); #endif #ifndef HAVE_STRCASECMP -extern int strcasecmp(char *s1, char *s2); +extern int strcasecmp(char *s1, char *s2); #endif #ifndef HAVE_STRDUP @@ -108,11 +110,11 @@ extern void srandom(unsigned int seed); /* thread.h */ extern char *pqStrerror(int errnum, char *strerrbuf, size_t buflen); -extern int pqGetpwuid(uid_t uid, struct passwd *resultbuf, char *buffer, - size_t buflen, struct passwd **result); +extern int pqGetpwuid(uid_t uid, struct passwd * resultbuf, char *buffer, + size_t buflen, struct passwd ** result); extern int pqGethostbyname(const char *name, - struct hostent *resbuf, - char *buf, size_t buflen, - struct hostent **result, - int *herrno); + struct hostent * resbuf, + char *buf, size_t buflen, + struct hostent ** result, + int *herrno); diff --git a/src/include/port/bsdi.h b/src/include/port/bsdi.h index 3a2aa59d09..f486536113 100644 --- a/src/include/port/bsdi.h +++ b/src/include/port/bsdi.h @@ -8,4 +8,3 @@ #define HAS_TEST_AND_SET typedef unsigned char slock_t; - diff --git a/src/include/port/cygwin.h b/src/include/port/cygwin.h index c703f59c62..2b818941ef 100644 --- a/src/include/port/cygwin.h +++ b/src/include/port/cygwin.h @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/include/port/cygwin.h,v 1.3 2003/05/22 17:20:28 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/include/port/cygwin.h,v 1.4 2003/08/04 00:43:32 momjian Exp $ */ #define HAS_TEST_AND_SET typedef unsigned char slock_t; @@ -20,4 +20,5 @@ typedef unsigned char slock_t; #define DLLIMPORT __declspec (dllexport) #else #define DLLIMPORT __declspec (dllimport) + #endif diff --git a/src/include/port/freebsd.h b/src/include/port/freebsd.h index aba5c72fe6..7729fa5b9b 100644 --- a/src/include/port/freebsd.h +++ b/src/include/port/freebsd.h @@ -44,4 +44,5 @@ typedef unsigned long slock_t; #if defined(__powerpc__) #define HAS_TEST_AND_SET typedef unsigned int slock_t; + #endif diff --git a/src/include/port/hpux.h b/src/include/port/hpux.h index 83296d852e..28883ad4b1 100644 --- a/src/include/port/hpux.h +++ b/src/include/port/hpux.h @@ -31,4 +31,5 @@ typedef unsigned int slock_t; #else #error unrecognized CPU type for HP-UX + #endif diff --git a/src/include/port/netbsd.h b/src/include/port/netbsd.h index aba5c72fe6..7729fa5b9b 100644 --- a/src/include/port/netbsd.h +++ b/src/include/port/netbsd.h @@ -44,4 +44,5 @@ typedef unsigned long slock_t; #if defined(__powerpc__) #define HAS_TEST_AND_SET typedef unsigned int slock_t; + #endif diff --git a/src/include/port/openbsd.h b/src/include/port/openbsd.h index aba5c72fe6..7729fa5b9b 100644 --- a/src/include/port/openbsd.h +++ b/src/include/port/openbsd.h @@ -44,4 +44,5 @@ typedef unsigned long slock_t; #if defined(__powerpc__) #define HAS_TEST_AND_SET typedef unsigned int slock_t; + #endif diff --git a/src/include/port/win32.h b/src/include/port/win32.h index 747a2d757c..7ffff9b303 100644 --- a/src/include/port/win32.h +++ b/src/include/port/win32.h @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/include/port/win32.h,v 1.11 2003/05/16 04:59:22 momjian Exp $ */ +/* $Header: /cvsroot/pgsql/src/include/port/win32.h,v 1.12 2003/08/04 00:43:32 momjian Exp $ */ /* undefine and redefine after #include */ #undef mkdir @@ -38,7 +38,6 @@ #else /* not CYGWIN, not MSVC */ #define DLLIMPORT - #endif /* @@ -68,14 +67,14 @@ */ struct shmid_ds { - int dummy; - int shm_nattch; + int dummy; + int shm_nattch; }; -int shmdt(const void *shmaddr); -void* shmat(int memId, void* shmaddr, int flag); -int shmctl(int shmid, int flag, struct shmid_ds * dummy); -int shmget(int memKey, int size, int flag); +int shmdt(const void *shmaddr); +void *shmat(int memId, void *shmaddr, int flag); +int shmctl(int shmid, int flag, struct shmid_ds * dummy); +int shmget(int memKey, int size, int flag); /* @@ -83,45 +82,46 @@ int shmget(int memKey, int size, int flag); */ union semun { - int val; + int val; struct semid_ds *buf; unsigned short *array; }; struct sembuf { - int sem_flg; - int sem_op; - int sem_num; + int sem_flg; + int sem_op; + int sem_num; }; -int semctl(int semId, int semNum, int flag, union semun); -int semget(int semKey, int semNum, int flags); -int semop(int semId, struct sembuf * sops, int flag); +int semctl(int semId, int semNum, int flag, union semun); +int semget(int semKey, int semNum, int flags); +int semop(int semId, struct sembuf * sops, int flag); #define sleep(sec) (Sleep(sec * 1000), /* no return value */ 0) /* Some extra signals */ #define SIGHUP 1 -#define SIGQUIT 3 -#define SIGTRAP 5 -#define SIGABRT 22 /* Set to match W32 value -- not UNIX value */ -#define SIGKILL 9 -#define SIGPIPE 13 -#define SIGALRM 14 -#define SIGSTOP 17 -#define SIGCONT 19 -#define SIGCHLD 20 -#define SIGTTIN 21 -#define SIGTTOU 22 /* Same as SIGABRT -- no problem, I hope */ -#define SIGWINCH 28 -#define SIGUSR1 30 -#define SIGUSR2 31 +#define SIGQUIT 3 +#define SIGTRAP 5 +#define SIGABRT 22 /* Set to match W32 value -- not UNIX + * value */ +#define SIGKILL 9 +#define SIGPIPE 13 +#define SIGALRM 14 +#define SIGSTOP 17 +#define SIGCONT 19 +#define SIGCHLD 20 +#define SIGTTIN 21 +#define SIGTTOU 22 /* Same as SIGABRT -- no problem, I hope */ +#define SIGWINCH 28 +#define SIGUSR1 30 +#define SIGUSR2 31 struct timezone { - int tz_minuteswest; /* Minutes west of GMT. */ - int tz_dsttime; /* Nonzero if DST is ever in effect. */ + int tz_minuteswest; /* Minutes west of GMT. */ + int tz_dsttime; /* Nonzero if DST is ever in effect. */ }; /* FROM SRA */ @@ -163,4 +163,3 @@ struct timezone #define EWOULDBLOCK WSAEWOULDBLOCK #define ECONNRESET WSAECONNRESET #define EINPROGRESS WSAEINPROGRESS - diff --git a/src/include/port/win32/dlfcn.h b/src/include/port/win32/dlfcn.h index e69de29bb2..8b13789179 100644 --- a/src/include/port/win32/dlfcn.h +++ b/src/include/port/win32/dlfcn.h @@ -0,0 +1 @@ + diff --git a/src/include/port/win32/grp.h b/src/include/port/win32/grp.h index e69de29bb2..8b13789179 100644 --- a/src/include/port/win32/grp.h +++ b/src/include/port/win32/grp.h @@ -0,0 +1 @@ + diff --git a/src/include/port/win32/netdb.h b/src/include/port/win32/netdb.h index e69de29bb2..8b13789179 100644 --- a/src/include/port/win32/netdb.h +++ b/src/include/port/win32/netdb.h @@ -0,0 +1 @@ + diff --git a/src/include/port/win32/netinet/in.h b/src/include/port/win32/netinet/in.h index 52db5248cb..dc979c0537 100644 --- a/src/include/port/win32/netinet/in.h +++ b/src/include/port/win32/netinet/in.h @@ -1,2 +1 @@ #include - diff --git a/src/include/port/win32/pwd.h b/src/include/port/win32/pwd.h index e69de29bb2..8b13789179 100644 --- a/src/include/port/win32/pwd.h +++ b/src/include/port/win32/pwd.h @@ -0,0 +1 @@ + diff --git a/src/include/port/win32/sys/socket.h b/src/include/port/win32/sys/socket.h index 93df14ed7c..86950699e4 100644 --- a/src/include/port/win32/sys/socket.h +++ b/src/include/port/win32/sys/socket.h @@ -12,4 +12,5 @@ /* Restore old ERROR value */ #ifdef PGERROR #define ERROR PGERROR + #endif diff --git a/src/include/port/win32/sys/wait.h b/src/include/port/win32/sys/wait.h index e69de29bb2..8b13789179 100644 --- a/src/include/port/win32/sys/wait.h +++ b/src/include/port/win32/sys/wait.h @@ -0,0 +1 @@ + diff --git a/src/include/postgres.h b/src/include/postgres.h index 3d2da911d2..8c40afc956 100644 --- a/src/include/postgres.h +++ b/src/include/postgres.h @@ -10,7 +10,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1995, Regents of the University of California * - * $Id: postgres.h,v 1.63 2003/04/06 22:45:23 petere Exp $ + * $Id: postgres.h,v 1.64 2003/08/04 00:43:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -130,6 +130,7 @@ typedef struct varattrib */ typedef unsigned long Datum; /* XXX sizeof(long) >= sizeof(void *) */ + #define SIZEOF_DATUM SIZEOF_UNSIGNED_LONG typedef Datum *DatumPtr; diff --git a/src/include/regex/regcustom.h b/src/include/regex/regcustom.h index 305243296f..1089126a3a 100644 --- a/src/include/regex/regcustom.h +++ b/src/include/regex/regcustom.h @@ -1,19 +1,19 @@ /* - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -25,7 +25,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Id: regcustom.h,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Id: regcustom.h,v 1.2 2003/08/04 00:43:32 momjian Exp $ */ /* headers if any */ @@ -38,27 +38,31 @@ /* overrides for regguts.h definitions, if any */ -#define FUNCPTR(name, args) (*name) args -#define MALLOC(n) malloc(n) -#define FREE(p) free(VS(p)) -#define REALLOC(p,n) realloc(VS(p),n) +#define FUNCPTR(name, args) (*name) args +#define MALLOC(n) malloc(n) +#define FREE(p) free(VS(p)) +#define REALLOC(p,n) realloc(VS(p),n) /* internal character type and related */ -typedef pg_wchar chr; /* the type itself */ -typedef unsigned uchr; /* unsigned type that will hold a chr */ -typedef int celt; /* type to hold chr, MCCE number, or NOCELT */ -#define NOCELT (-1) /* celt value which is not valid chr or MCCE */ -#define CHR(c) ((unsigned char) (c)) /* turn char literal into chr literal */ -#define DIGITVAL(c) ((c)-'0') /* turn chr digit into its value */ -#define CHRBITS 32 /* bits in a chr; must not use sizeof */ -#define CHR_MIN 0x00000000 /* smallest and largest chr; the value */ -#define CHR_MAX 0xfffffffe /* CHR_MAX-CHR_MIN+1 should fit in uchr */ +typedef pg_wchar chr; /* the type itself */ +typedef unsigned uchr; /* unsigned type that will hold a chr */ +typedef int celt; /* type to hold chr, MCCE number, or + * NOCELT */ + +#define NOCELT (-1) /* celt value which is not valid chr or + * MCCE */ +#define CHR(c) ((unsigned char) (c)) /* turn char literal into chr + * literal */ +#define DIGITVAL(c) ((c)-'0') /* turn chr digit into its value */ +#define CHRBITS 32 /* bits in a chr; must not use sizeof */ +#define CHR_MIN 0x00000000 /* smallest and largest chr; the value */ +#define CHR_MAX 0xfffffffe /* CHR_MAX-CHR_MIN+1 should fit in uchr */ /* functions operating on chr */ -#define iscalnum(x) pg_isalnum(x) -#define iscalpha(x) pg_isalpha(x) -#define iscdigit(x) pg_isdigit(x) -#define iscspace(x) pg_isspace(x) +#define iscalnum(x) pg_isalnum(x) +#define iscalpha(x) pg_isalpha(x) +#define iscdigit(x) pg_isdigit(x) +#define iscspace(x) pg_isspace(x) /* and pick up the standard header */ #include "regex.h" diff --git a/src/include/regex/regerrs.h b/src/include/regex/regerrs.h index 4b1a0541b5..fbf911fdf2 100644 --- a/src/include/regex/regerrs.h +++ b/src/include/regex/regerrs.h @@ -1,22 +1,75 @@ /* - * $Id: regerrs.h,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Id: regerrs.h,v 1.2 2003/08/04 00:43:32 momjian Exp $ */ -{ REG_OKAY, "REG_OKAY", "no errors detected" }, -{ REG_NOMATCH, "REG_NOMATCH", "failed to match" }, -{ REG_BADPAT, "REG_BADPAT", "invalid regexp (reg version 0.8)" }, -{ REG_ECOLLATE, "REG_ECOLLATE", "invalid collating element" }, -{ REG_ECTYPE, "REG_ECTYPE", "invalid character class" }, -{ REG_EESCAPE, "REG_EESCAPE", "invalid escape \\ sequence" }, -{ REG_ESUBREG, "REG_ESUBREG", "invalid backreference number" }, -{ REG_EBRACK, "REG_EBRACK", "brackets [] not balanced" }, -{ REG_EPAREN, "REG_EPAREN", "parentheses () not balanced" }, -{ REG_EBRACE, "REG_EBRACE", "braces {} not balanced" }, -{ REG_BADBR, "REG_BADBR", "invalid repetition count(s)" }, -{ REG_ERANGE, "REG_ERANGE", "invalid character range" }, -{ REG_ESPACE, "REG_ESPACE", "out of memory" }, -{ REG_BADRPT, "REG_BADRPT", "quantifier operand invalid" }, -{ REG_ASSERT, "REG_ASSERT", "\"can't happen\" -- you found a bug" }, -{ REG_INVARG, "REG_INVARG", "invalid argument to regex function" }, -{ REG_MIXED, "REG_MIXED", "character widths of regex and string differ" }, -{ REG_BADOPT, "REG_BADOPT", "invalid embedded option" }, +{ + REG_OKAY, "REG_OKAY", "no errors detected" +}, + +{ + REG_NOMATCH, "REG_NOMATCH", "failed to match" +}, + +{ + REG_BADPAT, "REG_BADPAT", "invalid regexp (reg version 0.8)" +}, + +{ + REG_ECOLLATE, "REG_ECOLLATE", "invalid collating element" +}, + +{ + REG_ECTYPE, "REG_ECTYPE", "invalid character class" +}, + +{ + REG_EESCAPE, "REG_EESCAPE", "invalid escape \\ sequence" +}, + +{ + REG_ESUBREG, "REG_ESUBREG", "invalid backreference number" +}, + +{ + REG_EBRACK, "REG_EBRACK", "brackets [] not balanced" +}, + +{ + REG_EPAREN, "REG_EPAREN", "parentheses () not balanced" +}, + +{ + REG_EBRACE, "REG_EBRACE", "braces {} not balanced" +}, + +{ + REG_BADBR, "REG_BADBR", "invalid repetition count(s)" +}, + +{ + REG_ERANGE, "REG_ERANGE", "invalid character range" +}, + +{ + REG_ESPACE, "REG_ESPACE", "out of memory" +}, + +{ + REG_BADRPT, "REG_BADRPT", "quantifier operand invalid" +}, + +{ + REG_ASSERT, "REG_ASSERT", "\"can't happen\" -- you found a bug" +}, + +{ + REG_INVARG, "REG_INVARG", "invalid argument to regex function" +}, + +{ + REG_MIXED, "REG_MIXED", "character widths of regex and string differ" +}, + +{ + REG_BADOPT, "REG_BADOPT", "invalid embedded option" +}, diff --git a/src/include/regex/regex.h b/src/include/regex/regex.h index f29379126a..86ea386dce 100644 --- a/src/include/regex/regex.h +++ b/src/include/regex/regex.h @@ -1,15 +1,15 @@ #ifndef _REGEX_H_ -#define _REGEX_H_ /* never again */ +#define _REGEX_H_ /* never again */ /* * regular expressions * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and @@ -17,7 +17,7 @@ * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -29,7 +29,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Id: regex.h,v 1.23 2003/02/05 17:41:32 tgl Exp $ + * $Id: regex.h,v 1.24 2003/08/04 00:43:32 momjian Exp $ */ /* @@ -52,77 +52,81 @@ typedef long regoff_t; */ /* the biggie, a compiled RE (or rather, a front end to same) */ -typedef struct { - int re_magic; /* magic number */ - size_t re_nsub; /* number of subexpressions */ - long re_info; /* information about RE */ -# define REG_UBACKREF 000001 -# define REG_ULOOKAHEAD 000002 -# define REG_UBOUNDS 000004 -# define REG_UBRACES 000010 -# define REG_UBSALNUM 000020 -# define REG_UPBOTCH 000040 -# define REG_UBBS 000100 -# define REG_UNONPOSIX 000200 -# define REG_UUNSPEC 000400 -# define REG_UUNPORT 001000 -# define REG_ULOCALE 002000 -# define REG_UEMPTYMATCH 004000 -# define REG_UIMPOSSIBLE 010000 -# define REG_USHORTEST 020000 - int re_csize; /* sizeof(character) */ - char *re_endp; /* backward compatibility kludge */ +typedef struct +{ + int re_magic; /* magic number */ + size_t re_nsub; /* number of subexpressions */ + long re_info; /* information about RE */ +#define REG_UBACKREF 000001 +#define REG_ULOOKAHEAD 000002 +#define REG_UBOUNDS 000004 +#define REG_UBRACES 000010 +#define REG_UBSALNUM 000020 +#define REG_UPBOTCH 000040 +#define REG_UBBS 000100 +#define REG_UNONPOSIX 000200 +#define REG_UUNSPEC 000400 +#define REG_UUNPORT 001000 +#define REG_ULOCALE 002000 +#define REG_UEMPTYMATCH 004000 +#define REG_UIMPOSSIBLE 010000 +#define REG_USHORTEST 020000 + int re_csize; /* sizeof(character) */ + char *re_endp; /* backward compatibility kludge */ /* the rest is opaque pointers to hidden innards */ - char *re_guts; /* `char *' is more portable than `void *' */ - char *re_fns; + char *re_guts; /* `char *' is more portable than `void *' */ + char *re_fns; } regex_t; /* result reporting (may acquire more fields later) */ -typedef struct { - regoff_t rm_so; /* start of substring */ - regoff_t rm_eo; /* end of substring */ +typedef struct +{ + regoff_t rm_so; /* start of substring */ + regoff_t rm_eo; /* end of substring */ } regmatch_t; /* supplementary control and reporting */ -typedef struct { - regmatch_t rm_extend; /* see REG_EXPECT */ -} rm_detail_t; +typedef struct +{ + regmatch_t rm_extend; /* see REG_EXPECT */ +} rm_detail_t; /* * regex compilation flags */ -#define REG_BASIC 000000 /* BREs (convenience) */ -#define REG_EXTENDED 000001 /* EREs */ -#define REG_ADVF 000002 /* advanced features in EREs */ -#define REG_ADVANCED 000003 /* AREs (which are also EREs) */ -#define REG_QUOTE 000004 /* no special characters, none */ -#define REG_NOSPEC REG_QUOTE /* historical synonym */ -#define REG_ICASE 000010 /* ignore case */ -#define REG_NOSUB 000020 /* don't care about subexpressions */ -#define REG_EXPANDED 000040 /* expanded format, white space & comments */ -#define REG_NLSTOP 000100 /* \n doesn't match . or [^ ] */ -#define REG_NLANCH 000200 /* ^ matches after \n, $ before */ -#define REG_NEWLINE 000300 /* newlines are line terminators */ -#define REG_PEND 000400 /* ugh -- backward-compatibility hack */ -#define REG_EXPECT 001000 /* report details on partial/limited matches */ -#define REG_BOSONLY 002000 /* temporary kludge for BOS-only matches */ -#define REG_DUMP 004000 /* none of your business :-) */ -#define REG_FAKE 010000 /* none of your business :-) */ -#define REG_PROGRESS 020000 /* none of your business :-) */ +#define REG_BASIC 000000 /* BREs (convenience) */ +#define REG_EXTENDED 000001 /* EREs */ +#define REG_ADVF 000002 /* advanced features in EREs */ +#define REG_ADVANCED 000003 /* AREs (which are also EREs) */ +#define REG_QUOTE 000004 /* no special characters, none */ +#define REG_NOSPEC REG_QUOTE /* historical synonym */ +#define REG_ICASE 000010 /* ignore case */ +#define REG_NOSUB 000020 /* don't care about subexpressions */ +#define REG_EXPANDED 000040 /* expanded format, white space & comments */ +#define REG_NLSTOP 000100 /* \n doesn't match . or [^ ] */ +#define REG_NLANCH 000200 /* ^ matches after \n, $ before */ +#define REG_NEWLINE 000300 /* newlines are line terminators */ +#define REG_PEND 000400 /* ugh -- backward-compatibility hack */ +#define REG_EXPECT 001000 /* report details on partial/limited + * matches */ +#define REG_BOSONLY 002000 /* temporary kludge for BOS-only matches */ +#define REG_DUMP 004000 /* none of your business :-) */ +#define REG_FAKE 010000 /* none of your business :-) */ +#define REG_PROGRESS 020000 /* none of your business :-) */ /* * regex execution flags */ -#define REG_NOTBOL 0001 /* BOS is not BOL */ -#define REG_NOTEOL 0002 /* EOS is not EOL */ -#define REG_STARTEND 0004 /* backward compatibility kludge */ -#define REG_FTRACE 0010 /* none of your business */ -#define REG_MTRACE 0020 /* none of your business */ -#define REG_SMALL 0040 /* none of your business */ +#define REG_NOTBOL 0001 /* BOS is not BOL */ +#define REG_NOTEOL 0002 /* EOS is not EOL */ +#define REG_STARTEND 0004 /* backward compatibility kludge */ +#define REG_FTRACE 0010 /* none of your business */ +#define REG_MTRACE 0020 /* none of your business */ +#define REG_SMALL 0040 /* none of your business */ /* @@ -130,36 +134,37 @@ typedef struct { * Be careful if modifying the list of error codes -- the table used by * regerror() is generated automatically from this file! */ -#define REG_OKAY 0 /* no errors detected */ -#define REG_NOMATCH 1 /* failed to match */ -#define REG_BADPAT 2 /* invalid regexp */ -#define REG_ECOLLATE 3 /* invalid collating element */ -#define REG_ECTYPE 4 /* invalid character class */ -#define REG_EESCAPE 5 /* invalid escape \ sequence */ -#define REG_ESUBREG 6 /* invalid backreference number */ -#define REG_EBRACK 7 /* brackets [] not balanced */ -#define REG_EPAREN 8 /* parentheses () not balanced */ -#define REG_EBRACE 9 /* braces {} not balanced */ -#define REG_BADBR 10 /* invalid repetition count(s) */ -#define REG_ERANGE 11 /* invalid character range */ -#define REG_ESPACE 12 /* out of memory */ -#define REG_BADRPT 13 /* quantifier operand invalid */ -#define REG_ASSERT 15 /* "can't happen" -- you found a bug */ -#define REG_INVARG 16 /* invalid argument to regex function */ -#define REG_MIXED 17 /* character widths of regex and string differ */ -#define REG_BADOPT 18 /* invalid embedded option */ +#define REG_OKAY 0 /* no errors detected */ +#define REG_NOMATCH 1 /* failed to match */ +#define REG_BADPAT 2 /* invalid regexp */ +#define REG_ECOLLATE 3 /* invalid collating element */ +#define REG_ECTYPE 4 /* invalid character class */ +#define REG_EESCAPE 5 /* invalid escape \ sequence */ +#define REG_ESUBREG 6 /* invalid backreference number */ +#define REG_EBRACK 7 /* brackets [] not balanced */ +#define REG_EPAREN 8 /* parentheses () not balanced */ +#define REG_EBRACE 9 /* braces {} not balanced */ +#define REG_BADBR 10 /* invalid repetition count(s) */ +#define REG_ERANGE 11 /* invalid character range */ +#define REG_ESPACE 12 /* out of memory */ +#define REG_BADRPT 13 /* quantifier operand invalid */ +#define REG_ASSERT 15 /* "can't happen" -- you found a bug */ +#define REG_INVARG 16 /* invalid argument to regex function */ +#define REG_MIXED 17 /* character widths of regex and string + * differ */ +#define REG_BADOPT 18 /* invalid embedded option */ /* two specials for debugging and testing */ -#define REG_ATOI 101 /* convert error-code name to number */ -#define REG_ITOA 102 /* convert error-code number to name */ +#define REG_ATOI 101 /* convert error-code name to number */ +#define REG_ITOA 102 /* convert error-code number to name */ /* * the prototypes for exported functions */ -extern int pg_regcomp(regex_t *, const pg_wchar *, size_t, int); -extern int pg_regexec(regex_t *, const pg_wchar *, size_t, rm_detail_t *, size_t, regmatch_t [], int); +extern int pg_regcomp(regex_t *, const pg_wchar *, size_t, int); +extern int pg_regexec(regex_t *, const pg_wchar *, size_t, rm_detail_t *, size_t, regmatch_t[], int); extern void pg_regfree(regex_t *); extern size_t pg_regerror(int, const regex_t *, char *, size_t); -#endif /* _REGEX_H_ */ +#endif /* _REGEX_H_ */ diff --git a/src/include/regex/regguts.h b/src/include/regex/regguts.h index a08abb8af1..dfbd392d09 100644 --- a/src/include/regex/regguts.h +++ b/src/include/regex/regguts.h @@ -1,21 +1,21 @@ /* * Internal interface definitions, etc., for the reg package * - * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. - * + * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved. + * * Development of this software was funded, in part, by Cray Research Inc., * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics * Corporation, none of whom are responsible for the results. The author - * thanks all of them. - * + * thanks all of them. + * * Redistribution and use in source and binary forms -- with or without * modification -- are permitted for any purpose, provided that * redistributions in source form retain this entire copyright notice and * indicate the origin and nature of any modifications. - * + * * I'd appreciate being given credit for this package in the documentation * of software which uses it, but that is not a requirement. - * + * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL @@ -27,7 +27,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * $Id: regguts.h,v 1.1 2003/02/05 17:41:32 tgl Exp $ + * $Id: regguts.h,v 1.2 2003/08/04 00:43:32 momjian Exp $ */ @@ -47,34 +47,34 @@ /* assertions */ #ifndef assert -# ifndef REG_DEBUG -# define NDEBUG /* no assertions */ -# endif +#ifndef REG_DEBUG +#define NDEBUG /* no assertions */ +#endif #include #endif /* voids */ #ifndef DISCARD -#define DISCARD void /* for throwing values away */ +#define DISCARD void /* for throwing values away */ #endif #ifndef VS -#define VS(x) ((void *)(x)) /* cast something to generic ptr */ +#define VS(x) ((void *)(x)) /* cast something to generic ptr */ #endif /* function-pointer declarator */ #ifndef FUNCPTR -#define FUNCPTR(name, args) (*name) args +#define FUNCPTR(name, args) (*name) args #endif /* memory allocation */ #ifndef MALLOC -#define MALLOC(n) malloc(n) +#define MALLOC(n) malloc(n) #endif #ifndef REALLOC -#define REALLOC(p, n) realloc(VS(p), n) +#define REALLOC(p, n) realloc(VS(p), n) #endif #ifndef FREE -#define FREE(p) free(VS(p)) +#define FREE(p) free(VS(p)) #endif /* want size of a char in bits, and max value in bounded quantifiers */ @@ -82,7 +82,7 @@ #include #endif #ifndef _POSIX2_RE_DUP_MAX -#define _POSIX2_RE_DUP_MAX 255 /* normally from */ +#define _POSIX2_RE_DUP_MAX 255 /* normally from */ #endif @@ -91,13 +91,13 @@ * misc */ -#define NOTREACHED 0 -#define xxx 1 +#define NOTREACHED 0 +#define xxx 1 -#define DUPMAX _POSIX2_RE_DUP_MAX -#define INFINITY (DUPMAX+1) +#define DUPMAX _POSIX2_RE_DUP_MAX +#define INFINITY (DUPMAX+1) -#define REMAGIC 0xfed7 /* magic number for main struct */ +#define REMAGIC 0xfed7 /* magic number for main struct */ @@ -106,12 +106,12 @@ */ #ifdef REG_DEBUG /* FDEBUG does finite-state tracing */ -#define FDEBUG(arglist) { if (v->eflags®_FTRACE) printf arglist; } +#define FDEBUG(arglist) { if (v->eflags®_FTRACE) printf arglist; } /* MDEBUG does higher-level tracing */ -#define MDEBUG(arglist) { if (v->eflags®_MTRACE) printf arglist; } +#define MDEBUG(arglist) { if (v->eflags®_MTRACE) printf arglist; } #else -#define FDEBUG(arglist) {} -#define MDEBUG(arglist) {} +#define FDEBUG(arglist) {} +#define MDEBUG(arglist) {} #endif @@ -119,24 +119,25 @@ /* * bitmap manipulation */ -#define UBITS (CHAR_BIT * sizeof(unsigned)) -#define BSET(uv, sn) ((uv)[(sn)/UBITS] |= (unsigned)1 << ((sn)%UBITS)) -#define ISBSET(uv, sn) ((uv)[(sn)/UBITS] & ((unsigned)1 << ((sn)%UBITS))) +#define UBITS (CHAR_BIT * sizeof(unsigned)) +#define BSET(uv, sn) ((uv)[(sn)/UBITS] |= (unsigned)1 << ((sn)%UBITS)) +#define ISBSET(uv, sn) ((uv)[(sn)/UBITS] & ((unsigned)1 << ((sn)%UBITS))) /* - * We dissect a chr into byts for colormap table indexing. Here we define - * a byt, which will be the same as a byte on most machines... The exact + * We dissect a chr into byts for colormap table indexing. Here we define + * a byt, which will be the same as a byte on most machines... The exact * size of a byt is not critical, but about 8 bits is good, and extraction * of 8-bit chunks is sometimes especially fast. */ #ifndef BYTBITS -#define BYTBITS 8 /* bits in a byt */ +#define BYTBITS 8 /* bits in a byt */ #endif -#define BYTTAB (1<flags&FREECOL) - union tree *block; /* block of solid color, if any */ +struct colordesc +{ + uchr nchrs; /* number of chars of this color */ + color sub; /* open subcolor (if any); free chain ptr */ +#define NOSUB COLORLESS + struct arc *arcs; /* color chain */ + int flags; +#define FREECOL 01 /* currently free */ +#define PSEUDO 02 /* pseudocolor, no real chars */ +#define UNUSEDCOLOR(cd) ((cd)->flags&FREECOL) + union tree *block; /* block of solid color, if any */ }; /* the color map itself */ -struct colormap { - int magic; -# define CMMAGIC 0x876 - struct vars *v; /* for compile error reporting */ - size_t ncds; /* number of colordescs */ - size_t max; /* highest in use */ - color free; /* beginning of free chain (if non-0) */ +struct colormap +{ + int magic; +#define CMMAGIC 0x876 + struct vars *v; /* for compile error reporting */ + size_t ncds; /* number of colordescs */ + size_t max; /* highest in use */ + color free; /* beginning of free chain (if non-0) */ struct colordesc *cd; -# define CDEND(cm) (&(cm)->cd[(cm)->max + 1]) -# define NINLINECDS ((size_t)10) +#define CDEND(cm) (&(cm)->cd[(cm)->max + 1]) +#define NINLINECDS ((size_t)10) struct colordesc cdspace[NINLINECDS]; - union tree tree[NBYTS]; /* tree top, plus fill blocks */ + union tree tree[NBYTS]; /* tree top, plus fill blocks */ }; /* optimization magic to do fast chr->color mapping */ -#define B0(c) ((c) & BYTMASK) -#define B1(c) (((c)>>BYTBITS) & BYTMASK) -#define B2(c) (((c)>>(2*BYTBITS)) & BYTMASK) -#define B3(c) (((c)>>(3*BYTBITS)) & BYTMASK) +#define B0(c) ((c) & BYTMASK) +#define B1(c) (((c)>>BYTBITS) & BYTMASK) +#define B2(c) (((c)>>(2*BYTBITS)) & BYTMASK) +#define B3(c) (((c)>>(3*BYTBITS)) & BYTMASK) #if NBYTS == 1 -#define GETCOLOR(cm, c) ((cm)->tree->tcolor[B0(c)]) +#define GETCOLOR(cm, c) ((cm)->tree->tcolor[B0(c)]) #endif /* beware, for NBYTS>1, GETCOLOR() is unsafe -- 2nd arg used repeatedly */ #if NBYTS == 2 -#define GETCOLOR(cm, c) ((cm)->tree->tptr[B1(c)]->tcolor[B0(c)]) +#define GETCOLOR(cm, c) ((cm)->tree->tptr[B1(c)]->tcolor[B0(c)]) #endif #if NBYTS == 4 -#define GETCOLOR(cm, c) ((cm)->tree->tptr[B3(c)]->tptr[B2(c)]->tptr[B1(c)]->tcolor[B0(c)]) +#define GETCOLOR(cm, c) ((cm)->tree->tptr[B3(c)]->tptr[B2(c)]->tptr[B1(c)]->tcolor[B0(c)]) #endif @@ -226,22 +234,23 @@ struct colormap { * Interface definitions for locale-interface functions in locale.c. * Multi-character collating elements (MCCEs) cause most of the trouble. */ -struct cvec { - int nchrs; /* number of chrs */ - int chrspace; /* number of chrs possible */ - chr *chrs; /* pointer to vector of chrs */ - int nranges; /* number of ranges (chr pairs) */ - int rangespace; /* number of chrs possible */ - chr *ranges; /* pointer to vector of chr pairs */ - int nmcces; /* number of MCCEs */ - int mccespace; /* number of MCCEs possible */ - int nmccechrs; /* number of chrs used for MCCEs */ - chr *mcces[1]; /* pointers to 0-terminated MCCEs */ - /* and both batches of chrs are on the end */ +struct cvec +{ + int nchrs; /* number of chrs */ + int chrspace; /* number of chrs possible */ + chr *chrs; /* pointer to vector of chrs */ + int nranges; /* number of ranges (chr pairs) */ + int rangespace; /* number of chrs possible */ + chr *ranges; /* pointer to vector of chr pairs */ + int nmcces; /* number of MCCEs */ + int mccespace; /* number of MCCEs possible */ + int nmccechrs; /* number of chrs used for MCCEs */ + chr *mcces[1]; /* pointers to 0-terminated MCCEs */ + /* and both batches of chrs are on the end */ }; /* caution: this value cannot be changed easily */ -#define MAXMCCE 2 /* length of longest MCCE */ +#define MAXMCCE 2 /* length of longest MCCE */ @@ -253,54 +262,59 @@ struct cvec { */ struct state; -struct arc { - int type; -# define ARCFREE '\0' - color co; - struct state *from; /* where it's from (and contained within) */ - struct state *to; /* where it's to */ - struct arc *outchain; /* *from's outs chain or free chain */ -# define freechain outchain - struct arc *inchain; /* *to's ins chain */ - struct arc *colorchain; /* color's arc chain */ +struct arc +{ + int type; +#define ARCFREE '\0' + color co; + struct state *from; /* where it's from (and contained within) */ + struct state *to; /* where it's to */ + struct arc *outchain; /* *from's outs chain or free chain */ +#define freechain outchain + struct arc *inchain; /* *to's ins chain */ + struct arc *colorchain; /* color's arc chain */ }; -struct arcbatch { /* for bulk allocation of arcs */ +struct arcbatch +{ /* for bulk allocation of arcs */ struct arcbatch *next; -# define ABSIZE 10 - struct arc a[ABSIZE]; +#define ABSIZE 10 + struct arc a[ABSIZE]; }; -struct state { - int no; -# define FREESTATE (-1) - char flag; /* marks special states */ - int nins; /* number of inarcs */ - struct arc *ins; /* chain of inarcs */ - int nouts; /* number of outarcs */ - struct arc *outs; /* chain of outarcs */ - struct arc *free; /* chain of free arcs */ - struct state *tmp; /* temporary for traversal algorithms */ - struct state *next; /* chain for traversing all */ - struct state *prev; /* back chain */ - struct arcbatch oas; /* first arcbatch, avoid malloc in easy case */ - int noas; /* number of arcs used in first arcbatch */ +struct state +{ + int no; +#define FREESTATE (-1) + char flag; /* marks special states */ + int nins; /* number of inarcs */ + struct arc *ins; /* chain of inarcs */ + int nouts; /* number of outarcs */ + struct arc *outs; /* chain of outarcs */ + struct arc *free; /* chain of free arcs */ + struct state *tmp; /* temporary for traversal algorithms */ + struct state *next; /* chain for traversing all */ + struct state *prev; /* back chain */ + struct arcbatch oas; /* first arcbatch, avoid malloc in easy + * case */ + int noas; /* number of arcs used in first arcbatch */ }; -struct nfa { - struct state *pre; /* pre-initial state */ - struct state *init; /* initial state */ - struct state *final; /* final state */ - struct state *post; /* post-final state */ - int nstates; /* for numbering states */ - struct state *states; /* state-chain header */ - struct state *slast; /* tail of the chain */ - struct state *free; /* free list */ - struct colormap *cm; /* the color map */ - color bos[2]; /* colors, if any, assigned to BOS and BOL */ - color eos[2]; /* colors, if any, assigned to EOS and EOL */ - struct vars *v; /* simplifies compile error reporting */ - struct nfa *parent; /* parent NFA, if any */ +struct nfa +{ + struct state *pre; /* pre-initial state */ + struct state *init; /* initial state */ + struct state *final; /* final state */ + struct state *post; /* post-final state */ + int nstates; /* for numbering states */ + struct state *states; /* state-chain header */ + struct state *slast; /* tail of the chain */ + struct state *free; /* free list */ + struct colormap *cm; /* the color map */ + color bos[2]; /* colors, if any, assigned to BOS and BOL */ + color eos[2]; /* colors, if any, assigned to EOS and EOL */ + struct vars *v; /* simplifies compile error reporting */ + struct nfa *parent; /* parent NFA, if any */ }; @@ -308,58 +322,64 @@ struct nfa { /* * definitions for compacted NFA */ -struct carc { - color co; /* COLORLESS is list terminator */ - int to; /* state number */ +struct carc +{ + color co; /* COLORLESS is list terminator */ + int to; /* state number */ }; -struct cnfa { - int nstates; /* number of states */ - int ncolors; /* number of colors */ - int flags; -# define HASLACONS 01 /* uses lookahead constraints */ - int pre; /* setup state number */ - int post; /* teardown state number */ - color bos[2]; /* colors, if any, assigned to BOS and BOL */ - color eos[2]; /* colors, if any, assigned to EOS and EOL */ - struct carc **states; /* vector of pointers to outarc lists */ - struct carc *arcs; /* the area for the lists */ +struct cnfa +{ + int nstates; /* number of states */ + int ncolors; /* number of colors */ + int flags; +#define HASLACONS 01 /* uses lookahead constraints */ + int pre; /* setup state number */ + int post; /* teardown state number */ + color bos[2]; /* colors, if any, assigned to BOS and BOL */ + color eos[2]; /* colors, if any, assigned to EOS and EOL */ + struct carc **states; /* vector of pointers to outarc lists */ + struct carc *arcs; /* the area for the lists */ }; -#define ZAPCNFA(cnfa) ((cnfa).nstates = 0) -#define NULLCNFA(cnfa) ((cnfa).nstates == 0) + +#define ZAPCNFA(cnfa) ((cnfa).nstates = 0) +#define NULLCNFA(cnfa) ((cnfa).nstates == 0) /* * subexpression tree */ -struct subre { - char op; /* '|', '.' (concat), 'b' (backref), '(', '=' */ - char flags; -# define LONGER 01 /* prefers longer match */ -# define SHORTER 02 /* prefers shorter match */ -# define MIXED 04 /* mixed preference below */ -# define CAP 010 /* capturing parens below */ -# define BACKR 020 /* back reference below */ -# define INUSE 0100 /* in use in final tree */ -# define LOCAL 03 /* bits which may not propagate up */ -# define LMIX(f) ((f)<<2) /* LONGER -> MIXED */ -# define SMIX(f) ((f)<<1) /* SHORTER -> MIXED */ -# define UP(f) (((f)&~LOCAL) | (LMIX(f) & SMIX(f) & MIXED)) -# define MESSY(f) ((f)&(MIXED|CAP|BACKR)) -# define PREF(f) ((f)&LOCAL) -# define PREF2(f1, f2) ((PREF(f1) != 0) ? PREF(f1) : PREF(f2)) -# define COMBINE(f1, f2) (UP((f1)|(f2)) | PREF2(f1, f2)) - short retry; /* index into retry memory */ - int subno; /* subexpression number (for 'b' and '(') */ - short min; /* min repetitions, for backref only */ - short max; /* max repetitions, for backref only */ - struct subre *left; /* left child, if any (also freelist chain) */ - struct subre *right; /* right child, if any */ - struct state *begin; /* outarcs from here... */ - struct state *end; /* ...ending in inarcs here */ - struct cnfa cnfa; /* compacted NFA, if any */ - struct subre *chain; /* for bookkeeping and error cleanup */ +struct subre +{ + char op; /* '|', '.' (concat), 'b' (backref), '(', + * '=' */ + char flags; +#define LONGER 01 /* prefers longer match */ +#define SHORTER 02 /* prefers shorter match */ +#define MIXED 04 /* mixed preference below */ +#define CAP 010 /* capturing parens below */ +#define BACKR 020 /* back reference below */ +#define INUSE 0100 /* in use in final tree */ +#define LOCAL 03 /* bits which may not propagate up */ +#define LMIX(f) ((f)<<2) /* LONGER -> MIXED */ +#define SMIX(f) ((f)<<1) /* SHORTER -> MIXED */ +#define UP(f) (((f)&~LOCAL) | (LMIX(f) & SMIX(f) & MIXED)) +#define MESSY(f) ((f)&(MIXED|CAP|BACKR)) +#define PREF(f) ((f)&LOCAL) +#define PREF2(f1, f2) ((PREF(f1) != 0) ? PREF(f1) : PREF(f2)) +#define COMBINE(f1, f2) (UP((f1)|(f2)) | PREF2(f1, f2)) + short retry; /* index into retry memory */ + int subno; /* subexpression number (for 'b' and '(') */ + short min; /* min repetitions, for backref only */ + short max; /* max repetitions, for backref only */ + struct subre *left; /* left child, if any (also freelist + * chain) */ + struct subre *right; /* right child, if any */ + struct state *begin; /* outarcs from here... */ + struct state *end; /* ...ending in inarcs here */ + struct cnfa cnfa; /* compacted NFA, if any */ + struct subre *chain; /* for bookkeeping and error cleanup */ }; @@ -368,8 +388,9 @@ struct subre { * table of function pointers for generic manipulation functions * A regex_t's re_fns points to one of these. */ -struct fns { - void FUNCPTR(free, (regex_t *)); +struct fns +{ + void FUNCPTR(free, (regex_t *)); }; @@ -377,17 +398,18 @@ struct fns { /* * the insides of a regex_t, hidden behind a void * */ -struct guts { - int magic; -# define GUTSMAGIC 0xfed9 - int cflags; /* copy of compile flags */ - long info; /* copy of re_info */ - size_t nsub; /* copy of re_nsub */ +struct guts +{ + int magic; +#define GUTSMAGIC 0xfed9 + int cflags; /* copy of compile flags */ + long info; /* copy of re_info */ + size_t nsub; /* copy of re_nsub */ struct subre *tree; - struct cnfa search; /* for fast preliminary search */ - int ntree; + struct cnfa search; /* for fast preliminary search */ + int ntree; struct colormap cmap; - int FUNCPTR(compare, (const chr *, const chr *, size_t)); - struct subre *lacons; /* lookahead-constraint vector */ - int nlacons; /* size of lacons */ + int FUNCPTR(compare, (const chr *, const chr *, size_t)); + struct subre *lacons; /* lookahead-constraint vector */ + int nlacons; /* size of lacons */ }; diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h index 767530fc18..f8bed9de03 100644 --- a/src/include/storage/bufmgr.h +++ b/src/include/storage/bufmgr.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: bufmgr.h,v 1.67 2003/03/28 20:17:13 tgl Exp $ + * $Id: bufmgr.h,v 1.68 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -23,7 +23,7 @@ typedef void *Block; /* in globals.c ... this duplicates miscadmin.h */ -extern DLLIMPORT int NBuffers; +extern DLLIMPORT int NBuffers; /* in bufmgr.c */ extern bool zero_damaged_pages; @@ -33,7 +33,7 @@ extern DLLIMPORT Block *BufferBlockPointers; extern long *PrivateRefCount; /* in localbuf.c */ -extern DLLIMPORT int NLocBuffer; +extern DLLIMPORT int NLocBuffer; extern DLLIMPORT Block *LocalBufferBlockPointers; extern long *LocalRefCount; diff --git a/src/include/storage/freespace.h b/src/include/storage/freespace.h index 8e93a69d77..b60d0ceb2f 100644 --- a/src/include/storage/freespace.h +++ b/src/include/storage/freespace.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: freespace.h,v 1.10 2003/03/06 00:04:27 tgl Exp $ + * $Id: freespace.h,v 1.11 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -23,9 +23,9 @@ */ typedef struct PageFreeSpaceInfo { - BlockNumber blkno; /* which page in relation */ - Size avail; /* space available on this page */ -} PageFreeSpaceInfo; + BlockNumber blkno; /* which page in relation */ + Size avail; /* space available on this page */ +} PageFreeSpaceInfo; /* GUC variables */ @@ -46,13 +46,13 @@ extern BlockNumber RecordAndGetPageWithFreeSpace(RelFileNode *rel, Size spaceNeeded); extern Size GetAvgFSMRequestSize(RelFileNode *rel); extern void RecordRelationFreeSpace(RelFileNode *rel, - int nPages, - PageFreeSpaceInfo *pageSpaces); + int nPages, + PageFreeSpaceInfo * pageSpaces); extern BlockNumber GetFreeIndexPage(RelFileNode *rel); extern void RecordIndexFreeSpace(RelFileNode *rel, - int nPages, - BlockNumber *pages); + int nPages, + BlockNumber *pages); extern void FreeSpaceMapTruncateRel(RelFileNode *rel, BlockNumber nblocks); extern void FreeSpaceMapForgetRel(RelFileNode *rel); diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h index 60482c67b9..577559f7a9 100644 --- a/src/include/storage/lock.h +++ b/src/include/storage/lock.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: lock.h,v 1.71 2003/02/19 23:41:15 momjian Exp $ + * $Id: lock.h,v 1.72 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -160,7 +160,7 @@ typedef struct LOCK * information for each such holder (or would-be holder). * * PROCLOCKTAG is the key information needed to look up a PROCLOCK item in the - * proclock hashtable. A PROCLOCKTAG value uniquely identifies a lock + * proclock hashtable. A PROCLOCKTAG value uniquely identifies a lock * holder/waiter. * * There are two possible kinds of proclock tags: a transaction (identified @@ -199,7 +199,8 @@ typedef struct PROCLOCK int holding[MAX_LOCKMODES]; /* count of locks currently held */ int nHolding; /* total of holding[] array */ SHM_QUEUE lockLink; /* list link for lock's list of proclocks */ - SHM_QUEUE procLink; /* list link for process's list of proclocks */ + SHM_QUEUE procLink; /* list link for process's list of + * proclocks */ } PROCLOCK; #define PROCLOCK_LOCKMETHOD(proclock) \ @@ -246,9 +247,9 @@ extern int LockShmemSize(int maxBackends); extern bool DeadLockCheck(PGPROC *proc); extern void DeadLockReport(void); extern void RememberSimpleDeadLock(PGPROC *proc1, - LOCKMODE lockmode, - LOCK *lock, - PGPROC *proc2); + LOCKMODE lockmode, + LOCK *lock, + PGPROC *proc2); extern void InitDeadLockChecking(void); extern LockData *GetLockStatusData(void); extern const char *GetLockmodeName(LOCKMODE mode); diff --git a/src/include/tcop/dest.h b/src/include/tcop/dest.h index b5721f4593..66d45e33bc 100644 --- a/src/include/tcop/dest.h +++ b/src/include/tcop/dest.h @@ -29,7 +29,7 @@ * * CreateDestReceiver returns a receiver object appropriate to the specified * destination. The executor, as well as utility statements that can return - * tuples, are passed the resulting DestReceiver* pointer. Each executor run + * tuples, are passed the resulting DestReceiver* pointer. Each executor run * or utility execution calls the receiver's startup method, then the * receiveTuple method (zero or more times), then the shutdown method. * The same receiver object may be re-used multiple times; eventually it is @@ -41,8 +41,8 @@ * object that has DestReceiver as its first field and contains additional * fields (see printtup.c for an example). These additional fields are then * accessible to the DestReceiver functions by casting the DestReceiver* - * pointer passed to them. The palloc'd object is pfree'd by the destroy - * method. Note that the caller of CreateDestReceiver should take care to + * pointer passed to them. The palloc'd object is pfree'd by the destroy + * method. Note that the caller of CreateDestReceiver should take care to * do so in a memory context that is long-lived enough for the receiver * object not to disappear while still needed. * @@ -54,7 +54,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: dest.h,v 1.38 2003/05/08 18:16:37 tgl Exp $ + * $Id: dest.h,v 1.39 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -73,7 +73,7 @@ * destination. Someday this will probably need to be improved. * * Note: only the values None, Debug, Remote are legal for the global - * variable whereToSendOutput. The other values may be used + * variable whereToSendOutput. The other values may be used * as the destination for individual commands. * ---------------- */ @@ -104,21 +104,21 @@ struct _DestReceiver { /* Called for each tuple to be output: */ void (*receiveTuple) (HeapTuple tuple, - TupleDesc typeinfo, - DestReceiver *self); + TupleDesc typeinfo, + DestReceiver *self); /* Per-executor-run initialization and shutdown: */ void (*startup) (DestReceiver *self, - int operation, - TupleDesc typeinfo); + int operation, + TupleDesc typeinfo); void (*shutdown) (DestReceiver *self); /* Destroy the receiver object itself (if dynamically allocated) */ void (*destroy) (DestReceiver *self); /* CommandDest code for this receiver */ - CommandDest mydest; + CommandDest mydest; /* Private fields might appear beyond this point... */ }; -extern DestReceiver *None_Receiver; /* permanent receiver for None */ +extern DestReceiver *None_Receiver; /* permanent receiver for None */ /* This is a forward reference to utils/portal.h */ diff --git a/src/include/tcop/pquery.h b/src/include/tcop/pquery.h index ff9cc9d76a..9a20259ae0 100644 --- a/src/include/tcop/pquery.h +++ b/src/include/tcop/pquery.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pquery.h,v 1.27 2003/05/08 18:16:37 tgl Exp $ + * $Id: pquery.h,v 1.28 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -18,25 +18,25 @@ extern void ProcessQuery(Query *parsetree, - Plan *plan, - ParamListInfo params, - DestReceiver *dest, - char *completionTag); + Plan *plan, + ParamListInfo params, + DestReceiver *dest, + char *completionTag); extern PortalStrategy ChoosePortalStrategy(List *parseTrees); extern void PortalStart(Portal portal, ParamListInfo params); extern void PortalSetResultFormat(Portal portal, int nFormats, - int16 *formats); + int16 *formats); extern bool PortalRun(Portal portal, long count, - DestReceiver *dest, DestReceiver *altdest, - char *completionTag); + DestReceiver *dest, DestReceiver *altdest, + char *completionTag); extern long PortalRunFetch(Portal portal, - FetchDirection fdirection, - long count, - DestReceiver *dest); + FetchDirection fdirection, + long count, + DestReceiver *dest); #endif /* PQUERY_H */ diff --git a/src/include/tcop/tcopprot.h b/src/include/tcop/tcopprot.h index ee2e4391fb..1003439291 100644 --- a/src/include/tcop/tcopprot.h +++ b/src/include/tcop/tcopprot.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: tcopprot.h,v 1.58 2003/07/22 20:29:13 momjian Exp $ + * $Id: tcopprot.h,v 1.59 2003/08/04 00:43:32 momjian Exp $ * * OLD COMMENTS * This file was created so that other c files could get the two @@ -40,11 +40,10 @@ extern List *pg_parse_and_rewrite(const char *query_string, Oid *paramTypes, int numParams); extern List *pg_parse_query(const char *query_string); extern List *pg_analyze_and_rewrite(Node *parsetree, - Oid *paramTypes, int numParams); + Oid *paramTypes, int numParams); extern List *pg_rewrite_queries(List *querytree_list); extern Plan *pg_plan_query(Query *querytree); extern List *pg_plan_queries(List *querytrees, bool needSnapshot); - #endif /* BOOTSTRAP_INCLUDE */ extern void die(SIGNAL_ARGS); diff --git a/src/include/utils/acl.h b/src/include/utils/acl.h index 3849cf2e85..8226381fba 100644 --- a/src/include/utils/acl.h +++ b/src/include/utils/acl.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: acl.h,v 1.58 2003/08/01 00:15:25 tgl Exp $ + * $Id: acl.h,v 1.59 2003/08/04 00:43:32 momjian Exp $ * * NOTES * For backward-compatibility purposes we have to allow there @@ -61,7 +61,7 @@ typedef struct AclItem * and the lower 15 bits are the actual privileges. */ #define ACLITEM_GET_PRIVS(item) ((item).ai_privs & 0x7FFF) -#define ACLITEM_GET_GOPTIONS(item) (((item).ai_privs >> 15) & 0x7FFF) +#define ACLITEM_GET_GOPTIONS(item) (((item).ai_privs >> 15) & 0x7FFF) #define ACLITEM_GET_IDTYPE(item) ((item).ai_privs >> 30) #define ACL_GRANT_OPTION_FOR(privs) (((privs) & 0x7FFF) << 15) @@ -190,14 +190,14 @@ typedef enum AclObjectKind ACL_KIND_OPCLASS, /* pg_opclass */ ACL_KIND_CONVERSION, /* pg_conversion */ MAX_ACL_KIND /* MUST BE LAST */ -} AclObjectKind; +} AclObjectKind; /* * routines used internally */ extern Acl *acldefault(GrantObjectType objtype, AclId ownerid); extern Acl *aclinsert3(const Acl *old_acl, const AclItem *mod_aip, - unsigned modechg, DropBehavior behavior); + unsigned modechg, DropBehavior behavior); /* * SQL functions (from acl.c) @@ -224,7 +224,7 @@ extern AclResult pg_language_aclcheck(Oid lang_oid, AclId userid, AclMode mode); extern AclResult pg_namespace_aclcheck(Oid nsp_oid, AclId userid, AclMode mode); extern void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, - const char *objectname); + const char *objectname); /* ownercheck routines just return true (owner) or false (not) */ extern bool pg_class_ownercheck(Oid class_oid, AclId userid); diff --git a/src/include/utils/array.h b/src/include/utils/array.h index 50c222a9b4..048210087a 100644 --- a/src/include/utils/array.h +++ b/src/include/utils/array.h @@ -10,7 +10,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: array.h,v 1.42 2003/07/14 20:34:18 tgl Exp $ + * $Id: array.h,v 1.43 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -36,6 +36,7 @@ typedef struct ArrayBuildState { MemoryContext mcontext; /* where all the temp stuff is kept */ Datum *dvalues; /* array of accumulated Datums */ + /* * The allocated size of dvalues[] is always a multiple of * ARRAY_ELEMS_CHUNKSIZE @@ -46,22 +47,22 @@ typedef struct ArrayBuildState int16 typlen; /* needed info about datatype */ bool typbyval; char typalign; -} ArrayBuildState; +} ArrayBuildState; /* * structure to cache type metadata needed for array manipulation */ typedef struct ArrayMetaState { - Oid element_type; - int16 typlen; - bool typbyval; - char typalign; - char typdelim; - Oid typelem; - Oid typiofunc; - FmgrInfo proc; -} ArrayMetaState; + Oid element_type; + int16 typlen; + bool typbyval; + char typalign; + char typdelim; + Oid typelem; + Oid typiofunc; + FmgrInfo proc; +} ArrayMetaState; /* * fmgr macros for array objects @@ -151,22 +152,22 @@ extern ArrayType *construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign); extern ArrayType *construct_md_array(Datum *elems, - int ndims, - int *dims, - int *lbs, - Oid elmtype, int elmlen, bool elmbyval, char elmalign); + int ndims, + int *dims, + int *lbs, + Oid elmtype, int elmlen, bool elmbyval, char elmalign); extern void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, int *nelemsp); -extern ArrayBuildState *accumArrayResult(ArrayBuildState *astate, - Datum dvalue, bool disnull, - Oid element_type, - MemoryContext rcontext); -extern Datum makeArrayResult(ArrayBuildState *astate, - MemoryContext rcontext); -extern Datum makeMdArrayResult(ArrayBuildState *astate, int ndims, - int *dims, int *lbs, MemoryContext rcontext); +extern ArrayBuildState *accumArrayResult(ArrayBuildState * astate, + Datum dvalue, bool disnull, + Oid element_type, + MemoryContext rcontext); +extern Datum makeArrayResult(ArrayBuildState * astate, + MemoryContext rcontext); +extern Datum makeMdArrayResult(ArrayBuildState * astate, int ndims, + int *dims, int *lbs, MemoryContext rcontext); /* * prototypes for functions defined in arrayutils.c @@ -187,8 +188,8 @@ extern Datum array_push(PG_FUNCTION_ARGS); extern Datum array_cat(PG_FUNCTION_ARGS); extern ArrayType *create_singleton_array(FunctionCallInfo fcinfo, - Oid element_type, - Datum element, - int ndims); + Oid element_type, + Datum element, + int ndims); #endif /* ARRAY_H */ diff --git a/src/include/utils/builtins.h b/src/include/utils/builtins.h index f2164590a3..b5e755882a 100644 --- a/src/include/utils/builtins.h +++ b/src/include/utils/builtins.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: builtins.h,v 1.224 2003/07/30 22:56:24 tgl Exp $ + * $Id: builtins.h,v 1.225 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -408,7 +408,7 @@ extern Datum texticregexne(PG_FUNCTION_ARGS); extern Datum textregexsubstr(PG_FUNCTION_ARGS); extern Datum similar_escape(PG_FUNCTION_ARGS); extern const char *assign_regex_flavor(const char *value, - bool doit, bool interactive); + bool doit, bool interactive); /* regproc.c */ extern Datum regprocin(PG_FUNCTION_ARGS); diff --git a/src/include/utils/datetime.h b/src/include/utils/datetime.h index 6fe4723bbe..109a86b0a9 100644 --- a/src/include/utils/datetime.h +++ b/src/include/utils/datetime.h @@ -9,7 +9,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: datetime.h,v 1.41 2003/07/17 22:28:42 tgl Exp $ + * $Id: datetime.h,v 1.42 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -268,8 +268,8 @@ extern int day_tab[2][13]; || (((m) == UTIME_MAXMONTH) && ((d) <= UTIME_MAXDAY)))))) /* Julian-date equivalents of Day 0 in Unix and Postgres reckoning */ -#define UNIX_EPOCH_JDATE 2440588 /* == date2j(1970, 1, 1) */ -#define POSTGRES_EPOCH_JDATE 2451545 /* == date2j(2000, 1, 1) */ +#define UNIX_EPOCH_JDATE 2440588 /* == date2j(1970, 1, 1) */ +#define POSTGRES_EPOCH_JDATE 2451545 /* == date2j(2000, 1, 1) */ extern void GetCurrentDateTime(struct tm * tm); diff --git a/src/include/utils/elog.h b/src/include/utils/elog.h index 5c5a66a761..faa4783d4e 100644 --- a/src/include/utils/elog.h +++ b/src/include/utils/elog.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: elog.h,v 1.60 2003/07/27 18:37:52 tgl Exp $ + * $Id: elog.h,v 1.61 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,12 +45,12 @@ #define FATAL 21 /* fatal error - abort process */ #define PANIC 22 /* take down the other backends with me */ - /*#define DEBUG DEBUG1*/ /* Backward compatibility with pre-7.3 */ + /* #define DEBUG DEBUG1 */ /* Backward compatibility with pre-7.3 */ /* macros for representing SQLSTATE strings compactly */ #define PGSIXBIT(ch) (((ch) - '0') & 0x3F) -#define PGUNSIXBIT(val) (((val) & 0x3F) + '0') +#define PGUNSIXBIT(val) (((val) & 0x3F) + '0') #define MAKE_SQLSTATE(ch1,ch2,ch3,ch4,ch5) \ (PGSIXBIT(ch1) + (PGSIXBIT(ch2) << 6) + (PGSIXBIT(ch3) << 12) + \ @@ -80,7 +80,7 @@ * ... other errxxx() fields as needed ...)); * * The error level is required, and so is a primary error message (errmsg - * or errmsg_internal). All else is optional. errcode() defaults to + * or errmsg_internal). All else is optional. errcode() defaults to * ERRCODE_INTERNAL_ERROR if elevel is ERROR or more, ERRCODE_WARNING * if elevel is WARNING, or ERRCODE_SUCCESSFUL_COMPLETION if elevel is * NOTICE or below. @@ -91,41 +91,46 @@ (errfinish rest) : (void) 0) extern bool errstart(int elevel, const char *filename, int lineno, - const char *funcname); -extern void errfinish(int dummy, ...); + const char *funcname); +extern void errfinish(int dummy,...); -extern int errcode(int sqlerrcode); +extern int errcode(int sqlerrcode); -extern int errcode_for_file_access(void); -extern int errcode_for_socket_access(void); +extern int errcode_for_file_access(void); +extern int errcode_for_socket_access(void); -extern int errmsg(const char *fmt, ...) +extern int +errmsg(const char *fmt,...) /* This extension allows gcc to check the format string for consistency with the supplied arguments. */ __attribute__((format(printf, 1, 2))); -extern int errmsg_internal(const char *fmt, ...) +extern int +errmsg_internal(const char *fmt,...) /* This extension allows gcc to check the format string for consistency with the supplied arguments. */ __attribute__((format(printf, 1, 2))); -extern int errdetail(const char *fmt, ...) +extern int +errdetail(const char *fmt,...) /* This extension allows gcc to check the format string for consistency with the supplied arguments. */ __attribute__((format(printf, 1, 2))); -extern int errhint(const char *fmt, ...) +extern int +errhint(const char *fmt,...) /* This extension allows gcc to check the format string for consistency with the supplied arguments. */ __attribute__((format(printf, 1, 2))); -extern int errcontext(const char *fmt, ...) +extern int +errcontext(const char *fmt,...) /* This extension allows gcc to check the format string for consistency with the supplied arguments. */ __attribute__((format(printf, 1, 2))); -extern int errfunction(const char *funcname); -extern int errposition(int cursorpos); +extern int errfunction(const char *funcname); +extern int errposition(int cursorpos); /*---------- @@ -133,10 +138,10 @@ extern int errposition(int cursorpos); * elog(ERROR, "portal \"%s\" not found", stmt->portalname); *---------- */ -#define elog errstart(ERROR, __FILE__, __LINE__, PG_FUNCNAME_MACRO), elog_finish +#define elog errstart(ERROR, __FILE__, __LINE__, PG_FUNCNAME_MACRO), elog_finish extern void -elog_finish(int elevel, const char *fmt, ...) +elog_finish(int elevel, const char *fmt,...) /* This extension allows gcc to check the format string for consistency with the supplied arguments. */ __attribute__((format(printf, 2, 3))); @@ -147,9 +152,9 @@ __attribute__((format(printf, 2, 3))); typedef struct ErrorContextCallback { struct ErrorContextCallback *previous; - void (*callback) (void *arg); - void *arg; -} ErrorContextCallback; + void (*callback) (void *arg); + void *arg; +} ErrorContextCallback; extern DLLIMPORT ErrorContextCallback *error_context_stack; @@ -161,11 +166,12 @@ typedef enum PGERROR_TERSE, /* single-line error messages */ PGERROR_DEFAULT, /* recommended style */ PGERROR_VERBOSE /* all the facts, ma'am */ -} PGErrorVerbosity; +} PGErrorVerbosity; extern PGErrorVerbosity Log_error_verbosity; extern bool Log_timestamp; extern bool Log_pid; + #ifdef HAVE_SYSLOG extern int Use_syslog; #endif diff --git a/src/include/utils/errcodes.h b/src/include/utils/errcodes.h index f076c7327b..8db8e52320 100644 --- a/src/include/utils/errcodes.h +++ b/src/include/utils/errcodes.h @@ -5,13 +5,13 @@ * * The error code list is kept in its own source file for possible use by * automatic tools. Each error code is identified by a five-character string - * following the SQLSTATE conventions. The exact representation of the + * following the SQLSTATE conventions. The exact representation of the * string is determined by the MAKE_SQLSTATE() macro, which is not defined * in this file; it can be defined by the caller for special purposes. * * Copyright (c) 2003, PostgreSQL Global Development Group * - * $Id: errcodes.h,v 1.3 2003/07/31 21:34:18 tgl Exp $ + * $Id: errcodes.h,v 1.4 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -91,9 +91,9 @@ #define ERRCODE_ARRAY_ELEMENT_ERROR MAKE_SQLSTATE('2','2', '0','2','E') /* SQL99's actual definition of "array element error" is subscript error */ #define ERRCODE_ARRAY_SUBSCRIPT_ERROR ERRCODE_ARRAY_ELEMENT_ERROR -#define ERRCODE_CHARACTER_NOT_IN_REPERTOIRE MAKE_SQLSTATE('2','2', '0','2','1') +#define ERRCODE_CHARACTER_NOT_IN_REPERTOIRE MAKE_SQLSTATE('2','2', '0','2','1') #define ERRCODE_DATETIME_FIELD_OVERFLOW MAKE_SQLSTATE('2','2', '0','0','8') -#define ERRCODE_DATETIME_VALUE_OUT_OF_RANGE ERRCODE_DATETIME_FIELD_OVERFLOW +#define ERRCODE_DATETIME_VALUE_OUT_OF_RANGE ERRCODE_DATETIME_FIELD_OVERFLOW #define ERRCODE_DIVISION_BY_ZERO MAKE_SQLSTATE('2','2', '0','1','2') #define ERRCODE_ERROR_IN_ASSIGNMENT MAKE_SQLSTATE('2','2', '0','0','5') #define ERRCODE_ESCAPE_CHARACTER_CONFLICT MAKE_SQLSTATE('2','2', '0','0','B') @@ -110,18 +110,18 @@ #define ERRCODE_INVALID_REGULAR_EXPRESSION MAKE_SQLSTATE('2','2', '0','1','B') #define ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE MAKE_SQLSTATE('2','2', '0','0','9') #define ERRCODE_INVALID_USE_OF_ESCAPE_CHARACTER MAKE_SQLSTATE('2','2', '0','0','C') -#define ERRCODE_MOST_SPECIFIC_TYPE_MISMATCH MAKE_SQLSTATE('2','2', '0','0','G') +#define ERRCODE_MOST_SPECIFIC_TYPE_MISMATCH MAKE_SQLSTATE('2','2', '0','0','G') #define ERRCODE_NULL_VALUE_NOT_ALLOWED MAKE_SQLSTATE('2','2', '0','0','4') #define ERRCODE_NULL_VALUE_NO_INDICATOR_PARAMETER MAKE_SQLSTATE('2','2', '0','0','2') #define ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE MAKE_SQLSTATE('2','2', '0','0','3') -#define ERRCODE_STRING_DATA_LENGTH_MISMATCH MAKE_SQLSTATE('2','2', '0','2','6') +#define ERRCODE_STRING_DATA_LENGTH_MISMATCH MAKE_SQLSTATE('2','2', '0','2','6') #define ERRCODE_STRING_DATA_RIGHT_TRUNCATION MAKE_SQLSTATE('2','2', '0','0','1') #define ERRCODE_SUBSTRING_ERROR MAKE_SQLSTATE('2','2', '0','1','1') #define ERRCODE_TRIM_ERROR MAKE_SQLSTATE('2','2', '0','2','7') #define ERRCODE_UNTERMINATED_C_STRING MAKE_SQLSTATE('2','2', '0','2','4') #define ERRCODE_ZERO_LENGTH_CHARACTER_STRING MAKE_SQLSTATE('2','2', '0','0','F') #define ERRCODE_FLOATING_POINT_EXCEPTION MAKE_SQLSTATE('2','2', 'P','0','1') -#define ERRCODE_INVALID_TEXT_REPRESENTATION MAKE_SQLSTATE('2','2', 'P','0','2') +#define ERRCODE_INVALID_TEXT_REPRESENTATION MAKE_SQLSTATE('2','2', 'P','0','2') #define ERRCODE_INVALID_BINARY_REPRESENTATION MAKE_SQLSTATE('2','2', 'P','0','3') #define ERRCODE_BAD_COPY_FILE_FORMAT MAKE_SQLSTATE('2','2', 'P','0','4') #define ERRCODE_UNTRANSLATABLE_CHARACTER MAKE_SQLSTATE('2','2', 'P','0','5') @@ -158,7 +158,7 @@ #define ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION MAKE_SQLSTATE('2','7', '0','0','0') /* Class 28 - Invalid Authorization Specification */ -#define ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION MAKE_SQLSTATE('2','8', '0','0','0') +#define ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION MAKE_SQLSTATE('2','8', '0','0','0') /* Class 2B - Dependent Privilege Descriptors Still Exist */ #define ERRCODE_DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST MAKE_SQLSTATE('2','B', '0','0','0') @@ -169,7 +169,7 @@ /* Class 2F - SQL Routine Exception */ #define ERRCODE_SQL_ROUTINE_EXCEPTION MAKE_SQLSTATE('2','F', '0','0','0') -#define ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT MAKE_SQLSTATE('2','F', '0','0','5') +#define ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT MAKE_SQLSTATE('2','F', '0','0','5') #define ERRCODE_S_R_E_MODIFYING_SQL_DATA_NOT_PERMITTED MAKE_SQLSTATE('2','F', '0','0','2') #define ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED MAKE_SQLSTATE('2','F', '0','0','3') #define ERRCODE_S_R_E_READING_SQL_DATA_NOT_PERMITTED MAKE_SQLSTATE('2','F', '0','0','4') @@ -255,15 +255,15 @@ #define ERRCODE_INVALID_COLUMN_REFERENCE MAKE_SQLSTATE('4','2', 'P','1','0') #define ERRCODE_INVALID_COLUMN_DEFINITION MAKE_SQLSTATE('4','2', '6','1','1') #define ERRCODE_INVALID_CURSOR_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','1') -#define ERRCODE_INVALID_DATABASE_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','2') -#define ERRCODE_INVALID_FUNCTION_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','3') +#define ERRCODE_INVALID_DATABASE_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','2') +#define ERRCODE_INVALID_FUNCTION_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','3') #define ERRCODE_INVALID_PSTATEMENT_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','4') #define ERRCODE_INVALID_SCHEMA_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','5') #define ERRCODE_INVALID_TABLE_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','6') #define ERRCODE_INVALID_OBJECT_DEFINITION MAKE_SQLSTATE('4','2', 'P','1','7') /* Class 44 - WITH CHECK OPTION Violation */ -#define ERRCODE_WITH_CHECK_OPTION_VIOLATION MAKE_SQLSTATE('4','4', '0','0','0') +#define ERRCODE_WITH_CHECK_OPTION_VIOLATION MAKE_SQLSTATE('4','4', '0','0','0') /* Class 53 - Insufficient Resources (PostgreSQL-specific error class) */ #define ERRCODE_INSUFFICIENT_RESOURCES MAKE_SQLSTATE('5','3', '0','0','0') diff --git a/src/include/utils/guc.h b/src/include/utils/guc.h index 979b5171e8..6b5816ddc8 100644 --- a/src/include/utils/guc.h +++ b/src/include/utils/guc.h @@ -7,7 +7,7 @@ * Copyright 2000-2003 by PostgreSQL Global Development Group * Written by Peter Eisentraut . * - * $Id: guc.h,v 1.38 2003/07/28 19:31:32 tgl Exp $ + * $Id: guc.h,v 1.39 2003/08/04 00:43:32 momjian Exp $ *-------------------------------------------------------------------- */ #ifndef GUC_H @@ -40,7 +40,7 @@ * configuration file, or by client request in the connection startup * packet (e.g., from libpq's PGOPTIONS variable). Furthermore, an * already-started backend will ignore changes to such an option in the - * configuration file. The idea is that these options are fixed for a + * configuration file. The idea is that these options are fixed for a * given backend once it's started, but they can vary across backends. * * SUSET options can be set at postmaster startup, with the SIGHUP @@ -146,8 +146,8 @@ extern ArrayType *GUCArrayAdd(ArrayType *array, const char *name, const char *va extern ArrayType *GUCArrayDelete(ArrayType *array, const char *name); #ifdef EXEC_BACKEND -void write_nondefault_variables(GucContext context); -void read_nondefault_variables(void); +void write_nondefault_variables(GucContext context); +void read_nondefault_variables(void); #endif #endif /* GUC_H */ diff --git a/src/include/utils/guc_tables.h b/src/include/utils/guc_tables.h index b1abc0b107..742b3b2ff6 100644 --- a/src/include/utils/guc_tables.h +++ b/src/include/utils/guc_tables.h @@ -7,7 +7,7 @@ * * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * - * $Id: guc_tables.h,v 1.4 2003/07/28 19:31:32 tgl Exp $ + * $Id: guc_tables.h,v 1.5 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -68,17 +68,17 @@ enum config_type * Generic fields applicable to all types of variables * * The short description should be less than 80 chars in length. Some - * applications may use the long description as well, and will append - * it to the short description. (separated by a newline or '. ') + * applications may use the long description as well, and will append + * it to the short description. (separated by a newline or '. ') */ struct config_generic { /* constant fields, must be set correctly in initial value: */ const char *name; /* name of variable - MUST BE FIRST */ GucContext context; /* context required to set the variable */ - enum config_group group; /* to help organize variables by function */ - const char *short_desc; /* short desc. of this variable's purpose */ - const char *long_desc; /* long desc. of this variable's purpose */ + enum config_group group; /* to help organize variables by function */ + const char *short_desc; /* short desc. of this variable's purpose */ + const char *long_desc; /* long desc. of this variable's purpose */ int flags; /* flag bits, see below */ /* variable fields, initialized at runtime: */ enum config_type vartype; /* type of variable (set only at startup) */ @@ -95,8 +95,8 @@ struct config_generic #define GUC_NO_SHOW_ALL 0x0004 /* exclude from SHOW ALL */ #define GUC_NO_RESET_ALL 0x0008 /* exclude from RESET ALL */ #define GUC_REPORT 0x0010 /* auto-report changes to client */ -#define GUC_NOT_IN_SAMPLE 0x0020 /* not in postgresql.conf.sample */ -#define GUC_DISALLOW_IN_FILE 0x0040 /* can't set in postgresql.conf */ +#define GUC_NOT_IN_SAMPLE 0x0020 /* not in postgresql.conf.sample */ +#define GUC_DISALLOW_IN_FILE 0x0040 /* can't set in postgresql.conf */ /* bit values in status field */ #define GUC_HAVE_TENTATIVE 0x0001 /* tentative value is defined */ @@ -167,10 +167,10 @@ struct config_string }; /* constant tables corresponding to enums above and in guc.h */ -extern const char * const config_group_names[]; -extern const char * const config_type_names[]; -extern const char * const GucContext_Names[]; -extern const char * const GucSource_Names[]; +extern const char *const config_group_names[]; +extern const char *const config_type_names[]; +extern const char *const GucContext_Names[]; +extern const char *const GucSource_Names[]; /* the current set of variables */ extern struct config_generic **guc_variables; diff --git a/src/include/utils/help_config.h b/src/include/utils/help_config.h index 45645f0216..cd2c6e02fc 100644 --- a/src/include/utils/help_config.h +++ b/src/include/utils/help_config.h @@ -1,11 +1,11 @@ /*------------------------------------------------------------------------- * * help_config.h - * Interface to the --help-config option of main.c - * + * Interface to the --help-config option of main.c + * * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * - * $Id: help_config.h,v 1.1 2003/07/04 16:41:22 tgl Exp $ + * $Id: help_config.h,v 1.2 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ diff --git a/src/include/utils/inet.h b/src/include/utils/inet.h index dd6df6d56d..9b375ed24c 100644 --- a/src/include/utils/inet.h +++ b/src/include/utils/inet.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: inet.h,v 1.14 2003/06/24 22:21:23 momjian Exp $ + * $Id: inet.h,v 1.15 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -23,7 +23,7 @@ typedef struct unsigned char family; unsigned char bits; unsigned char type; - unsigned char ip_addr[16]; /* 128 bits of address */ + unsigned char ip_addr[16]; /* 128 bits of address */ } inet_struct; /* diff --git a/src/include/utils/lsyscache.h b/src/include/utils/lsyscache.h index 1f8bcb06d1..129492a325 100644 --- a/src/include/utils/lsyscache.h +++ b/src/include/utils/lsyscache.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: lsyscache.h,v 1.76 2003/07/01 19:10:53 tgl Exp $ + * $Id: lsyscache.h,v 1.77 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -22,7 +22,7 @@ typedef enum IOFuncSelector IOFunc_output, IOFunc_receive, IOFunc_send -} IOFuncSelector; +} IOFuncSelector; extern bool op_in_opclass(Oid opno, Oid opclass); extern bool op_requires_recheck(Oid opno, Oid opclass); @@ -67,13 +67,13 @@ extern void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval); extern void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign); extern void get_type_io_data(Oid typid, - IOFuncSelector which_func, - int16 *typlen, - bool *typbyval, - char *typalign, - char *typdelim, - Oid *typelem, - Oid *func); + IOFuncSelector which_func, + int16 *typlen, + bool *typbyval, + char *typalign, + char *typdelim, + Oid *typelem, + Oid *func); extern char get_typstorage(Oid typid); extern int32 get_typtypmod(Oid typid); extern Node *get_typdefault(Oid typid); @@ -87,7 +87,7 @@ extern void getTypeOutputInfo(Oid type, Oid *typOutput, Oid *typElem, bool *typIsVarlena); extern void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typElem); extern void getTypeBinaryOutputInfo(Oid type, Oid *typSend, Oid *typElem, - bool *typIsVarlena); + bool *typIsVarlena); extern Oid getBaseType(Oid typid); extern int32 get_typavgwidth(Oid typid, int32 typmod); extern int32 get_attavgwidth(Oid relid, AttrNumber attnum); diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 6934d10962..6d04ddba5d 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -10,7 +10,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: memutils.h,v 1.51 2003/05/02 20:54:36 tgl Exp $ + * $Id: memutils.h,v 1.52 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -70,6 +70,7 @@ extern DLLIMPORT MemoryContext PostmasterContext; extern DLLIMPORT MemoryContext CacheMemoryContext; extern DLLIMPORT MemoryContext MessageContext; extern DLLIMPORT MemoryContext TopTransactionContext; + /* These two are transient links to contexts owned by other objects: */ extern DLLIMPORT MemoryContext QueryContext; extern DLLIMPORT MemoryContext PortalContext; @@ -127,8 +128,8 @@ extern MemoryContext AllocSetContextCreate(MemoryContext parent, * Recommended alloc parameters for "small" contexts that are not expected * to contain much data (for example, a context to contain a query plan). */ -#define ALLOCSET_SMALL_MINSIZE 0 +#define ALLOCSET_SMALL_MINSIZE 0 #define ALLOCSET_SMALL_INITSIZE (1 * 1024) -#define ALLOCSET_SMALL_MAXSIZE (8 * 1024) +#define ALLOCSET_SMALL_MAXSIZE (8 * 1024) #endif /* MEMUTILS_H */ diff --git a/src/include/utils/palloc.h b/src/include/utils/palloc.h index 7dabc52f31..7ba40efda9 100644 --- a/src/include/utils/palloc.h +++ b/src/include/utils/palloc.h @@ -21,7 +21,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: palloc.h,v 1.24 2002/12/16 16:22:46 tgl Exp $ + * $Id: palloc.h,v 1.25 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -51,7 +51,7 @@ extern void *MemoryContextAllocZeroAligned(MemoryContext context, Size size); #define palloc(sz) MemoryContextAlloc(CurrentMemoryContext, (sz)) -#define palloc0(sz) MemoryContextAllocZero(CurrentMemoryContext, (sz)) +#define palloc0(sz) MemoryContextAllocZero(CurrentMemoryContext, (sz)) /* * The result of palloc() is always word-aligned, so we can skip testing @@ -61,7 +61,7 @@ extern void *MemoryContextAllocZeroAligned(MemoryContext context, Size size); * issue that it evaluates the argument multiple times isn't a problem in * practice. */ -#define palloc0fast(sz) \ +#define palloc0fast(sz) \ ( MemSetTest(0, sz) ? \ MemoryContextAllocZeroAligned(CurrentMemoryContext, sz) : \ MemoryContextAllocZero(CurrentMemoryContext, sz) ) diff --git a/src/include/utils/portal.h b/src/include/utils/portal.h index 7da359cbe7..6c7664f04d 100644 --- a/src/include/utils/portal.h +++ b/src/include/utils/portal.h @@ -9,7 +9,7 @@ * * Scrolling (nonsequential access) and suspension of execution are allowed * only for portals that contain a single SELECT-type query. We do not want - * to let the client suspend an update-type query partway through! Because + * to let the client suspend an update-type query partway through! Because * the query rewriter does not allow arbitrary ON SELECT rewrite rules, * only queries that were originally update-type could produce multiple * parse/plan trees; so the restriction to a single query is not a problem @@ -18,13 +18,13 @@ * For SQL cursors, we support three kinds of scroll behavior: * * (1) Neither NO SCROLL nor SCROLL was specified: to remain backward - * compatible, we allow backward fetches here, unless it would - * impose additional runtime overhead to do so. + * compatible, we allow backward fetches here, unless it would + * impose additional runtime overhead to do so. * * (2) NO SCROLL was specified: don't allow any backward fetches. * * (3) SCROLL was specified: allow all kinds of backward fetches, even - * if we need to take a performance hit to do so. (The planner sticks + * if we need to take a performance hit to do so. (The planner sticks * a Materialize node atop the query plan if needed.) * * Case #1 is converted to #2 or #3 by looking at the query itself and @@ -39,7 +39,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: portal.h,v 1.44 2003/05/08 18:16:37 tgl Exp $ + * $Id: portal.h,v 1.45 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -58,8 +58,8 @@ * single result from the user's viewpoint. However, the rule rewriter * may expand the single source query to zero or many actual queries.) * - * PORTAL_ONE_SELECT: the portal contains one single SELECT query. We run - * the Executor incrementally as results are demanded. This strategy also + * PORTAL_ONE_SELECT: the portal contains one single SELECT query. We run + * the Executor incrementally as results are demanded. This strategy also * supports holdable cursors (the Executor results can be dumped into a * tuplestore for access after transaction completion). * @@ -77,7 +77,7 @@ typedef enum PortalStrategy PORTAL_ONE_SELECT, PORTAL_UTIL_SELECT, PORTAL_MULTI_QUERY -} PortalStrategy; +} PortalStrategy; /* * Note: typedef Portal is declared in tcop/dest.h as @@ -89,7 +89,7 @@ typedef struct PortalData /* Bookkeeping data */ const char *name; /* portal's name */ MemoryContext heap; /* subsidiary memory for portal */ - void (*cleanup) (Portal portal, bool isError); /* cleanup hook */ + void (*cleanup) (Portal portal, bool isError); /* cleanup hook */ TransactionId createXact; /* the xid of the creating xact */ /* The query or queries the portal will execute */ @@ -97,15 +97,16 @@ typedef struct PortalData const char *commandTag; /* command tag for original query */ List *parseTrees; /* parse tree(s) */ List *planTrees; /* plan tree(s) */ - MemoryContext queryContext; /* where the above trees live */ + MemoryContext queryContext; /* where the above trees live */ + /* * Note: queryContext effectively identifies which prepared statement * the portal depends on, if any. The queryContext is *not* owned by - * the portal and is not to be deleted by portal destruction. (But for - * a cursor it is the same as "heap", and that context is deleted by - * portal destruction.) + * the portal and is not to be deleted by portal destruction. (But + * for a cursor it is the same as "heap", and that context is deleted + * by portal destruction.) */ - ParamListInfo portalParams; /* params to pass to query */ + ParamListInfo portalParams; /* params to pass to query */ /* Features/options */ PortalStrategy strategy; /* see above */ @@ -113,7 +114,7 @@ typedef struct PortalData /* Status data */ bool portalReady; /* PortalStart complete? */ - bool portalUtilReady; /* PortalRunUtility complete? */ + bool portalUtilReady; /* PortalRunUtility complete? */ bool portalActive; /* portal is running (can't delete it) */ bool portalDone; /* portal is finished (don't re-run it) */ @@ -126,21 +127,21 @@ typedef struct PortalData int16 *formats; /* a format code for each column */ /* - * Where we store tuples for a held cursor or a PORTAL_UTIL_SELECT query. - * (A cursor held past the end of its transaction no longer has any - * active executor state.) + * Where we store tuples for a held cursor or a PORTAL_UTIL_SELECT + * query. (A cursor held past the end of its transaction no longer has + * any active executor state.) */ - Tuplestorestate *holdStore; /* store for holdable cursors */ - MemoryContext holdContext; /* memory containing holdStore */ + Tuplestorestate *holdStore; /* store for holdable cursors */ + MemoryContext holdContext; /* memory containing holdStore */ /* * atStart, atEnd and portalPos indicate the current cursor position. - * portalPos is zero before the first row, N after fetching N'th row of - * query. After we run off the end, portalPos = # of rows in query, and - * atEnd is true. If portalPos overflows, set posOverflow (this causes - * us to stop relying on its value for navigation). Note that atStart - * implies portalPos == 0, but not the reverse (portalPos could have - * overflowed). + * portalPos is zero before the first row, N after fetching N'th row + * of query. After we run off the end, portalPos = # of rows in + * query, and atEnd is true. If portalPos overflows, set posOverflow + * (this causes us to stop relying on its value for navigation). Note + * that atStart implies portalPos == 0, but not the reverse (portalPos + * could have overflowed). */ bool atStart; bool atEnd; @@ -172,11 +173,11 @@ extern void PortalDrop(Portal portal, bool isError); extern void DropDependentPortals(MemoryContext queryContext); extern Portal GetPortalByName(const char *name); extern void PortalDefineQuery(Portal portal, - const char *sourceText, - const char *commandTag, - List *parseTrees, - List *planTrees, - MemoryContext queryContext); + const char *sourceText, + const char *commandTag, + List *parseTrees, + List *planTrees, + MemoryContext queryContext); extern void PortalCreateHoldStore(Portal portal); #endif /* PORTAL_H */ diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h index fd5e0c56b7..29f1923b93 100644 --- a/src/include/utils/rel.h +++ b/src/include/utils/rel.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: rel.h,v 1.65 2003/05/28 16:04:02 tgl Exp $ + * $Id: rel.h,v 1.66 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -132,8 +132,8 @@ typedef struct RelationData /* These are non-NULL only for an index relation: */ Form_pg_index rd_index; /* pg_index tuple describing this index */ - struct HeapTupleData *rd_indextuple; /* all of pg_index tuple */ - /* "struct HeapTupleData *" avoids need to include htup.h here */ + struct HeapTupleData *rd_indextuple; /* all of pg_index tuple */ + /* "struct HeapTupleData *" avoids need to include htup.h here */ Form_pg_am rd_am; /* pg_am tuple for index's AM */ /* index access support info (used only for an index relation) */ diff --git a/src/include/utils/selfuncs.h b/src/include/utils/selfuncs.h index cea19f2693..3eec90c942 100644 --- a/src/include/utils/selfuncs.h +++ b/src/include/utils/selfuncs.h @@ -8,7 +8,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: selfuncs.h,v 1.13 2003/05/15 15:50:20 petere Exp $ + * $Id: selfuncs.h,v 1.14 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -66,16 +66,16 @@ extern Datum nlikejoinsel(PG_FUNCTION_ARGS); extern Datum icnlikejoinsel(PG_FUNCTION_ARGS); extern Selectivity booltestsel(Query *root, BoolTestType booltesttype, - Node *arg, int varRelid, JoinType jointype); + Node *arg, int varRelid, JoinType jointype); extern Selectivity nulltestsel(Query *root, NullTestType nulltesttype, - Node *arg, int varRelid); + Node *arg, int varRelid); extern void mergejoinscansel(Query *root, Node *clause, Selectivity *leftscan, Selectivity *rightscan); extern double estimate_num_groups(Query *root, List *groupExprs, - double input_rows); + double input_rows); extern Datum btcostestimate(PG_FUNCTION_ARGS); extern Datum rtcostestimate(PG_FUNCTION_ARGS); diff --git a/src/include/utils/tuplestore.h b/src/include/utils/tuplestore.h index 6a021ba52f..4732a47ca7 100644 --- a/src/include/utils/tuplestore.h +++ b/src/include/utils/tuplestore.h @@ -8,7 +8,7 @@ * a dumbed-down version of tuplesort.c; it does no sorting of tuples * but can only store and regurgitate a sequence of tuples. However, * because no sort is required, it is allowed to start reading the sequence - * before it has all been written. This is particularly useful for cursors, + * before it has all been written. This is particularly useful for cursors, * because it allows random access within the already-scanned portion of * a query without having to process the underlying scan to completion. * A temporary file is used to handle the data if it exceeds the @@ -17,7 +17,7 @@ * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: tuplestore.h,v 1.11 2003/04/29 03:21:30 tgl Exp $ + * $Id: tuplestore.h,v 1.12 2003/08/04 00:43:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,8 +37,8 @@ typedef struct Tuplestorestate Tuplestorestate; */ extern Tuplestorestate *tuplestore_begin_heap(bool randomAccess, - bool interXact, - int maxKBytes); + bool interXact, + int maxKBytes); extern void tuplestore_puttuple(Tuplestorestate *state, void *tuple); diff --git a/src/interfaces/ecpg/compatlib/informix.c b/src/interfaces/ecpg/compatlib/informix.c index a1b1f9c566..15101094f5 100644 --- a/src/interfaces/ecpg/compatlib/informix.c +++ b/src/interfaces/ecpg/compatlib/informix.c @@ -10,17 +10,18 @@ #include #include -char * ECPGalloc(long, int); +char *ECPGalloc(long, int); static int -deccall2(Decimal *arg1, Decimal *arg2, int (*ptr)(Numeric *, Numeric *)) +deccall2(Decimal * arg1, Decimal * arg2, int (*ptr) (Numeric *, Numeric *)) { - Numeric *a1, *a2; - int i; + Numeric *a1, + *a2; + int i; if ((a1 = PGTYPESnumeric_new()) == NULL) return -1211; - + if ((a2 = PGTYPESnumeric_new()) == NULL) { PGTYPESnumeric_free(a1); @@ -33,37 +34,39 @@ deccall2(Decimal *arg1, Decimal *arg2, int (*ptr)(Numeric *, Numeric *)) PGTYPESnumeric_free(a2); return -1211; } - + if (PGTYPESnumeric_from_decimal(arg2, a2) != 0) { PGTYPESnumeric_free(a1); PGTYPESnumeric_free(a2); return -1211; } - - i = (*ptr)(a1, a2); - + + i = (*ptr) (a1, a2); + PGTYPESnumeric_free(a1); PGTYPESnumeric_free(a2); - + return (i); } static int -deccall3(Decimal *arg1, Decimal *arg2, Decimal *result, int (*ptr)(Numeric *, Numeric *, Numeric *)) +deccall3(Decimal * arg1, Decimal * arg2, Decimal * result, int (*ptr) (Numeric *, Numeric *, Numeric *)) { - Numeric *a1, *a2, *nres; - int i; + Numeric *a1, + *a2, + *nres; + int i; - if (risnull(CDECIMALTYPE, (char *)arg1) || risnull(CDECIMALTYPE, (char *)arg2)) + if (risnull(CDECIMALTYPE, (char *) arg1) || risnull(CDECIMALTYPE, (char *) arg2)) { - rsetnull(CDECIMALTYPE, (char *)result); + rsetnull(CDECIMALTYPE, (char *) result); return 0; } - + if ((a1 = PGTYPESnumeric_new()) == NULL) return -1211; - + if ((a2 = PGTYPESnumeric_new()) == NULL) { PGTYPESnumeric_free(a1); @@ -84,7 +87,7 @@ deccall3(Decimal *arg1, Decimal *arg2, Decimal *result, int (*ptr)(Numeric *, Nu PGTYPESnumeric_free(nres); return -1211; } - + if (PGTYPESnumeric_from_decimal(arg2, a2) != 0) { PGTYPESnumeric_free(a1); @@ -92,39 +95,41 @@ deccall3(Decimal *arg1, Decimal *arg2, Decimal *result, int (*ptr)(Numeric *, Nu PGTYPESnumeric_free(nres); return -1211; } - - i = (*ptr)(a1, a2, nres); - - if (i == 0) /* No error */ + + i = (*ptr) (a1, a2, nres); + + if (i == 0) /* No error */ PGTYPESnumeric_to_decimal(nres, result); PGTYPESnumeric_free(nres); PGTYPESnumeric_free(a1); PGTYPESnumeric_free(a2); - + return (i); } + /* we start with the numeric functions */ int -decadd(Decimal *arg1, Decimal *arg2, Decimal *sum) +decadd(Decimal * arg1, Decimal * arg2, Decimal * sum) { deccall3(arg1, arg2, sum, PGTYPESnumeric_add); if (errno == PGTYPES_NUM_OVERFLOW) return -1200; else if (errno != 0) - return -1201; - else return 0; + return -1201; + else + return 0; } int -deccmp(Decimal *arg1, Decimal *arg2) +deccmp(Decimal * arg1, Decimal * arg2) { - return(deccall2(arg1, arg2, PGTYPESnumeric_cmp)); + return (deccall2(arg1, arg2, PGTYPESnumeric_cmp)); } void -deccopy(Decimal *src, Decimal *target) +deccopy(Decimal * src, Decimal * target) { memcpy(target, src, sizeof(Decimal)); } @@ -132,10 +137,10 @@ deccopy(Decimal *src, Decimal *target) static char * strndup(const char *str, size_t len) { - int real_len = strlen(str); - int use_len = (real_len > len) ? len : real_len; - - char *new = malloc(use_len + 1); + int real_len = strlen(str); + int use_len = (real_len > len) ? len : real_len; + + char *new = malloc(use_len + 1); if (new) { @@ -149,15 +154,16 @@ strndup(const char *str, size_t len) } int -deccvasc(char *cp, int len, Decimal *np) +deccvasc(char *cp, int len, Decimal * np) { - char *str = strndup(cp, len); /* Decimal_in always converts the complete string */ - int ret = 0; - Numeric *result; + char *str = strndup(cp, len); /* Decimal_in always converts the + * complete string */ + int ret = 0; + Numeric *result; if (risnull(CSTRINGTYPE, cp)) { - rsetnull(CDECIMALTYPE, (char *)np); + rsetnull(CDECIMALTYPE, (char *) np); return 0; } @@ -170,36 +176,39 @@ deccvasc(char *cp, int len, Decimal *np) { switch (errno) { - case PGTYPES_NUM_OVERFLOW: ret = -1200; - break; - case PGTYPES_NUM_BAD_NUMERIC: ret = -1213; - break; - default: ret = -1216; - break; + case PGTYPES_NUM_OVERFLOW: + ret = -1200; + break; + case PGTYPES_NUM_BAD_NUMERIC: + ret = -1213; + break; + default: + ret = -1216; + break; } } else { - if (PGTYPESnumeric_to_decimal(result, np) !=0) + if (PGTYPESnumeric_to_decimal(result, np) != 0) ret = -1200; free(result); } } - + free(str); return ret; } int -deccvdbl(double dbl, Decimal *np) +deccvdbl(double dbl, Decimal * np) { - Numeric *nres = PGTYPESnumeric_new(); - int result = 1; - - if (risnull(CDOUBLETYPE, (char *)&dbl)) + Numeric *nres = PGTYPESnumeric_new(); + int result = 1; + + if (risnull(CDOUBLETYPE, (char *) &dbl)) { - rsetnull(CDECIMALTYPE, (char *)np); + rsetnull(CDECIMALTYPE, (char *) np); return 0; } @@ -211,18 +220,18 @@ deccvdbl(double dbl, Decimal *np) result = PGTYPESnumeric_to_decimal(nres, np); PGTYPESnumeric_free(nres); - return(result); + return (result); } int -deccvint(int in, Decimal *np) +deccvint(int in, Decimal * np) { - Numeric *nres = PGTYPESnumeric_new(); - int result = 1; - - if (risnull(CINTTYPE, (char *)&in)) + Numeric *nres = PGTYPESnumeric_new(); + int result = 1; + + if (risnull(CINTTYPE, (char *) &in)) { - rsetnull(CDECIMALTYPE, (char *)np); + rsetnull(CDECIMALTYPE, (char *) np); return 0; } @@ -234,18 +243,18 @@ deccvint(int in, Decimal *np) result = PGTYPESnumeric_to_decimal(nres, np); PGTYPESnumeric_free(nres); - return(result); + return (result); } int -deccvlong(long lng, Decimal *np) +deccvlong(long lng, Decimal * np) { - Numeric *nres = PGTYPESnumeric_new(); - int result = 1; - - if (risnull(CLONGTYPE, (char *)&lng)) + Numeric *nres = PGTYPESnumeric_new(); + int result = 1; + + if (risnull(CLONGTYPE, (char *) &lng)) { - rsetnull(CDECIMALTYPE, (char *)np); + rsetnull(CDECIMALTYPE, (char *) np); return 0; } @@ -257,80 +266,87 @@ deccvlong(long lng, Decimal *np) result = PGTYPESnumeric_to_decimal(nres, np); PGTYPESnumeric_free(nres); - return(result); + return (result); } int -decdiv(Decimal *n1, Decimal *n2, Decimal *n3) +decdiv(Decimal * n1, Decimal * n2, Decimal * n3) { - int i = deccall3(n1, n2, n3, PGTYPESnumeric_div); + int i = deccall3(n1, n2, n3, PGTYPESnumeric_div); if (i != 0) switch (errno) { - case PGTYPES_NUM_DIVIDE_ZERO: return -1202; - break; - case PGTYPES_NUM_OVERFLOW: return -1200; - break; - default: return -1201; - break; - } - - return 0; -} - -int -decmul(Decimal *n1, Decimal *n2, Decimal *n3) -{ - int i = deccall3(n1, n2, n3, PGTYPESnumeric_mul); - - if (i != 0) - switch (errno) - { - case PGTYPES_NUM_OVERFLOW: return -1200; - break; - default: return -1201; - break; + case PGTYPES_NUM_DIVIDE_ZERO: + return -1202; + break; + case PGTYPES_NUM_OVERFLOW: + return -1200; + break; + default: + return -1201; + break; } return 0; } int -decsub(Decimal *n1, Decimal *n2, Decimal *n3) +decmul(Decimal * n1, Decimal * n2, Decimal * n3) { - int i = deccall3(n1, n2, n3, PGTYPESnumeric_sub); + int i = deccall3(n1, n2, n3, PGTYPESnumeric_mul); if (i != 0) switch (errno) { - case PGTYPES_NUM_OVERFLOW: return -1200; - break; - default: return -1201; - break; + case PGTYPES_NUM_OVERFLOW: + return -1200; + break; + default: + return -1201; + break; } return 0; } int -dectoasc(Decimal *np, char *cp, int len, int right) +decsub(Decimal * n1, Decimal * n2, Decimal * n3) { - char *str; - Numeric *nres = PGTYPESnumeric_new(); + int i = deccall3(n1, n2, n3, PGTYPESnumeric_sub); + + if (i != 0) + switch (errno) + { + case PGTYPES_NUM_OVERFLOW: + return -1200; + break; + default: + return -1201; + break; + } + + return 0; +} + +int +dectoasc(Decimal * np, char *cp, int len, int right) +{ + char *str; + Numeric *nres = PGTYPESnumeric_new(); if (nres == NULL) return -1211; - if (risnull(CDECIMALTYPE, (char *)np)) + if (risnull(CDECIMALTYPE, (char *) np)) { - rsetnull(CSTRINGTYPE, (char *)cp); + rsetnull(CSTRINGTYPE, (char *) cp); return 0; } if (PGTYPESnumeric_from_decimal(np, nres) != 0) return -1211; - + if (right >= 0) str = PGTYPESnumeric_to_asc(nres, right); else @@ -339,26 +355,29 @@ dectoasc(Decimal *np, char *cp, int len, int right) PGTYPESnumeric_free(nres); if (!str) return -1; - - /* TODO: have to take care of len here and create exponatial notion if necessary */ + + /* + * TODO: have to take care of len here and create exponatial notion if + * necessary + */ strncpy(cp, str, len); - free (str); + free(str); return 0; } int -dectodbl(Decimal *np, double *dblp) +dectodbl(Decimal * np, double *dblp) { - Numeric *nres = PGTYPESnumeric_new(); - int i; + Numeric *nres = PGTYPESnumeric_new(); + int i; if (nres == NULL) return -1211; - + if (PGTYPESnumeric_from_decimal(np, nres) != 0) return -1211; - + i = PGTYPESnumeric_to_double(nres, dblp); PGTYPESnumeric_free(nres); @@ -366,118 +385,123 @@ dectodbl(Decimal *np, double *dblp) } int -dectoint(Decimal *np, int *ip) +dectoint(Decimal * np, int *ip) { - int ret; - Numeric *nres = PGTYPESnumeric_new(); + int ret; + Numeric *nres = PGTYPESnumeric_new(); if (nres == NULL) return -1211; - + if (PGTYPESnumeric_from_decimal(np, nres) != 0) return -1211; - + ret = PGTYPESnumeric_to_int(nres, ip); if (ret == PGTYPES_NUM_OVERFLOW) ret = -1200; - + return ret; } int -dectolong(Decimal *np, long *lngp) +dectolong(Decimal * np, long *lngp) { - int ret; - Numeric *nres = PGTYPESnumeric_new();; + int ret; + Numeric *nres = PGTYPESnumeric_new();; if (nres == NULL) return -1211; - + if (PGTYPESnumeric_from_decimal(np, nres) != 0) return -1211; - + ret = PGTYPESnumeric_to_long(nres, lngp); if (ret == PGTYPES_NUM_OVERFLOW) ret = -1200; - + return ret; } /* Now the date functions */ int -rdatestr (Date d, char *str) +rdatestr(Date d, char *str) { - char *tmp = PGTYPESdate_to_asc(d); + char *tmp = PGTYPESdate_to_asc(d); if (!tmp) return -1210; - + /* move to user allocated buffer */ strcpy(str, tmp); free(tmp); - + return 0; } int -rstrdate (char *str, Date *d) +rstrdate(char *str, Date * d) { - Date dat = PGTYPESdate_from_asc(str, NULL); + Date dat = PGTYPESdate_from_asc(str, NULL); if (errno != PGTYPES_DATE_BAD_DATE && dat == 0) return -1218; - *d=dat; + *d = dat; return 0; } void -rtoday (Date *d) +rtoday(Date * d) { PGTYPESdate_today(d); return; } int -rjulmdy (Date d, short mdy[3]) +rjulmdy(Date d, short mdy[3]) { - int mdy_int[3]; - + int mdy_int[3]; + PGTYPESdate_julmdy(d, mdy_int); - mdy[0] = (short)mdy_int[0]; - mdy[1] = (short)mdy_int[1]; - mdy[2] = (short)mdy_int[2]; + mdy[0] = (short) mdy_int[0]; + mdy[1] = (short) mdy_int[1]; + mdy[2] = (short) mdy_int[2]; return 0; } int -rdefmtdate (Date *d, char *fmt, char *str) +rdefmtdate(Date * d, char *fmt, char *str) { /* TODO: take care of DBCENTURY environment variable */ /* PGSQL functions allow all centuries */ if (PGTYPESdate_defmt_asc(d, fmt, str) == 0) return 0; - + switch (errno) { - case PGTYPES_DATE_ERR_ENOSHORTDATE: return -1209; + case PGTYPES_DATE_ERR_ENOSHORTDATE: + return -1209; case PGTYPES_DATE_ERR_EARGS: - case PGTYPES_DATE_ERR_ENOTDMY: return -1212; - case PGTYPES_DATE_BAD_DAY: return -1204; - case PGTYPES_DATE_BAD_MONTH: return -1205; - default: return -1206; + case PGTYPES_DATE_ERR_ENOTDMY: + return -1212; + case PGTYPES_DATE_BAD_DAY: + return -1204; + case PGTYPES_DATE_BAD_MONTH: + return -1205; + default: + return -1206; } } int -rfmtdate (Date d, char *fmt, char *str) +rfmtdate(Date d, char *fmt, char *str) { if (PGTYPESdate_fmt_asc(d, fmt, str) == 0) return 0; - + if (errno == ENOMEM) return -1211; @@ -485,9 +509,9 @@ rfmtdate (Date d, char *fmt, char *str) } int -rmdyjul (short mdy[3], Date *d) +rmdyjul(short mdy[3], Date * d) { - int mdy_int[3]; + int mdy_int[3]; mdy_int[0] = mdy[0]; mdy_int[1] = mdy[1]; @@ -499,58 +523,58 @@ rmdyjul (short mdy[3], Date *d) int rdayofweek(Date d) { - return(PGTYPESdate_dayofweek(d)); + return (PGTYPESdate_dayofweek(d)); } - + /* And the datetime stuff */ void -dtcurrent (Timestamp *ts) +dtcurrent(Timestamp *ts) { - PGTYPEStimestamp_current (ts); + PGTYPEStimestamp_current(ts); } int -dtcvasc (char *str, Timestamp *ts) +dtcvasc(char *str, Timestamp *ts) { - Timestamp ts_tmp; - int i; - char **endptr = &str; + Timestamp ts_tmp; + int i; + char **endptr = &str; - ts_tmp = PGTYPEStimestamp_from_asc(str, endptr); - i = errno; - if (i) { - return i; - } - if (**endptr) { - /* extra characters exist at the end */ - return -1264; - } + ts_tmp = PGTYPEStimestamp_from_asc(str, endptr); + i = errno; + if (i) + return i; + if (**endptr) + { + /* extra characters exist at the end */ + return -1264; + } + + /* everything went fine */ + *ts = ts_tmp; - /* everything went fine */ - *ts = ts_tmp; - return 0; } int -dtsub (Timestamp *ts1, Timestamp *ts2, Interval *iv) +dtsub(Timestamp *ts1, Timestamp *ts2, Interval *iv) { return PGTYPEStimestamp_sub(ts1, ts2, iv); } int -dttoasc (Timestamp *ts, char *output) +dttoasc(Timestamp *ts, char *output) { - char *asctime = PGTYPEStimestamp_to_asc( *ts ); - - strcpy (output, asctime); + char *asctime = PGTYPEStimestamp_to_asc(*ts); + + strcpy(output, asctime); free(asctime); return 0; } int -dttofmtasc (Timestamp *ts, char *output, int str_len, char *fmtstr) +dttofmtasc(Timestamp *ts, char *output, int str_len, char *fmtstr) { return PGTYPEStimestamp_fmt_asc(ts, output, str_len, fmtstr); } @@ -559,59 +583,65 @@ int intoasc(Interval *i, char *str) { str = PGTYPESinterval_to_asc(i); - + if (!str) return -errno; - + return 0; } /*************************************************************************** - rfmt.c - description - ------------------- - begin : Wed Apr 2 2003 - copyright : (C) 2003 by Carsten Wolff - email : carsten.wolff@credativ.de + rfmt.c - description + ------------------- + begin : Wed Apr 2 2003 + copyright : (C) 2003 by Carsten Wolff + email : carsten.wolff@credativ.de ***************************************************************************/ -static struct { - long val; - int maxdigits; - int digits; - int remaining; - char sign; - char *val_string; -} value; +static struct +{ + long val; + int maxdigits; + int digits; + int remaining; + char sign; + char *val_string; +} value; /** * initialize the struct, wich holds the different forms * of the long value */ -static void initValue(long lng_val) { - int i, div, dig; - char tmp[2] = " "; +static void +initValue(long lng_val) +{ + int i, + div, + dig; + char tmp[2] = " "; /* set some obvious things */ value.val = lng_val >= 0 ? lng_val : lng_val * (-1); value.sign = lng_val >= 0 ? '+' : '-'; - value.maxdigits = log10(2)*(8*sizeof(long)-1); + value.maxdigits = log10(2) * (8 * sizeof(long) - 1); /* determine the number of digits */ - for(i=1; i <= value.maxdigits; i++) { - if ((int)(value.val / pow(10, i)) != 0) { - value.digits = i+1; - } + for (i = 1; i <= value.maxdigits; i++) + { + if ((int) (value.val / pow(10, i)) != 0) + value.digits = i + 1; } value.remaining = value.digits; /* convert the long to string */ - value.val_string = (char *)malloc(value.digits + 1); - for(i=value.digits; i > 0; i--) { - div = pow(10,i); + value.val_string = (char *) malloc(value.digits + 1); + for (i = value.digits; i > 0; i--) + { + div = pow(10, i); dig = (value.val % div) / (div / 10); - tmp[0] = (char)(dig + 48); + tmp[0] = (char) (dig + 48); strcat(value.val_string, tmp); - } + } /* safety-net */ value.val_string[value.digits] = '\0'; /* clean up */ @@ -619,14 +649,18 @@ static void initValue(long lng_val) { } /* return the position oft the right-most dot in some string */ -static int getRightMostDot(char* str) { - size_t len = strlen(str); - int i,j; - j=0; - for(i=len-1; i >= 0; i--) { - if (str[i] == '.') { - return len-j-1; - } +static int +getRightMostDot(char *str) +{ + size_t len = strlen(str); + int i, + j; + + j = 0; + for (i = len - 1; i >= 0; i--) + { + if (str[i] == '.') + return len - j - 1; j++; } return -1; @@ -636,29 +670,36 @@ static int getRightMostDot(char* str) { int rfmtlong(long lng_val, char *fmt, char *outbuf) { - size_t fmt_len = strlen(fmt); - size_t temp_len; - int i, j, k, dotpos; - int leftalign = 0, blank = 0, sign = 0, entity = 0, - entitydone = 0, signdone = 0, brackets_ok = 0; - char *temp; - char tmp[2] = " "; - char lastfmt = ' ', fmtchar = ' '; + size_t fmt_len = strlen(fmt); + size_t temp_len; + int i, + j, + k, + dotpos; + int leftalign = 0, + blank = 0, + sign = 0, + entity = 0, + entitydone = 0, + signdone = 0, + brackets_ok = 0; + char *temp; + char tmp[2] = " "; + char lastfmt = ' ', + fmtchar = ' '; - temp = (char *) malloc(fmt_len+1); + temp = (char *) malloc(fmt_len + 1); /* put all info about the long in a struct */ initValue(lng_val); /* '<' is the only format, where we have to align left */ - if (strchr(fmt, (int)'<')) { + if (strchr(fmt, (int) '<')) leftalign = 1; - } /* '(' requires ')' */ - if (strchr(fmt, (int)'(') && strchr(fmt, (int)')')) { + if (strchr(fmt, (int) '(') && strchr(fmt, (int) ')')) brackets_ok = 1; - } /* get position of the right-most dot in the format-string */ /* and fill the temp-string wit '0's up to there. */ @@ -666,94 +707,122 @@ rfmtlong(long lng_val, char *fmt, char *outbuf) /* start to parse the formatstring */ temp[0] = '\0'; - j = 0; /* position in temp */ - k = value.digits - 1; /* position in the value_string */ - for(i=fmt_len-1, j=0; i>=0; i--, j++) { + j = 0; /* position in temp */ + k = value.digits - 1; /* position in the value_string */ + for (i = fmt_len - 1, j = 0; i >= 0; i--, j++) + { /* qualify, where we are in the value_string */ - if (k < 0) { - if (leftalign) { + if (k < 0) + { + if (leftalign) + { /* can't use strncat(,,0) here, Solaris would freek out */ temp[j] = '\0'; break; } blank = 1; - if (k == -2) { + if (k == -2) entity = 1; - } - else if (k == -1) { + else if (k == -1) sign = 1; - } } /* if we're right side of the right-most dot, print '0' */ - if (dotpos >= 0 && dotpos <= i) { - if (dotpos < i) { - if (fmt[i] == ')') tmp[0] = value.sign == '-' ? ')' : ' '; - else tmp[0] = '0'; + if (dotpos >= 0 && dotpos <= i) + { + if (dotpos < i) + { + if (fmt[i] == ')') + tmp[0] = value.sign == '-' ? ')' : ' '; + else + tmp[0] = '0'; } - else { + else tmp[0] = '.'; - } strcat(temp, tmp); continue; } /* the ',' needs special attention, if it is in the blank area */ - if (blank && fmt[i] == ',') fmtchar = lastfmt; - else fmtchar = fmt[i]; + if (blank && fmt[i] == ',') + fmtchar = lastfmt; + else + fmtchar = fmt[i]; /* analyse this format-char */ - switch(fmtchar) { + switch (fmtchar) + { case ',': tmp[0] = ','; k++; break; case '*': - if (blank) tmp[0] = '*'; - else tmp[0] = value.val_string[k]; + if (blank) + tmp[0] = '*'; + else + tmp[0] = value.val_string[k]; break; case '&': - if (blank) tmp[0] = '0'; - else tmp[0] = value.val_string[k]; + if (blank) + tmp[0] = '0'; + else + tmp[0] = value.val_string[k]; break; case '#': - if (blank) tmp[0] = ' '; - else tmp[0] = value.val_string[k]; + if (blank) + tmp[0] = ' '; + else + tmp[0] = value.val_string[k]; break; case '<': tmp[0] = value.val_string[k]; break; case '-': - if (sign && value.sign == '-' && !signdone) { + if (sign && value.sign == '-' && !signdone) + { tmp[0] = '-'; signdone = 1; } - else if (blank) tmp[0] = ' '; - else tmp[0] = value.val_string[k]; + else if (blank) + tmp[0] = ' '; + else + tmp[0] = value.val_string[k]; break; case '+': - if (sign && !signdone) { + if (sign && !signdone) + { tmp[0] = value.sign; signdone = 1; } - else if (blank) tmp[0] = ' '; - else tmp[0] = value.val_string[k]; + else if (blank) + tmp[0] = ' '; + else + tmp[0] = value.val_string[k]; break; case '(': - if (sign && brackets_ok && value.sign == '-') tmp[0] = '('; - else if (blank) tmp[0] = ' '; - else tmp[0] = value.val_string[k]; + if (sign && brackets_ok && value.sign == '-') + tmp[0] = '('; + else if (blank) + tmp[0] = ' '; + else + tmp[0] = value.val_string[k]; break; case ')': - if (brackets_ok && value.sign == '-') tmp[0] = ')'; - else tmp[0] = ' '; + if (brackets_ok && value.sign == '-') + tmp[0] = ')'; + else + tmp[0] = ' '; break; case '$': - if (blank && !entitydone) { + if (blank && !entitydone) + { tmp[0] = '$'; entitydone = 1; } - else if (blank) tmp[0] = ' '; - else tmp[0] = value.val_string[k]; + else if (blank) + tmp[0] = ' '; + else + tmp[0] = value.val_string[k]; break; - default: tmp[0] = fmt[i]; + default: + tmp[0] = fmt[i]; } strcat(temp, tmp); lastfmt = fmt[i]; @@ -765,9 +834,10 @@ rfmtlong(long lng_val, char *fmt, char *outbuf) /* reverse the temp-string and put it into the outbuf */ temp_len = strlen(temp); outbuf[0] = '\0'; - for(i=temp_len-1; i>=0; i--) { + for (i = temp_len - 1; i >= 0; i--) + { tmp[0] = temp[i]; - strcat(outbuf, tmp); + strcat(outbuf, tmp); } outbuf[temp_len] = '\0'; @@ -782,22 +852,23 @@ void rupshift(char *str) { for (; *str != '\0'; str++) - if (islower(*str)) *str = toupper(*str); + if (islower(*str)) + *str = toupper(*str); return; } int byleng(char *str, int len) { - for (len--; str[len] && str[len] == ' '; len--); - return (len+1); + for (len--; str[len] && str[len] == ' '; len--); + return (len + 1); } void ldchar(char *src, int len, char *dest) { - memmove(dest, src, len); - dest[len]=0; + memmove(dest, src, len); + dest[len] = 0; } int @@ -825,17 +896,17 @@ rtypwidth(int sqltype, int sqllen) } int -dtcvfmtasc (char *inbuf, char *fmtstr, dtime_t *dtvalue) +dtcvfmtasc(char *inbuf, char *fmtstr, dtime_t * dtvalue) { - return PGTYPEStimestamp_defmt_asc(inbuf, fmtstr, dtvalue); + return PGTYPEStimestamp_defmt_asc(inbuf, fmtstr, dtvalue); } static struct var_list { - int number; - void *pointer; + int number; + void *pointer; struct var_list *next; -} *ivlist = NULL; +} *ivlist = NULL; void ECPG_informix_set_var(int number, void *pointer, int lineno) @@ -853,7 +924,7 @@ ECPG_informix_set_var(int number, void *pointer, int lineno) } /* a new one has to be added */ - ptr = (struct var_list *) ECPGalloc (sizeof(struct var_list), lineno); + ptr = (struct var_list *) ECPGalloc(sizeof(struct var_list), lineno); ptr->number = number; ptr->pointer = pointer; ptr->next = ivlist; @@ -869,14 +940,15 @@ ECPG_informix_get_var(int number) return (ptr) ? ptr->pointer : NULL; } -int rsetnull(int t, char *ptr) +int +rsetnull(int t, char *ptr) { ECPGset_informix_null(t, ptr); return 0; } -int risnull(int t, char *ptr) +int +risnull(int t, char *ptr) { - return(ECPGis_informix_null(t, ptr)); + return (ECPGis_informix_null(t, ptr)); } - diff --git a/src/interfaces/ecpg/ecpglib/connect.c b/src/interfaces/ecpg/ecpglib/connect.c index 1030b041ab..679efb6466 100644 --- a/src/interfaces/ecpg/ecpglib/connect.c +++ b/src/interfaces/ecpg/ecpglib/connect.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/connect.c,v 1.14 2003/08/01 13:53:36 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/connect.c,v 1.15 2003/08/04 00:43:32 momjian Exp $ */ #define POSTGRES_ECPG_INTERNAL #include "postgres_fe.h" @@ -15,49 +15,48 @@ #ifdef USE_THREADS static pthread_mutex_t connections_mutex = PTHREAD_MUTEX_INITIALIZER; #endif -static struct connection *all_connections = NULL; +static struct connection *all_connections = NULL; static struct connection *actual_connection = NULL; static struct connection * ecpg_get_connection_nr(const char *connection_name) { - struct connection *ret = NULL; + struct connection *ret = NULL; - if( (connection_name == NULL) || (strcmp(connection_name, "CURRENT") == 0) ) - { - ret = actual_connection; - } - else - { - struct connection *con; - - for( con = all_connections; con != NULL; con = con->next) + if ((connection_name == NULL) || (strcmp(connection_name, "CURRENT") == 0)) + ret = actual_connection; + else { - if( strcmp(connection_name, con->name) == 0 ) - break; - } - ret = con; - } + struct connection *con; - return( ret ); + for (con = all_connections; con != NULL; con = con->next) + { + if (strcmp(connection_name, con->name) == 0) + break; + } + ret = con; + } + + return (ret); } struct connection * ECPGget_connection(const char *connection_name) { - struct connection *ret = NULL; -#ifdef USE_THREADS - pthread_mutex_lock(&connections_mutex); -#endif - - ret = ecpg_get_connection_nr(connection_name); + struct connection *ret = NULL; #ifdef USE_THREADS - pthread_mutex_unlock(&connections_mutex); + pthread_mutex_lock(&connections_mutex); #endif - return (ret); - + ret = ecpg_get_connection_nr(connection_name); + +#ifdef USE_THREADS + pthread_mutex_unlock(&connections_mutex); +#endif + + return (ret); + } static void @@ -70,9 +69,10 @@ ecpg_finish(struct connection * act) PQfinish(act->connection); - /* no need to lock connections_mutex - we're always called - by ECPGdisconnect or ECPGconnect, which are holding - the lock */ + /* + * no need to lock connections_mutex - we're always called by + * ECPGdisconnect or ECPGconnect, which are holding the lock + */ /* remove act from the list */ if (act == all_connections) @@ -158,26 +158,26 @@ ECPGsetconn(int lineno, const char *connection_name) static void ECPGnoticeReceiver(void *arg, const PGresult *result) { - char *sqlstate = PQresultErrorField(result, 'C'); - char *message = PQresultErrorField(result, 'M'); + char *sqlstate = PQresultErrorField(result, 'C'); + char *message = PQresultErrorField(result, 'M'); struct sqlca_t *sqlca = ECPGget_sqlca(); - int sqlcode; + int sqlcode; /* these are not warnings */ - if (strncmp(sqlstate, "00", 2)==0) + if (strncmp(sqlstate, "00", 2) == 0) return; ECPGlog("%s", message); /* map to SQLCODE for backward compatibility */ - if (strcmp(sqlstate, ECPG_SQLSTATE_INVALID_CURSOR_NAME)==0) + if (strcmp(sqlstate, ECPG_SQLSTATE_INVALID_CURSOR_NAME) == 0) sqlcode = ECPG_WARNING_UNKNOWN_PORTAL; - else if (strcmp(sqlstate, ECPG_SQLSTATE_ACTIVE_SQL_TRANSACTION)==0) + else if (strcmp(sqlstate, ECPG_SQLSTATE_ACTIVE_SQL_TRANSACTION) == 0) sqlcode = ECPG_WARNING_IN_TRANSACTION; - else if (strcmp(sqlstate, ECPG_SQLSTATE_NO_ACTIVE_SQL_TRANSACTION)==0) + else if (strcmp(sqlstate, ECPG_SQLSTATE_NO_ACTIVE_SQL_TRANSACTION) == 0) sqlcode = ECPG_WARNING_NO_TRANSACTION; - else if (strcmp(sqlstate, ECPG_SQLSTATE_DUPLICATE_CURSOR)==0) + else if (strcmp(sqlstate, ECPG_SQLSTATE_DUPLICATE_CURSOR) == 0) sqlcode = ECPG_WARNING_PORTAL_EXISTS; else sqlcode = 0; @@ -210,21 +210,23 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p *options = NULL; ECPGinit_sqlca(sqlca); - + if (INFORMIX_MODE(compat)) { - char *envname; - - /* Informix uses an environment variable DBPATH that overrides - * the connection parameters given here. - * We do the same with PG_DBPATH as the syntax is different. */ + char *envname; + + /* + * Informix uses an environment variable DBPATH that overrides the + * connection parameters given here. We do the same with PG_DBPATH + * as the syntax is different. + */ envname = getenv("PG_DBPATH"); if (envname) { ECPGfree(dbname); dbname = strdup(envname); } - + } if ((this = (struct connection *) ECPGalloc(sizeof(struct connection), lineno)) == NULL) @@ -378,21 +380,21 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p if (PQstatus(this->connection) == CONNECTION_BAD) { - const char *errmsg = PQerrorMessage(this->connection); - char *db = realname ? realname : ""; + const char *errmsg = PQerrorMessage(this->connection); + char *db = realname ? realname : ""; ecpg_finish(this); #ifdef USE_THREADS pthread_mutex_unlock(&connections_mutex); #endif ECPGlog("connect: could not open database %s on %s port %s %s%s%s%s in line %d\n\t%s\n", - db, + db, host ? host : "", port ? port : "", options ? "with options " : "", options ? options : "", user ? "for user " : "", user ? user : "", lineno, errmsg); - + ECPGraise(lineno, ECPG_CONNECT, ECPG_SQLSTATE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION, db); if (host) ECPGfree(host); @@ -455,14 +457,14 @@ ECPGdisconnect(int lineno, const char *connection_name) con = ecpg_get_connection_nr(connection_name); if (!ECPGinit(con, connection_name, lineno)) - { + { #ifdef USE_THREADS - pthread_mutex_unlock(&connections_mutex); + pthread_mutex_unlock(&connections_mutex); #endif - return (false); - } + return (false); + } else - ecpg_finish(con); + ecpg_finish(con); } #ifdef USE_THREADS diff --git a/src/interfaces/ecpg/ecpglib/data.c b/src/interfaces/ecpg/ecpglib/data.c index 14e459d1b6..e095ed671d 100644 --- a/src/interfaces/ecpg/ecpglib/data.c +++ b/src/interfaces/ecpg/ecpglib/data.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/data.c,v 1.15 2003/08/01 13:53:36 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/data.c,v 1.16 2003/08/04 00:43:32 momjian Exp $ */ #define POSTGRES_ECPG_INTERNAL #include "postgres_fe.h" @@ -24,7 +24,7 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, { struct sqlca_t *sqlca = ECPGget_sqlca(); char *pval = (char *) PQgetvalue(results, act_tuple, act_field); - int value_for_indicator = 0; + int value_for_indicator = 0; ECPGlog("ECPGget_data line %d: RESULT: %s offset: %ld\n", lineno, pval ? pval : "", offset); @@ -54,11 +54,12 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, /* We will have to decode the value */ /* - * check for null value and set indicator accordingly, i.e. -1 if NULL and 0 if not + * check for null value and set indicator accordingly, i.e. -1 if NULL + * and 0 if not */ if (PQgetisnull(results, act_tuple, act_field)) value_for_indicator = -1; - + switch (ind_type) { case ECPGt_short: @@ -81,11 +82,13 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, #endif /* HAVE_LONG_LONG_INT_64 */ case ECPGt_NO_INDICATOR: if (value_for_indicator == -1) - { + { if (force_indicator == false) { - /* Informix has an additional way to specify NULLs - * note that this uses special values to denote NULL */ + /* + * Informix has an additional way to specify NULLs + * note that this uses special values to denote NULL + */ ECPGset_informix_null(type, var + offset * act_tuple); } else @@ -109,13 +112,13 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, switch (type) { long res; - unsigned long ures; + unsigned long ures; double dres; - char *scan_length; - Numeric *nres; + char *scan_length; + Numeric *nres; Date ddres; Timestamp tres; - Interval *ires; + Interval *ires; case ECPGt_short: case ECPGt_int: @@ -294,9 +297,7 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, case ECPGt_unsigned_char: { if (varcharsize == 0) - { - strncpy((char *) ((long) var + offset * act_tuple), pval, strlen(pval)+1); - } + strncpy((char *) ((long) var + offset * act_tuple), pval, strlen(pval) + 1); else { strncpy((char *) ((long) var + offset * act_tuple), pval, varcharsize); @@ -340,9 +341,7 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, variable->len = strlen(pval); if (varcharsize == 0) - { strncpy(variable->arr, pval, variable->len); - } else { strncpy(variable->arr, pval, varcharsize); @@ -403,12 +402,12 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, else nres = PGTYPESnumeric_from_asc("0.0", &scan_length); - if (type == ECPGt_numeric) - PGTYPESnumeric_copy(nres, (Numeric *)(var + offset * act_tuple)); + if (type == ECPGt_numeric) + PGTYPESnumeric_copy(nres, (Numeric *) (var + offset * act_tuple)); else - PGTYPESnumeric_to_decimal(nres, (Decimal *)(var + offset * act_tuple)); + PGTYPESnumeric_to_decimal(nres, (Decimal *) (var + offset * act_tuple)); break; - + case ECPGt_interval: if (pval) { @@ -430,7 +429,7 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, else ires = PGTYPESinterval_from_asc("0 seconds", NULL); - PGTYPESinterval_copy(ires, (Interval *)(var + offset * act_tuple)); + PGTYPESinterval_copy(ires, (Interval *) (var + offset * act_tuple)); break; case ECPGt_date: if (pval) @@ -450,7 +449,7 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, return (false); } - *((Date *)(var + offset * act_tuple)) = ddres; + *((Date *) (var + offset * act_tuple)) = ddres; } break; @@ -472,10 +471,10 @@ ECPGget_data(const PGresult *results, int act_tuple, int act_field, int lineno, return (false); } - *((Timestamp *)(var + offset * act_tuple)) = tres; + *((Timestamp *) (var + offset * act_tuple)) = tres; } break; - + default: ECPGraise(lineno, ECPG_UNSUPPORTED, ECPG_SQLSTATE_ECPG_INTERNAL_ERROR, ECPGtype_name(type)); return (false); diff --git a/src/interfaces/ecpg/ecpglib/descriptor.c b/src/interfaces/ecpg/ecpglib/descriptor.c index 0beae2d93a..839fc780cb 100644 --- a/src/interfaces/ecpg/ecpglib/descriptor.c +++ b/src/interfaces/ecpg/ecpglib/descriptor.c @@ -1,6 +1,6 @@ /* dynamic SQL support routines * - * $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/descriptor.c,v 1.5 2003/08/01 13:53:36 petere Exp $ + * $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/descriptor.c,v 1.6 2003/08/04 00:43:32 momjian Exp $ */ #define POSTGRES_ECPG_INTERNAL @@ -454,7 +454,7 @@ ECPGdescriptor_lvalue(int line, const char *descriptor) } bool -ECPGdescribe(int line, bool input, const char *statement, ...) +ECPGdescribe(int line, bool input, const char *statement,...) { ECPGlog("ECPGdescribe called on line %d for %s in %s\n", line, (input) ? "input" : "output", statement); return false; diff --git a/src/interfaces/ecpg/ecpglib/error.c b/src/interfaces/ecpg/ecpglib/error.c index cfeb4e65b0..33bac6e892 100644 --- a/src/interfaces/ecpg/ecpglib/error.c +++ b/src/interfaces/ecpg/ecpglib/error.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/error.c,v 1.5 2003/08/01 13:53:36 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/error.c,v 1.6 2003/08/04 00:43:32 momjian Exp $ */ #define POSTGRES_ECPG_INTERNAL #include "postgres_fe.h" @@ -13,9 +13,10 @@ void -ECPGraise(int line, int code, const char * sqlstate, const char *str) +ECPGraise(int line, int code, const char *sqlstate, const char *str) { struct sqlca_t *sqlca = ECPGget_sqlca(); + sqlca->sqlcode = code; strncpy(sqlca->sqlstate, sqlstate, sizeof(sqlca->sqlstate)); @@ -161,8 +162,8 @@ ECPGraise_backend(int line, PGresult *result, PGconn *conn, int compat) /* copy error message */ snprintf(sqlca->sqlerrm.sqlerrmc, sizeof(sqlca->sqlerrm.sqlerrmc), - "'%s' in line %d.", - result ? PQresultErrorField(result, 'M') : PQerrorMessage(conn), + "'%s' in line %d.", + result ? PQresultErrorField(result, 'M') : PQerrorMessage(conn), line); sqlca->sqlerrm.sqlerrml = strlen(sqlca->sqlerrm.sqlerrmc); @@ -172,9 +173,9 @@ ECPGraise_backend(int line, PGresult *result, PGconn *conn, int compat) sizeof(sqlca->sqlstate)); /* assign SQLCODE for backward compatibility */ - if (strncmp(sqlca->sqlstate, "23505", sizeof(sqlca->sqlstate))==0) + if (strncmp(sqlca->sqlstate, "23505", sizeof(sqlca->sqlstate)) == 0) sqlca->sqlcode = INFORMIX_MODE(compat) ? ECPG_INFORMIX_DUPLICATE_KEY : ECPG_DUPLICATE_KEY; - if (strncmp(sqlca->sqlstate, "21000", sizeof(sqlca->sqlstate))==0) + if (strncmp(sqlca->sqlstate, "21000", sizeof(sqlca->sqlstate)) == 0) sqlca->sqlcode = INFORMIX_MODE(compat) ? ECPG_INFORMIX_SUBSELECT_NOT_ONE : ECPG_SUBSELECT_NOT_ONE; else sqlca->sqlcode = ECPG_PGSQL; diff --git a/src/interfaces/ecpg/ecpglib/execute.c b/src/interfaces/ecpg/ecpglib/execute.c index 0d4247897d..c45441d47c 100644 --- a/src/interfaces/ecpg/ecpglib/execute.c +++ b/src/interfaces/ecpg/ecpglib/execute.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/execute.c,v 1.22 2003/08/01 13:53:36 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/execute.c,v 1.23 2003/08/04 00:43:32 momjian Exp $ */ /* * The aim is to get a simpler inteface to the database routines. @@ -65,7 +65,7 @@ quote_postgres(char *arg, int lineno) res[ri++] = '\''; res[ri] = '\0'; - + return res; } @@ -138,13 +138,16 @@ create_statement(int lineno, int compat, int force_indicator, struct connection else var->value = var->pointer; - /* negative values are used to indicate an array without given bounds */ + /* + * negative values are used to indicate an array without given + * bounds + */ /* reset to zero for us */ if (var->arrsize < 0) var->arrsize = 0; if (var->varcharsize < 0) var->varcharsize = 0; - + var->ind_type = va_arg(ap, enum ECPGttype); var->ind_pointer = va_arg(ap, char *); var->ind_varcharsize = va_arg(ap, long); @@ -157,8 +160,11 @@ create_statement(int lineno, int compat, int force_indicator, struct connection var->ind_value = *((char **) (var->ind_pointer)); else var->ind_value = var->ind_pointer; - - /* negative values are used to indicate an array without given bounds */ + + /* + * negative values are used to indicate an array without given + * bounds + */ /* reset to zero for us */ if (var->ind_arrsize < 0) var->ind_arrsize = 0; @@ -482,11 +488,11 @@ ECPGstore_input(const struct statement * stmt, const struct variable * var, * we do not know if the attribute is an array here */ #if 0 - if (var->arrsize > 1 && ...) - { + if (var->arrsize > 1 &&...) + { ECPGraise(stmt->lineno, ECPG_ARRAY_INSERT, ECPG_SQLSTATE_DATATYPE_MISMATCH, NULL); return false; - } + } #endif /* @@ -739,7 +745,7 @@ ECPGstore_input(const struct statement * stmt, const struct variable * var, break; case ECPGt_bool: - if (!(mallocedval = ECPGalloc(var->arrsize +sizeof ("array []"), stmt->lineno))) + if (!(mallocedval = ECPGalloc(var->arrsize + sizeof("array []"), stmt->lineno))) return false; if (var->arrsize > 1) @@ -838,30 +844,30 @@ ECPGstore_input(const struct statement * stmt, const struct variable * var, case ECPGt_decimal: case ECPGt_numeric: { - char *str = NULL; - int slen; - Numeric *nval = PGTYPESnumeric_new(); - + char *str = NULL; + int slen; + Numeric *nval = PGTYPESnumeric_new(); + if (var->arrsize > 1) { for (element = 0; element < var->arrsize; element++) { if (var->type == ECPGt_numeric) - PGTYPESnumeric_copy((Numeric *)((var + var->offset * element)->value), nval); + PGTYPESnumeric_copy((Numeric *) ((var + var->offset * element)->value), nval); else - PGTYPESnumeric_from_decimal((Decimal *)((var + var->offset * element)->value), nval); - + PGTYPESnumeric_from_decimal((Decimal *) ((var + var->offset * element)->value), nval); + str = PGTYPESnumeric_to_asc(nval, 0); PGTYPESnumeric_free(nval); - slen = strlen (str); - + slen = strlen(str); + if (!(mallocedval = ECPGrealloc(mallocedval, strlen(mallocedval) + slen + sizeof("array [] "), stmt->lineno))) return false; - + if (!element) strcpy(mallocedval, "array ["); - - strncpy(mallocedval + strlen(mallocedval), str , slen + 1); + + strncpy(mallocedval + strlen(mallocedval), str, slen + 1); strcpy(mallocedval + strlen(mallocedval), ","); } strcpy(mallocedval + strlen(mallocedval) - 1, "]"); @@ -869,22 +875,22 @@ ECPGstore_input(const struct statement * stmt, const struct variable * var, else { if (var->type == ECPGt_numeric) - PGTYPESnumeric_copy((Numeric *)(var->value), nval); + PGTYPESnumeric_copy((Numeric *) (var->value), nval); else - PGTYPESnumeric_from_decimal((Decimal *)(var->value), nval); - + PGTYPESnumeric_from_decimal((Decimal *) (var->value), nval); + str = PGTYPESnumeric_to_asc(nval, 0); PGTYPESnumeric_free(nval); - slen = strlen (str); - + slen = strlen(str); + if (!(mallocedval = ECPGalloc(slen + 1, stmt->lineno))) return false; - strncpy(mallocedval, str , slen); + strncpy(mallocedval, str, slen); mallocedval[slen] = '\0'; } - + *tobeinserted_p = mallocedval; *malloced_p = true; free(str); @@ -893,41 +899,41 @@ ECPGstore_input(const struct statement * stmt, const struct variable * var, case ECPGt_interval: { - char *str = NULL; - int slen; - + char *str = NULL; + int slen; + if (var->arrsize > 1) { for (element = 0; element < var->arrsize; element++) { - str = quote_postgres(PGTYPESinterval_to_asc((Interval *)((var + var->offset * element)->value)), stmt->lineno); - slen = strlen (str); - + str = quote_postgres(PGTYPESinterval_to_asc((Interval *) ((var + var->offset * element)->value)), stmt->lineno); + slen = strlen(str); + if (!(mallocedval = ECPGrealloc(mallocedval, strlen(mallocedval) + slen + sizeof("array [],interval "), stmt->lineno))) return false; - + if (!element) strcpy(mallocedval, "array ["); - + strcpy(mallocedval + strlen(mallocedval), "interval "); - strncpy(mallocedval + strlen(mallocedval), str , slen + 1); + strncpy(mallocedval + strlen(mallocedval), str, slen + 1); strcpy(mallocedval + strlen(mallocedval), ","); } strcpy(mallocedval + strlen(mallocedval) - 1, "]"); } else { - str = quote_postgres(PGTYPESinterval_to_asc((Interval *)(var->value)), stmt->lineno); - slen = strlen (str); - + str = quote_postgres(PGTYPESinterval_to_asc((Interval *) (var->value)), stmt->lineno); + slen = strlen(str); + if (!(mallocedval = ECPGalloc(slen + sizeof("interval ") + 1, stmt->lineno))) return false; strcpy(mallocedval, "interval "); /* also copy trailing '\0' */ - strncpy(mallocedval + strlen(mallocedval), str , slen + 1); + strncpy(mallocedval + strlen(mallocedval), str, slen + 1); } - + *tobeinserted_p = mallocedval; *malloced_p = true; free(str); @@ -936,90 +942,90 @@ ECPGstore_input(const struct statement * stmt, const struct variable * var, case ECPGt_date: { - char *str = NULL; - int slen; - + char *str = NULL; + int slen; + if (var->arrsize > 1) { for (element = 0; element < var->arrsize; element++) { - str = quote_postgres(PGTYPESdate_to_asc(*(Date *)((var + var->offset * element)->value)), stmt->lineno); - slen = strlen (str); - + str = quote_postgres(PGTYPESdate_to_asc(*(Date *) ((var + var->offset * element)->value)), stmt->lineno); + slen = strlen(str); + if (!(mallocedval = ECPGrealloc(mallocedval, strlen(mallocedval) + slen + sizeof("array [],date "), stmt->lineno))) return false; - + if (!element) strcpy(mallocedval, "array ["); - + strcpy(mallocedval + strlen(mallocedval), "date "); - strncpy(mallocedval + strlen(mallocedval), str , slen + 1); + strncpy(mallocedval + strlen(mallocedval), str, slen + 1); strcpy(mallocedval + strlen(mallocedval), ","); } strcpy(mallocedval + strlen(mallocedval) - 1, "]"); } else { - str = quote_postgres(PGTYPESdate_to_asc(*(Date *)(var->value)), stmt->lineno); - slen = strlen (str); - + str = quote_postgres(PGTYPESdate_to_asc(*(Date *) (var->value)), stmt->lineno); + slen = strlen(str); + if (!(mallocedval = ECPGalloc(slen + sizeof("date ") + 1, stmt->lineno))) return false; strcpy(mallocedval, "date "); /* also copy trailing '\0' */ - strncpy(mallocedval + strlen(mallocedval), str , slen + 1); + strncpy(mallocedval + strlen(mallocedval), str, slen + 1); } - + *tobeinserted_p = mallocedval; *malloced_p = true; free(str); } break; - + case ECPGt_timestamp: { - char *str = NULL; - int slen; - + char *str = NULL; + int slen; + if (var->arrsize > 1) { for (element = 0; element < var->arrsize; element++) { - str = quote_postgres(PGTYPEStimestamp_to_asc(*(Timestamp *)((var + var->offset * element)->value)), stmt->lineno); - slen = strlen (str); - + str = quote_postgres(PGTYPEStimestamp_to_asc(*(Timestamp *) ((var + var->offset * element)->value)), stmt->lineno); + slen = strlen(str); + if (!(mallocedval = ECPGrealloc(mallocedval, strlen(mallocedval) + slen + sizeof("array [], timestamp "), stmt->lineno))) return false; - + if (!element) strcpy(mallocedval, "array ["); - + strcpy(mallocedval + strlen(mallocedval), "timestamp "); - strncpy(mallocedval + strlen(mallocedval), str , slen + 1); + strncpy(mallocedval + strlen(mallocedval), str, slen + 1); strcpy(mallocedval + strlen(mallocedval), ","); } strcpy(mallocedval + strlen(mallocedval) - 1, "]"); } else { - str = quote_postgres(PGTYPEStimestamp_to_asc(*(Timestamp *)(var->value)), stmt->lineno); - slen = strlen (str); - + str = quote_postgres(PGTYPEStimestamp_to_asc(*(Timestamp *) (var->value)), stmt->lineno); + slen = strlen(str); + if (!(mallocedval = ECPGalloc(slen + sizeof("timestamp") + 1, stmt->lineno))) return false; strcpy(mallocedval, "timestamp "); /* also copy trailing '\0' */ - strncpy(mallocedval + strlen(mallocedval), str , slen + 1); + strncpy(mallocedval + strlen(mallocedval), str, slen + 1); } - + *tobeinserted_p = mallocedval; *malloced_p = true; free(str); } break; - + default: /* Not implemented yet */ ECPGraise(stmt->lineno, ECPG_UNSUPPORTED, ECPG_SQLSTATE_ECPG_INTERNAL_ERROR, (char *) ECPGtype_name(var->type)); @@ -1219,10 +1225,10 @@ ECPGexecute(struct statement * stmt) sqlca->sqlerrd[2] = atol(PQcmdTuples(results)); ECPGlog("ECPGexecute line %d Ok: %s\n", stmt->lineno, cmdstat); if (stmt->compat != ECPG_COMPAT_INFORMIX_SE && - !sqlca->sqlerrd[2] && - ( !strncmp(cmdstat, "UPDATE", 6) - || !strncmp(cmdstat, "INSERT", 6) - || !strncmp(cmdstat, "DELETE", 6))) + !sqlca->sqlerrd[2] && + (!strncmp(cmdstat, "UPDATE", 6) + || !strncmp(cmdstat, "INSERT", 6) + || !strncmp(cmdstat, "DELETE", 6))) ECPGraise(stmt->lineno, ECPG_NOT_FOUND, ECPG_SQLSTATE_NO_DATA, NULL); break; case PGRES_NONFATAL_ERROR: @@ -1326,4 +1332,3 @@ ECPGdo_descriptor(int line, const char *connection, ECPGt_descriptor, descriptor, 0L, 0L, 0L, ECPGt_NO_INDICATOR, NULL, 0L, 0L, 0L, ECPGt_EORT); } - diff --git a/src/interfaces/ecpg/ecpglib/extern.h b/src/interfaces/ecpg/ecpglib/extern.h index d98f158bac..3976d5b24d 100644 --- a/src/interfaces/ecpg/ecpglib/extern.h +++ b/src/interfaces/ecpg/ecpglib/extern.h @@ -5,7 +5,11 @@ #include "libpq-fe.h" #include "sqlca.h" -enum COMPAT_MODE { ECPG_COMPAT_PGSQL = 0, ECPG_COMPAT_INFORMIX, ECPG_COMPAT_INFORMIX_SE}; +enum COMPAT_MODE +{ + ECPG_COMPAT_PGSQL = 0, ECPG_COMPAT_INFORMIX, ECPG_COMPAT_INFORMIX_SE +}; + #define INFORMIX_MODE(X) ((X) == ECPG_COMPAT_INFORMIX || (X) == ECPG_COMPAT_INFORMIX_SE) /* Here are some methods used by the lib. */ @@ -51,7 +55,7 @@ struct statement char *command; struct connection *connection; enum COMPAT_MODE compat; - bool force_indicator; + bool force_indicator; struct variable *inlist; struct variable *outlist; }; @@ -109,7 +113,7 @@ bool ECPGstore_result(const PGresult *results, int act_field, #define ECPG_SQLSTATE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION "08001" #define ECPG_SQLSTATE_CONNECTION_DOES_NOT_EXIST "08003" #define ECPG_SQLSTATE_TRANSACTION_RESOLUTION_UNKNOWN "08007" -#define ECPG_SQLSTATE_CARDINALITY_VIOLATION "21000" +#define ECPG_SQLSTATE_CARDINALITY_VIOLATION "21000" #define ECPG_SQLSTATE_NULL_VALUE_NO_INDICATOR_PARAMETER "22002" #define ECPG_SQLSTATE_ACTIVE_SQL_TRANSACTION "25001" #define ECPG_SQLSTATE_NO_ACTIVE_SQL_TRANSACTION "25P01" @@ -124,4 +128,4 @@ bool ECPGstore_result(const PGresult *results, int act_field, #define ECPG_SQLSTATE_ECPG_INTERNAL_ERROR "YE000" #define ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY "YE001" -#endif /* _ECPG_LIB_EXTERN_H */ +#endif /* _ECPG_LIB_EXTERN_H */ diff --git a/src/interfaces/ecpg/ecpglib/misc.c b/src/interfaces/ecpg/ecpglib/misc.c index f42b8f721e..e87643d8df 100644 --- a/src/interfaces/ecpg/ecpglib/misc.c +++ b/src/interfaces/ecpg/ecpglib/misc.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/misc.c,v 1.12 2003/08/01 13:53:36 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/misc.c,v 1.13 2003/08/04 00:43:32 momjian Exp $ */ #define POSTGRES_ECPG_INTERNAL #include "postgres_fe.h" @@ -23,7 +23,7 @@ #define LONG_LONG_MIN LLONG_MIN #endif #endif - + static struct sqlca_t sqlca_init = { { @@ -52,8 +52,9 @@ static struct sqlca_t sqlca_init = }; #ifdef USE_THREADS -static pthread_key_t sqlca_key; -static pthread_once_t sqlca_key_once = PTHREAD_ONCE_INIT; +static pthread_key_t sqlca_key; +static pthread_once_t sqlca_key_once = PTHREAD_ONCE_INIT; + #else static struct sqlca_t sqlca = { @@ -84,22 +85,23 @@ static struct sqlca_t sqlca = #endif #ifdef USE_THREADS -static pthread_mutex_t debug_mutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_mutex_t debug_init_mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_mutex_t debug_mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_mutex_t debug_init_mutex = PTHREAD_MUTEX_INITIALIZER; #endif -static int simple_debug = 0; +static int simple_debug = 0; static FILE *debugstream = NULL; void -ECPGinit_sqlca(struct sqlca_t *sqlca) +ECPGinit_sqlca(struct sqlca_t * sqlca) { - memcpy((char *)sqlca, (char *)&sqlca_init, sizeof(struct sqlca_t)); + memcpy((char *) sqlca, (char *) &sqlca_init, sizeof(struct sqlca_t)); } bool ECPGinit(const struct connection * con, const char *connection_name, const int lineno) { struct sqlca_t *sqlca = ECPGget_sqlca(); + ECPGinit_sqlca(sqlca); if (con == NULL) { @@ -115,7 +117,7 @@ ECPGinit(const struct connection * con, const char *connection_name, const int l static void ecpg_sqlca_key_init(void) { - pthread_key_create(&sqlca_key, NULL); + pthread_key_create(&sqlca_key, NULL); } #endif @@ -123,20 +125,20 @@ struct sqlca_t * ECPGget_sqlca(void) { #ifdef USE_THREADS - struct sqlca_t *sqlca; + struct sqlca_t *sqlca; - pthread_once(&sqlca_key_once, ecpg_sqlca_key_init); + pthread_once(&sqlca_key_once, ecpg_sqlca_key_init); - sqlca = pthread_getspecific(sqlca_key); - if( sqlca == NULL ) - { - sqlca = malloc(sizeof(struct sqlca_t)); - ECPGinit_sqlca(sqlca); - pthread_setspecific(sqlca_key, sqlca); - } - return( sqlca ); + sqlca = pthread_getspecific(sqlca_key); + if (sqlca == NULL) + { + sqlca = malloc(sizeof(struct sqlca_t)); + ECPGinit_sqlca(sqlca); + pthread_setspecific(sqlca_key, sqlca); + } + return (sqlca); #else - return( &sqlca ); + return (&sqlca); #endif } @@ -227,16 +229,17 @@ ECPGlog(const char *format,...) pthread_mutex_lock(&debug_mutex); #endif - if( simple_debug ) + if (simple_debug) { - char *f = (char *)malloc(strlen(format) + 100); - if( f == NULL ) - { + char *f = (char *) malloc(strlen(format) + 100); + + if (f == NULL) + { #ifdef USE_THREADS pthread_mutex_unlock(&debug_mutex); #endif return; - } + } sprintf(f, "[%d]: %s", (int) getpid(), format); @@ -258,7 +261,7 @@ ECPGset_informix_null(enum ECPGttype type, void *ptr) { switch (type) { - case ECPGt_char: + case ECPGt_char: case ECPGt_unsigned_char: *((char *) ptr) = 0x00; break; @@ -307,10 +310,12 @@ ECPGset_informix_null(enum ECPGttype type, void *ptr) } } -static bool _check(unsigned char *ptr, int length) +static bool +_check(unsigned char *ptr, int length) { - for (;ptr[--length] == 0xff && length >= 0; length --); - if (length < 0) return true; + for (; ptr[--length] == 0xff && length >= 0; length--); + if (length < 0) + return true; return false; } @@ -319,49 +324,57 @@ ECPGis_informix_null(enum ECPGttype type, void *ptr) { switch (type) { - case ECPGt_char: + case ECPGt_char: case ECPGt_unsigned_char: - if (*((char *)ptr) == 0x00) return true; + if (*((char *) ptr) == 0x00) + return true; break; case ECPGt_short: case ECPGt_unsigned_short: - if (*((short int *) ptr) == SHRT_MIN) return true; + if (*((short int *) ptr) == SHRT_MIN) + return true; break; case ECPGt_int: case ECPGt_unsigned_int: - if (*((int *) ptr) == INT_MIN) return true; + if (*((int *) ptr) == INT_MIN) + return true; break; case ECPGt_long: case ECPGt_unsigned_long: case ECPGt_date: - if (*((long *) ptr) == LONG_MIN) return true; + if (*((long *) ptr) == LONG_MIN) + return true; break; #ifdef HAVE_LONG_LONG_INT_64 case ECPGt_long_long: case ECPGt_unsigned_long_long: - if (*((long long *) ptr) == LONG_LONG_MIN) return true; + if (*((long long *) ptr) == LONG_LONG_MIN) + return true; break; #endif /* HAVE_LONG_LONG_INT_64 */ case ECPGt_float: - return(_check(ptr, sizeof(float))); + return (_check(ptr, sizeof(float))); break; case ECPGt_double: - return(_check(ptr, sizeof(double))); + return (_check(ptr, sizeof(double))); break; case ECPGt_varchar: - if (*(((struct ECPGgeneric_varchar *) ptr)->arr) == 0x00) return true; + if (*(((struct ECPGgeneric_varchar *) ptr)->arr) == 0x00) + return true; break; case ECPGt_decimal: - if (((Decimal *) ptr)->sign == NUMERIC_NAN) return true; + if (((Decimal *) ptr)->sign == NUMERIC_NAN) + return true; break; case ECPGt_numeric: - if (((Numeric *) ptr)->sign == NUMERIC_NAN) return true; + if (((Numeric *) ptr)->sign == NUMERIC_NAN) + return true; break; case ECPGt_interval: - return(_check(ptr, sizeof(Interval))); + return (_check(ptr, sizeof(Interval))); break; case ECPGt_timestamp: - return(_check(ptr, sizeof(Timestamp))); + return (_check(ptr, sizeof(Timestamp))); break; default: break; diff --git a/src/interfaces/ecpg/ecpglib/prepare.c b/src/interfaces/ecpg/ecpglib/prepare.c index 5569d36da0..55f497e03a 100644 --- a/src/interfaces/ecpg/ecpglib/prepare.c +++ b/src/interfaces/ecpg/ecpglib/prepare.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/prepare.c,v 1.8 2003/08/01 13:53:36 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/ecpglib/prepare.c,v 1.9 2003/08/04 00:43:32 momjian Exp $ */ #define POSTGRES_ECPG_INTERNAL #include "postgres_fe.h" @@ -66,7 +66,7 @@ ECPGprepare(int lineno, char *name, char *variable) for (this = prep_stmts; this != NULL && strcmp(this->name, name) != 0; this = this->next); if (this) { - bool b = ECPGdeallocate(lineno, ECPG_COMPAT_PGSQL, name); + bool b = ECPGdeallocate(lineno, ECPG_COMPAT_PGSQL, name); if (!b) return false; @@ -109,17 +109,19 @@ ECPGprepare(int lineno, char *name, char *variable) bool ECPGdeallocate(int lineno, int c, char *name) { - bool ret = ECPGdeallocate_one(lineno, name); + bool ret = ECPGdeallocate_one(lineno, name); enum COMPAT_MODE compat = c; if (INFORMIX_MODE(compat)) { - /* Just ignore all errors since we do not know the list of cursors we - * are allowed to free. We have to trust that the software. */ - return true; + /* + * Just ignore all errors since we do not know the list of cursors + * we are allowed to free. We have to trust that the software. + */ + return true; } - - if (!ret) + + if (!ret) ECPGraise(lineno, ECPG_INVALID_STMT, ECPG_SQLSTATE_INVALID_SQL_STATEMENT_NAME, name); return ret; @@ -156,7 +158,7 @@ ECPGdeallocate_all(int lineno) /* deallocate all prepared statements */ while (prep_stmts != NULL) { - bool b = ECPGdeallocate(lineno, ECPG_COMPAT_PGSQL, prep_stmts->name); + bool b = ECPGdeallocate(lineno, ECPG_COMPAT_PGSQL, prep_stmts->name); if (!b) return false; diff --git a/src/interfaces/ecpg/include/datetime.h b/src/interfaces/ecpg/include/datetime.h index da16faa485..ed8f31dfc8 100644 --- a/src/interfaces/ecpg/include/datetime.h +++ b/src/interfaces/ecpg/include/datetime.h @@ -3,16 +3,16 @@ #ifndef dtime_t #define dtime_t Timestamp -#endif /* dtime_t */ +#endif /* dtime_t */ #ifndef intrvl_t #define intrvl_t Interval -#endif /* intrvl_t */ +#endif /* intrvl_t */ -extern void dtcurrent (dtime_t *); -extern int dtcvasc (char *, dtime_t *); -extern int dtsub (dtime_t *, dtime_t *, intrvl_t *); -extern int dttoasc (dtime_t *, char *); -extern int dttofmtasc (dtime_t *, char *, int, char *); -extern int intoasc(intrvl_t *, char *); -extern int dtcvfmtasc(char *, char *, dtime_t *); +extern void dtcurrent(dtime_t *); +extern int dtcvasc(char *, dtime_t *); +extern int dtsub(dtime_t *, dtime_t *, intrvl_t *); +extern int dttoasc(dtime_t *, char *); +extern int dttofmtasc(dtime_t *, char *, int, char *); +extern int intoasc(intrvl_t *, char *); +extern int dtcvfmtasc(char *, char *, dtime_t *); diff --git a/src/interfaces/ecpg/include/decimal.h b/src/interfaces/ecpg/include/decimal.h index e0cb06bd5c..c68e253e68 100644 --- a/src/interfaces/ecpg/include/decimal.h +++ b/src/interfaces/ecpg/include/decimal.h @@ -2,20 +2,19 @@ #ifndef dec_t #define dec_t Decimal -#endif /* dec_t */ - -int decadd(dec_t *, dec_t *, dec_t *); -int deccmp(dec_t *, dec_t *); -void deccopy(dec_t *, dec_t *); -int deccvasc(char *, int, dec_t *); -int deccvdbl(double, dec_t *); -int deccvint(int, dec_t *); -int deccvlong(long, dec_t *); -int decdiv(dec_t *, dec_t *, dec_t *); -int decmul(dec_t *, dec_t *, dec_t *); -int decsub(dec_t *, dec_t *, dec_t *); -int dectoasc(dec_t *, char *, int, int); -int dectodbl(dec_t *, double *); -int dectoint(dec_t *, int *); -int dectolong(dec_t *, long *); +#endif /* dec_t */ +int decadd(dec_t *, dec_t *, dec_t *); +int deccmp(dec_t *, dec_t *); +void deccopy(dec_t *, dec_t *); +int deccvasc(char *, int, dec_t *); +int deccvdbl(double, dec_t *); +int deccvint(int, dec_t *); +int deccvlong(long, dec_t *); +int decdiv(dec_t *, dec_t *, dec_t *); +int decmul(dec_t *, dec_t *, dec_t *); +int decsub(dec_t *, dec_t *, dec_t *); +int dectoasc(dec_t *, char *, int, int); +int dectodbl(dec_t *, double *); +int dectoint(dec_t *, int *); +int dectolong(dec_t *, long *); diff --git a/src/interfaces/ecpg/include/ecpg_informix.h b/src/interfaces/ecpg/include/ecpg_informix.h index 59991c70a9..b5c8ed4884 100644 --- a/src/interfaces/ecpg/include/ecpg_informix.h +++ b/src/interfaces/ecpg/include/ecpg_informix.h @@ -1,4 +1,4 @@ -/* +/* * This file contains stuff needed to be as compatible to Informix as possible. */ @@ -10,27 +10,27 @@ #ifndef Date #define Date long -#endif /* ! Date */ +#endif /* ! Date */ -extern int rdatestr (Date, char *); -extern void rtoday (Date *); -extern int rjulmdy (Date, short *); -extern int rdefmtdate (Date *, char *, char *); -extern int rfmtdate (Date, char *, char *); -extern int rmdyjul (short *, Date *); -extern int rstrdate (char *, Date *); -extern int rdayofweek(Date); +extern int rdatestr(Date, char *); +extern void rtoday(Date *); +extern int rjulmdy(Date, short *); +extern int rdefmtdate(Date *, char *, char *); +extern int rfmtdate(Date, char *, char *); +extern int rmdyjul(short *, Date *); +extern int rstrdate(char *, Date *); +extern int rdayofweek(Date); -extern int rfmtlong(long, char *, char *); -extern int rgetmsg(int, char *, int); -extern int risnull(int, char *); -extern int rsetnull(int, char *); -extern int rtypalign(int, int); -extern int rtypmsize(int, int); -extern int rtypwidth(int, int); +extern int rfmtlong(long, char *, char *); +extern int rgetmsg(int, char *, int); +extern int risnull(int, char *); +extern int rsetnull(int, char *); +extern int rtypalign(int, int); +extern int rtypmsize(int, int); +extern int rtypwidth(int, int); extern void rupshift(char *); -extern int byleng(char *, int); +extern int byleng(char *, int); extern void ldchar(char *, int, char *); extern void ECPG_informix_set_var(int, void *, int); diff --git a/src/interfaces/ecpg/include/ecpgerrno.h b/src/interfaces/ecpg/include/ecpgerrno.h index eb1936beb1..7a55155154 100644 --- a/src/interfaces/ecpg/include/ecpgerrno.h +++ b/src/interfaces/ecpg/include/ecpgerrno.h @@ -52,8 +52,8 @@ /* for compatibility we define some different error codes for the same error * if adding a new one make sure to not double define it */ -#define ECPG_INFORMIX_DUPLICATE_KEY -239 -#define ECPG_INFORMIX_SUBSELECT_NOT_ONE -284 +#define ECPG_INFORMIX_DUPLICATE_KEY -239 +#define ECPG_INFORMIX_SUBSELECT_NOT_ONE -284 /* backend WARNINGs, starting at 600 */ #define ECPG_WARNING_UNRECOGNIZED -600 diff --git a/src/interfaces/ecpg/include/ecpglib.h b/src/interfaces/ecpg/include/ecpglib.h index 3f510fbfa6..fc429c9643 100644 --- a/src/interfaces/ecpg/include/ecpglib.h +++ b/src/interfaces/ecpg/include/ecpglib.h @@ -41,7 +41,7 @@ extern "C" struct sqlca_t; -void ECPGinit_sqlca(struct sqlca_t *sqlca); +void ECPGinit_sqlca(struct sqlca_t * sqlca); void ECPGdebug(int, FILE *); bool ECPGstatus(int, const char *); bool ECPGsetcommit(int, const char *, const char *); @@ -57,7 +57,7 @@ bool ECPGdeallocate_all(int); char *ECPGprepared_statement(char *); void ECPGlog(const char *format,...); -char *ECPGerrmsg(void); +char *ECPGerrmsg(void); /* print an error message */ void sqlprint(void); @@ -79,14 +79,13 @@ bool ECPGget_desc(int, char *, int,...); void ECPGset_informix_null(enum ECPGttype, void *); bool ECPGis_informix_null(enum ECPGttype, void *); -bool ECPGdescribe(int, bool, const char *, ...); +bool ECPGdescribe(int, bool, const char *,...); /* dynamic result allocation */ void ECPGfree_auto_mem(void); #ifdef __cplusplus } - #endif -#endif /* _ECPGLIB_H */ +#endif /* _ECPGLIB_H */ diff --git a/src/interfaces/ecpg/include/ecpgtype.h b/src/interfaces/ecpg/include/ecpgtype.h index 7a299d0be8..3d544029b7 100644 --- a/src/interfaces/ecpg/include/ecpgtype.h +++ b/src/interfaces/ecpg/include/ecpgtype.h @@ -44,20 +44,22 @@ enum ECPGttype ECPGt_bool, ECPGt_float, ECPGt_double, ECPGt_varchar, ECPGt_varchar2, - ECPGt_numeric, /* this is a decimal that stores its digits in a malloced array */ - ECPGt_decimal, /* this is a decimal that stores its digits in a fixed array */ + ECPGt_numeric, /* this is a decimal that stores its + * digits in a malloced array */ + ECPGt_decimal, /* this is a decimal that stores its + * digits in a fixed array */ ECPGt_date, ECPGt_timestamp, ECPGt_interval, ECPGt_array, ECPGt_struct, ECPGt_union, - ECPGt_descriptor, /* sql descriptor, no C variable */ + ECPGt_descriptor, /* sql descriptor, no C variable */ ECPGt_char_variable, - ECPGt_const, /* a constant is needed sometimes */ - ECPGt_EOIT, /* End of insert types. */ - ECPGt_EORT, /* End of result types. */ - ECPGt_NO_INDICATOR /* no indicator */ + ECPGt_const, /* a constant is needed sometimes */ + ECPGt_EOIT, /* End of insert types. */ + ECPGt_EORT, /* End of result types. */ + ECPGt_NO_INDICATOR /* no indicator */ }; /* descriptor items */ @@ -88,4 +90,4 @@ enum ECPGdtype } #endif -#endif /* _ECPGTYPE_H */ +#endif /* _ECPGTYPE_H */ diff --git a/src/interfaces/ecpg/include/pgtypes_date.h b/src/interfaces/ecpg/include/pgtypes_date.h index 190a9de703..391eeedce8 100644 --- a/src/interfaces/ecpg/include/pgtypes_date.h +++ b/src/interfaces/ecpg/include/pgtypes_date.h @@ -8,10 +8,11 @@ extern Date PGTYPESdate_from_asc(char *, char **); extern char *PGTYPESdate_to_asc(Date); extern Date PGTYPESdate_from_timestamp(Timestamp); -extern void PGTYPESdate_julmdy(Date, int*); -extern void PGTYPESdate_mdyjul(int*, Date *); -extern int PGTYPESdate_dayofweek(Date); -extern void PGTYPESdate_today (Date *); -extern int PGTYPESdate_defmt_asc(Date *, char *, char *); -extern int PGTYPESdate_fmt_asc(Date, char *, char *); -#endif /* PGTYPES_DATETIME */ +extern void PGTYPESdate_julmdy(Date, int *); +extern void PGTYPESdate_mdyjul(int *, Date *); +extern int PGTYPESdate_dayofweek(Date); +extern void PGTYPESdate_today(Date *); +extern int PGTYPESdate_defmt_asc(Date *, char *, char *); +extern int PGTYPESdate_fmt_asc(Date, char *, char *); + +#endif /* PGTYPES_DATETIME */ diff --git a/src/interfaces/ecpg/include/pgtypes_error.h b/src/interfaces/ecpg/include/pgtypes_error.h index e5a102ca98..4a1008adc3 100644 --- a/src/interfaces/ecpg/include/pgtypes_error.h +++ b/src/interfaces/ecpg/include/pgtypes_error.h @@ -1,4 +1,4 @@ -#define PGTYPES_NUM_OVERFLOW 301 +#define PGTYPES_NUM_OVERFLOW 301 #define PGTYPES_NUM_BAD_NUMERIC 302 #define PGTYPES_NUM_DIVIDE_ZERO 303 @@ -10,7 +10,6 @@ #define PGTYPES_DATE_BAD_MONTH 315 #define PGTYPES_TS_BAD_TIMESTAMP 320 -#define PGTYPES_TS_ERR_EINFTIME 321 +#define PGTYPES_TS_ERR_EINFTIME 321 #define PGTYPES_INTVL_BAD_INTERVAL 330 - diff --git a/src/interfaces/ecpg/include/pgtypes_interval.h b/src/interfaces/ecpg/include/pgtypes_interval.h index 884df67216..4e1fa6e10b 100644 --- a/src/interfaces/ecpg/include/pgtypes_interval.h +++ b/src/interfaces/ecpg/include/pgtypes_interval.h @@ -4,15 +4,18 @@ typedef struct { #ifdef HAVE_INT64_TIMESTAMP - int64 time; /* all time units other than months and years */ + int64 time; /* all time units other than months and + * years */ #else - double time; /* all time units other than months and years */ + double time; /* all time units other than months and + * years */ #endif - long month; /* months and years, after time for alignment */ + long month; /* months and years, after time for + * alignment */ } Interval; extern Interval *PGTYPESinterval_from_asc(char *, char **); extern char *PGTYPESinterval_to_asc(Interval *); -extern int PGTYPESinterval_copy(Interval *, Interval *); - -#endif /* PGTYPES_INTERVAL */ +extern int PGTYPESinterval_copy(Interval *, Interval *); + +#endif /* PGTYPES_INTERVAL */ diff --git a/src/interfaces/ecpg/include/pgtypes_numeric.h b/src/interfaces/ecpg/include/pgtypes_numeric.h index 28b902f290..55d2924e59 100644 --- a/src/interfaces/ecpg/include/pgtypes_numeric.h +++ b/src/interfaces/ecpg/include/pgtypes_numeric.h @@ -1,55 +1,59 @@ #ifndef PGTYPES_NUMERIC #define PGTYPES_NUMERIC -#define NUMERIC_POS 0x0000 -#define NUMERIC_NEG 0x4000 -#define NUMERIC_NAN 0xC000 -#define NUMERIC_MAX_PRECISION 1000 -#define NUMERIC_MAX_DISPLAY_SCALE NUMERIC_MAX_PRECISION -#define NUMERIC_MIN_DISPLAY_SCALE 0 -#define NUMERIC_MIN_SIG_DIGITS 16 +#define NUMERIC_POS 0x0000 +#define NUMERIC_NEG 0x4000 +#define NUMERIC_NAN 0xC000 +#define NUMERIC_MAX_PRECISION 1000 +#define NUMERIC_MAX_DISPLAY_SCALE NUMERIC_MAX_PRECISION +#define NUMERIC_MIN_DISPLAY_SCALE 0 +#define NUMERIC_MIN_SIG_DIGITS 16 #define DECSIZE 30 typedef unsigned char NumericDigit; -typedef struct +typedef struct { - int ndigits; /* number of digits in digits[] - can be 0! */ - int weight; /* weight of first digit */ - int rscale; /* result scale */ - int dscale; /* display scale */ - int sign; /* NUMERIC_POS, NUMERIC_NEG, or NUMERIC_NAN */ - NumericDigit *buf; /* start of alloc'd space for digits[] */ - NumericDigit *digits; /* decimal digits */ + int ndigits; /* number of digits in digits[] - can be + * 0! */ + int weight; /* weight of first digit */ + int rscale; /* result scale */ + int dscale; /* display scale */ + int sign; /* NUMERIC_POS, NUMERIC_NEG, or + * NUMERIC_NAN */ + NumericDigit *buf; /* start of alloc'd space for digits[] */ + NumericDigit *digits; /* decimal digits */ } Numeric; -typedef struct +typedef struct { - int ndigits; /* number of digits in digits[] - can be 0! */ - int weight; /* weight of first digit */ - int rscale; /* result scale */ - int dscale; /* display scale */ - int sign; /* NUMERIC_POS, NUMERIC_NEG, or NUMERIC_NAN */ - NumericDigit digits[DECSIZE]; /* decimal digits */ -} Decimal; + int ndigits; /* number of digits in digits[] - can be + * 0! */ + int weight; /* weight of first digit */ + int rscale; /* result scale */ + int dscale; /* display scale */ + int sign; /* NUMERIC_POS, NUMERIC_NEG, or + * NUMERIC_NAN */ + NumericDigit digits[DECSIZE]; /* decimal digits */ +} Decimal; -Numeric *PGTYPESnumeric_new(void); -void PGTYPESnumeric_free(Numeric *); -Numeric *PGTYPESnumeric_from_asc(char *, char **); -char *PGTYPESnumeric_to_asc(Numeric *, int); -int PGTYPESnumeric_add(Numeric *, Numeric *, Numeric *); -int PGTYPESnumeric_sub(Numeric *, Numeric *, Numeric *); -int PGTYPESnumeric_mul(Numeric *, Numeric *, Numeric *); -int PGTYPESnumeric_div(Numeric *, Numeric *, Numeric *); -int PGTYPESnumeric_cmp(Numeric *, Numeric *); -int PGTYPESnumeric_from_int(signed int, Numeric *); -int PGTYPESnumeric_from_long(signed long int, Numeric *); -int PGTYPESnumeric_copy(Numeric *, Numeric *); -int PGTYPESnumeric_from_double(double, Numeric *); -int PGTYPESnumeric_to_double(Numeric *, double *); -int PGTYPESnumeric_to_int(Numeric *, int *); -int PGTYPESnumeric_to_long(Numeric *, long *); -int PGTYPESnumeric_to_decimal(Numeric *, Decimal *); -int PGTYPESnumeric_from_decimal(Decimal *, Numeric *); +Numeric *PGTYPESnumeric_new(void); +void PGTYPESnumeric_free(Numeric *); +Numeric *PGTYPESnumeric_from_asc(char *, char **); +char *PGTYPESnumeric_to_asc(Numeric *, int); +int PGTYPESnumeric_add(Numeric *, Numeric *, Numeric *); +int PGTYPESnumeric_sub(Numeric *, Numeric *, Numeric *); +int PGTYPESnumeric_mul(Numeric *, Numeric *, Numeric *); +int PGTYPESnumeric_div(Numeric *, Numeric *, Numeric *); +int PGTYPESnumeric_cmp(Numeric *, Numeric *); +int PGTYPESnumeric_from_int(signed int, Numeric *); +int PGTYPESnumeric_from_long(signed long int, Numeric *); +int PGTYPESnumeric_copy(Numeric *, Numeric *); +int PGTYPESnumeric_from_double(double, Numeric *); +int PGTYPESnumeric_to_double(Numeric *, double *); +int PGTYPESnumeric_to_int(Numeric *, int *); +int PGTYPESnumeric_to_long(Numeric *, long *); +int PGTYPESnumeric_to_decimal(Numeric *, Decimal *); +int PGTYPESnumeric_from_decimal(Decimal *, Numeric *); -#endif /* PGTYPES_NUMERIC */ +#endif /* PGTYPES_NUMERIC */ diff --git a/src/interfaces/ecpg/include/pgtypes_timestamp.h b/src/interfaces/ecpg/include/pgtypes_timestamp.h index 9294e1d77a..f1aabcbea2 100644 --- a/src/interfaces/ecpg/include/pgtypes_timestamp.h +++ b/src/interfaces/ecpg/include/pgtypes_timestamp.h @@ -14,9 +14,9 @@ typedef double TimestampTz; extern Timestamp PGTYPEStimestamp_from_asc(char *, char **); extern char *PGTYPEStimestamp_to_asc(Timestamp); -extern int PGTYPEStimestamp_sub (Timestamp *, Timestamp *, Interval *); -extern int PGTYPEStimestamp_fmt_asc (Timestamp *, char *, int, char *); -extern void PGTYPEStimestamp_current (Timestamp *); -extern int PGTYPEStimestamp_defmt_asc(char *, char *, Timestamp *); +extern int PGTYPEStimestamp_sub(Timestamp *, Timestamp *, Interval *); +extern int PGTYPEStimestamp_fmt_asc(Timestamp *, char *, int, char *); +extern void PGTYPEStimestamp_current(Timestamp *); +extern int PGTYPEStimestamp_defmt_asc(char *, char *, Timestamp *); -#endif /* PGTYPES_TIMESTAMP */ +#endif /* PGTYPES_TIMESTAMP */ diff --git a/src/interfaces/ecpg/include/sqlca.h b/src/interfaces/ecpg/include/sqlca.h index 37370b6f60..8d58d3dfd3 100644 --- a/src/interfaces/ecpg/include/sqlca.h +++ b/src/interfaces/ecpg/include/sqlca.h @@ -56,7 +56,7 @@ struct sqlca_t struct sqlca_t *ECPGget_sqlca(void); #ifndef POSTGRES_ECPG_INTERNAL -# define sqlca (*ECPGget_sqlca()) +#define sqlca (*ECPGget_sqlca()) #endif #ifdef __cplusplus diff --git a/src/interfaces/ecpg/include/sqlda.h b/src/interfaces/ecpg/include/sqlda.h index e69de29bb2..8b13789179 100644 --- a/src/interfaces/ecpg/include/sqlda.h +++ b/src/interfaces/ecpg/include/sqlda.h @@ -0,0 +1 @@ + diff --git a/src/interfaces/ecpg/include/sqltypes.h b/src/interfaces/ecpg/include/sqltypes.h index c50bf54314..1ebde04714 100644 --- a/src/interfaces/ecpg/include/sqltypes.h +++ b/src/interfaces/ecpg/include/sqltypes.h @@ -3,23 +3,23 @@ #define CINTTYPE ECPGt_int #define CLONGTYPE ECPGt_long #define CFLOATTYPE ECPGt_float -#define CDOUBLETYPE ECPGt_double +#define CDOUBLETYPE ECPGt_double #define CDECIMALTYPE ECPGt_decimal #define CFIXCHARTYPE 108 -#define CSTRINGTYPE ECPGt_char +#define CSTRINGTYPE ECPGt_char #define CDATETYPE ECPGt_date #define CMONEYTYPE 111 #define CDTIMETYPE 112 -#define CLOCATORTYPE 113 -#define CVCHARTYPE ECPGt_varchar +#define CLOCATORTYPE 113 +#define CVCHARTYPE ECPGt_varchar #define CINVTYPE 115 #define CFILETYPE 116 #define CINT8TYPE ECPGt_long_long -#define CCOLLTYPE 118 -#define CLVCHARTYPE 119 -#define CFIXBINTYPE 120 -#define CVARBINTYPE 121 -#define CBOOLTYPE ECPGt_bool -#define CROWTYPE 123 -#define CLVCHARPTRTYPE 124 +#define CCOLLTYPE 118 +#define CLVCHARTYPE 119 +#define CFIXBINTYPE 120 +#define CVARBINTYPE 121 +#define CBOOLTYPE ECPGt_bool +#define CROWTYPE 123 +#define CLVCHARPTRTYPE 124 #define CTYPEMAX 25 diff --git a/src/interfaces/ecpg/pgtypeslib/common.c b/src/interfaces/ecpg/pgtypeslib/common.c index f9762c8ae3..986d8fc3f0 100644 --- a/src/interfaces/ecpg/pgtypeslib/common.c +++ b/src/interfaces/ecpg/pgtypeslib/common.c @@ -5,7 +5,7 @@ char * pgtypes_alloc(long size) { - char *new = (char *) calloc(1L, size); + char *new = (char *) calloc(1L, size); if (!new) { @@ -20,7 +20,7 @@ pgtypes_alloc(long size) char * pgtypes_strdup(char *str) { - char *new = (char *) strdup(str); + char *new = (char *) strdup(str); if (!new) errno = ENOMEM; @@ -28,40 +28,47 @@ pgtypes_strdup(char *str) } int -pgtypes_fmt_replace(union un_fmt_comb replace_val, int replace_type, char** output, int *pstr_len) { - /* general purpose variable, set to 0 in order to fix compiler - * warning */ - int i = 0; - switch(replace_type) { +pgtypes_fmt_replace(union un_fmt_comb replace_val, int replace_type, char **output, int *pstr_len) +{ + /* + * general purpose variable, set to 0 in order to fix compiler warning + */ + int i = 0; + + switch (replace_type) + { case PGTYPES_TYPE_NOTHING: break; case PGTYPES_TYPE_STRING_CONSTANT: case PGTYPES_TYPE_STRING_MALLOCED: i = strlen(replace_val.str_val); - if (i + 1 <= *pstr_len) { - /* copy over i + 1 bytes, that includes the - * tailing terminator */ + if (i + 1 <= *pstr_len) + { + /* + * copy over i + 1 bytes, that includes the tailing + * terminator + */ strncpy(*output, replace_val.str_val, i + 1); *pstr_len -= i; *output += i; - if (replace_type == PGTYPES_TYPE_STRING_MALLOCED) { + if (replace_type == PGTYPES_TYPE_STRING_MALLOCED) free(replace_val.str_val); - } return 0; - } else { - return -1; } + else + return -1; break; case PGTYPES_TYPE_CHAR: - if (*pstr_len >= 2) { + if (*pstr_len >= 2) + { (*output)[0] = replace_val.char_val; (*output)[1] = '\0'; (*pstr_len)--; (*output)++; return 0; - } else { - return -1; } + else + return -1; break; case PGTYPES_TYPE_DOUBLE_NF: case PGTYPES_TYPE_INT64: @@ -71,53 +78,58 @@ pgtypes_fmt_replace(union un_fmt_comb replace_val, int replace_type, char** outp case PGTYPES_TYPE_UINT_3_LZ: case PGTYPES_TYPE_UINT_4_LZ: { - char* t = pgtypes_alloc(PGTYPES_FMT_NUM_MAX_DIGITS); - if (!t) { + char *t = pgtypes_alloc(PGTYPES_FMT_NUM_MAX_DIGITS); + + if (!t) return ENOMEM; - } - switch (replace_type) { + switch (replace_type) + { case PGTYPES_TYPE_DOUBLE_NF: i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, - "%0.0g", replace_val.double_val); + "%0.0g", replace_val.double_val); break; #ifdef HAVE_INT64 case PGTYPES_TYPE_INT64: i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, - INT64_FORMAT, replace_val.int64_val); + INT64_FORMAT, replace_val.int64_val); break; #endif case PGTYPES_TYPE_UINT: - i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, - "%u", replace_val.uint_val); + i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, + "%u", replace_val.uint_val); break; case PGTYPES_TYPE_UINT_2_LZ: - i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, - "%02u", replace_val.uint_val); + i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, + "%02u", replace_val.uint_val); break; case PGTYPES_TYPE_UINT_2_LS: - i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, - "%2u", replace_val.uint_val); + i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, + "%2u", replace_val.uint_val); break; case PGTYPES_TYPE_UINT_3_LZ: - i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, - "%03u", replace_val.uint_val); + i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, + "%03u", replace_val.uint_val); break; case PGTYPES_TYPE_UINT_4_LZ: - i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, - "%04u", replace_val.uint_val); + i = snprintf(t, PGTYPES_FMT_NUM_MAX_DIGITS, + "%04u", replace_val.uint_val); break; } - if (i < 0) { + if (i < 0) + { free(t); return -1; } i = strlen(t); *pstr_len -= i; - /* if *pstr_len == 0, we don't have enough - * space for the terminator and the - * conversion fails */ - if (*pstr_len <= 0) { + + /* + * if *pstr_len == 0, we don't have enough space for the + * terminator and the conversion fails + */ + if (*pstr_len <= 0) + { free(t); return -1; } @@ -131,5 +143,3 @@ pgtypes_fmt_replace(union un_fmt_comb replace_val, int replace_type, char** outp } return 0; } - - diff --git a/src/interfaces/ecpg/pgtypeslib/datetime.c b/src/interfaces/ecpg/pgtypeslib/datetime.c index 789f8400fa..34ed888b66 100644 --- a/src/interfaces/ecpg/pgtypeslib/datetime.c +++ b/src/interfaces/ecpg/pgtypeslib/datetime.c @@ -14,17 +14,17 @@ PGTYPESdate_from_timestamp(Timestamp dt) { Date dDate; - dDate = 0; /* suppress compiler warning */ + dDate = 0; /* suppress compiler warning */ if (TIMESTAMP_NOT_FINITE(dt)) - return + return #ifdef HAVE_INT64_TIMESTAMP - /* Microseconds to days */ - dDate = (dt / INT64CONST(86400000000)); + /* Microseconds to days */ + dDate = (dt / INT64CONST(86400000000)); #else - /* Seconds to days */ - dDate = (dt / 86400.0); + /* Seconds to days */ + dDate = (dt / 86400.0); #endif return dDate; @@ -33,7 +33,7 @@ PGTYPESdate_from_timestamp(Timestamp dt) Date PGTYPESdate_from_asc(char *str, char **endptr) { - + Date dDate; fsec_t fsec; struct tm tt, @@ -44,9 +44,9 @@ PGTYPESdate_from_asc(char *str, char **endptr) char *field[MAXDATEFIELDS]; int ftype[MAXDATEFIELDS]; char lowstr[MAXDATELEN + 1]; - char *realptr; - char **ptr = (endptr != NULL) ? endptr : &realptr; - + char *realptr; + char **ptr = (endptr != NULL) ? endptr : &realptr; + bool EuroDates = FALSE; errno = 0; @@ -57,7 +57,7 @@ PGTYPESdate_from_asc(char *str, char **endptr) } if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf, ptr) != 0) - || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tzp, EuroDates) != 0)) + || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tzp, EuroDates) != 0)) { errno = PGTYPES_DATE_BAD_DATE; return 0; @@ -69,7 +69,7 @@ PGTYPESdate_from_asc(char *str, char **endptr) break; case DTK_EPOCH: - GetEpochTime(tm); + GetEpochTime(tm); break; default: @@ -85,21 +85,24 @@ PGTYPESdate_from_asc(char *str, char **endptr) char * PGTYPESdate_to_asc(Date dDate) { - struct tm tt, *tm = &tt; - char buf[MAXDATELEN + 1]; - int DateStyle=1; + struct tm tt, + *tm = &tt; + char buf[MAXDATELEN + 1]; + int DateStyle = 1; bool EuroDates = FALSE; - + j2date((dDate + date2j(2000, 1, 1)), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday)); EncodeDateOnly(tm, DateStyle, buf, EuroDates); return pgtypes_strdup(buf); } void -PGTYPESdate_julmdy(Date jd, int* mdy) +PGTYPESdate_julmdy(Date jd, int *mdy) { - int y, m, d; - + int y, + m, + d; + j2date((int) (jd + date2j(2000, 1, 1)), &y, &m, &d); mdy[0] = m; mdy[1] = d; @@ -107,10 +110,10 @@ PGTYPESdate_julmdy(Date jd, int* mdy) } void -PGTYPESdate_mdyjul(int* mdy, Date *jdate) +PGTYPESdate_mdyjul(int *mdy, Date * jdate) { /* month is mdy[0] */ - /* day is mdy[1] */ + /* day is mdy[1] */ /* year is mdy[2] */ *jdate = (Date) (date2j(mdy[2], mdy[0], mdy[1]) - date2j(2000, 1, 1)); @@ -120,19 +123,14 @@ int PGTYPESdate_dayofweek(Date dDate) { /* - Sunday: 0 - Monday: 1 - Tuesday: 2 - Wednesday: 3 - Thursday: 4 - Friday: 5 - Saturday: 6 - */ - return 6-j2day(dDate+3); + * Sunday: 0 Monday: 1 Tuesday: 2 Wednesday: 3 + * Thursday: 4 Friday: 5 Saturday: 6 + */ + return 6 - j2day(dDate + 3); } void -PGTYPESdate_today (Date *d) +PGTYPESdate_today(Date * d) { struct tm ts; @@ -141,40 +139,60 @@ PGTYPESdate_today (Date *d) return; } -#define PGTYPES_DATE_NUM_MAX_DIGITS 20 /* should suffice for most years... */ +#define PGTYPES_DATE_NUM_MAX_DIGITS 20 /* should suffice for most + * years... */ -#define PGTYPES_FMTDATE_DAY_DIGITS_LZ 1 /* LZ means "leading zeroes" */ +#define PGTYPES_FMTDATE_DAY_DIGITS_LZ 1 /* LZ means "leading + * zeroes" */ #define PGTYPES_FMTDATE_DOW_LITERAL_SHORT 2 #define PGTYPES_FMTDATE_MONTH_DIGITS_LZ 3 -#define PGTYPES_FMTDATE_MONTH_LITERAL_SHORT 4 +#define PGTYPES_FMTDATE_MONTH_LITERAL_SHORT 4 #define PGTYPES_FMTDATE_YEAR_DIGITS_SHORT 5 #define PGTYPES_FMTDATE_YEAR_DIGITS_LONG 6 int -PGTYPESdate_fmt_asc(Date dDate, char* fmtstring, char* outbuf) { - static struct { - char* format; - int component; - } mapping[] = { - /* format items have to be sorted according to their length, - * since the first pattern that matches gets replaced by its - * value */ - {"ddd", PGTYPES_FMTDATE_DOW_LITERAL_SHORT }, - {"dd", PGTYPES_FMTDATE_DAY_DIGITS_LZ }, - {"mmm", PGTYPES_FMTDATE_MONTH_LITERAL_SHORT }, - {"mm", PGTYPES_FMTDATE_MONTH_DIGITS_LZ }, - {"yyyy", PGTYPES_FMTDATE_YEAR_DIGITS_LONG }, - {"yy", PGTYPES_FMTDATE_YEAR_DIGITS_SHORT }, - { NULL, 0 } +PGTYPESdate_fmt_asc(Date dDate, char *fmtstring, char *outbuf) +{ + static struct + { + char *format; + int component; + } mapping[] = + { + /* + * format items have to be sorted according to their length, since + * the first pattern that matches gets replaced by its value + */ + { + "ddd", PGTYPES_FMTDATE_DOW_LITERAL_SHORT + }, + { + "dd", PGTYPES_FMTDATE_DAY_DIGITS_LZ + }, + { + "mmm", PGTYPES_FMTDATE_MONTH_LITERAL_SHORT + }, + { + "mm", PGTYPES_FMTDATE_MONTH_DIGITS_LZ + }, + { + "yyyy", PGTYPES_FMTDATE_YEAR_DIGITS_LONG + }, + { + "yy", PGTYPES_FMTDATE_YEAR_DIGITS_SHORT + }, + { + NULL, 0 + } }; union un_fmt_comb replace_val; - int replace_type; + int replace_type; - int i; - int dow; - char* start_pattern; - struct tm tm; + int i; + int dow; + char *start_pattern; + struct tm tm; /* XXX error handling ? */ /* copy the string over */ @@ -184,9 +202,12 @@ PGTYPESdate_fmt_asc(Date dDate, char* fmtstring, char* outbuf) { j2date((dDate + date2j(2000, 1, 1)), &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday)); dow = PGTYPESdate_dayofweek(dDate); - for (i = 0; mapping[i].format != NULL; i++) { - while ((start_pattern = strstr(outbuf, mapping[i].format)) != NULL) { - switch(mapping[i].component) { + for (i = 0; mapping[i].format != NULL; i++) + { + while ((start_pattern = strstr(outbuf, mapping[i].format)) != NULL) + { + switch (mapping[i].component) + { case PGTYPES_FMTDATE_DOW_LITERAL_SHORT: replace_val.str_val = pgtypes_date_weekdays_short[dow]; replace_type = PGTYPES_TYPE_STRING_CONSTANT; @@ -196,7 +217,7 @@ PGTYPESdate_fmt_asc(Date dDate, char* fmtstring, char* outbuf) { replace_type = PGTYPES_TYPE_UINT_2_LZ; break; case PGTYPES_FMTDATE_MONTH_LITERAL_SHORT: - replace_val.str_val = months[tm.tm_mon-1]; + replace_val.str_val = months[tm.tm_mon - 1]; replace_type = PGTYPES_TYPE_STRING_CONSTANT; break; case PGTYPES_FMTDATE_MONTH_DIGITS_LZ: @@ -212,61 +233,65 @@ PGTYPESdate_fmt_asc(Date dDate, char* fmtstring, char* outbuf) { replace_type = PGTYPES_TYPE_UINT_2_LZ; break; default: - /* should not happen, set something - * anyway */ + + /* + * should not happen, set something anyway + */ replace_val.str_val = " "; replace_type = PGTYPES_TYPE_STRING_CONSTANT; } - switch(replace_type) { + switch (replace_type) + { case PGTYPES_TYPE_STRING_MALLOCED: case PGTYPES_TYPE_STRING_CONSTANT: strncpy(start_pattern, replace_val.str_val, strlen(replace_val.str_val)); - if (replace_type == PGTYPES_TYPE_STRING_MALLOCED) { + if (replace_type == PGTYPES_TYPE_STRING_MALLOCED) free(replace_val.str_val); - } break; case PGTYPES_TYPE_UINT: { - char* t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); - if (!t) { + char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); + + if (!t) return -1; - } snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS, - "%u", replace_val.uint_val); + "%u", replace_val.uint_val); strncpy(start_pattern, t, strlen(t)); free(t); } break; case PGTYPES_TYPE_UINT_2_LZ: { - char* t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); - if (!t) { + char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); + + if (!t) return -1; - } snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS, - "%02u", replace_val.uint_val); + "%02u", replace_val.uint_val); strncpy(start_pattern, t, strlen(t)); free(t); } break; case PGTYPES_TYPE_UINT_4_LZ: { - char* t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); - if (!t) { + char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); + + if (!t) return -1; - } snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS, - "%04u", replace_val.uint_val); + "%04u", replace_val.uint_val); strncpy(start_pattern, t, strlen(t)); free(t); } break; default: - /* doesn't happen (we set - * replace_type to - * PGTYPES_TYPE_STRING_CONSTANT - * in case of an error above) */ + + /* + * doesn't happen (we set replace_type to + * PGTYPES_TYPE_STRING_CONSTANT in case of an error + * above) + */ break; } } @@ -279,32 +304,37 @@ PGTYPESdate_fmt_asc(Date dDate, char* fmtstring, char* outbuf) { * PGTYPESdate_defmt_asc * * function works as follows: - * - first we analyze the paramters - * - if this is a special case with no delimiters, add delimters - * - find the tokens. First we look for numerical values. If we have found - * less than 3 tokens, we check for the months' names and thereafter for - * the abbreviations of the months' names. - * - then we see which parameter should be the date, the month and the - * year and from these values we calculate the date + * - first we analyze the paramters + * - if this is a special case with no delimiters, add delimters + * - find the tokens. First we look for numerical values. If we have found + * less than 3 tokens, we check for the months' names and thereafter for + * the abbreviations of the months' names. + * - then we see which parameter should be the date, the month and the + * year and from these values we calculate the date */ -#define PGTYPES_DATE_MONTH_MAXLENGTH 20 /* probably even less :-) */ +#define PGTYPES_DATE_MONTH_MAXLENGTH 20 /* probably even less :-) */ int -PGTYPESdate_defmt_asc(Date *d, char *fmt, char *str) +PGTYPESdate_defmt_asc(Date * d, char *fmt, char *str) { - /* token[2] = { 4,6 } means that token 2 starts at - * position 4 and ends at (including) position 6 */ - int token[3][2]; - int token_values[3] = { -1, -1, -1 }; - char* fmt_token_order; - char* fmt_ystart, *fmt_mstart, *fmt_dstart; - int i; - int reading_digit; - int token_count; - char* str_copy; - struct tm tm; + /* + * token[2] = { 4,6 } means that token 2 starts at position 4 and ends + * at (including) position 6 + */ + int token[3][2]; + int token_values[3] = {-1, -1, -1}; + char *fmt_token_order; + char *fmt_ystart, + *fmt_mstart, + *fmt_dstart; + int i; + int reading_digit; + int token_count; + char *str_copy; + struct tm tm; - if (!d || !str || !fmt) { + if (!d || !str || !fmt) + { errno = PGTYPES_DATE_ERR_EARGS; return -1; } @@ -314,229 +344,305 @@ PGTYPESdate_defmt_asc(Date *d, char *fmt, char *str) fmt_mstart = strstr(fmt, "mm"); fmt_dstart = strstr(fmt, "dd"); - if (!fmt_ystart || !fmt_mstart || !fmt_dstart) { + if (!fmt_ystart || !fmt_mstart || !fmt_dstart) + { errno = PGTYPES_DATE_ERR_EARGS; return -1; } - if (fmt_ystart < fmt_mstart) { + if (fmt_ystart < fmt_mstart) + { /* y m */ - if (fmt_dstart < fmt_ystart) { + if (fmt_dstart < fmt_ystart) + { /* d y m */ fmt_token_order = "dym"; - } else if (fmt_dstart > fmt_mstart) { + } + else if (fmt_dstart > fmt_mstart) + { /* y m d */ fmt_token_order = "ymd"; - } else { + } + else + { /* y d m */ fmt_token_order = "ydm"; } - } else { + } + else + { /* fmt_ystart > fmt_mstart */ /* m y */ - if (fmt_dstart < fmt_mstart) { + if (fmt_dstart < fmt_mstart) + { /* d m y */ fmt_token_order = "dmy"; - } else if (fmt_dstart > fmt_ystart) { + } + else if (fmt_dstart > fmt_ystart) + { /* m y d */ fmt_token_order = "myd"; - } else { + } + else + { /* m d y */ fmt_token_order = "mdy"; } } - /* handle the special cases where there is no delimiter between the + /* + * handle the special cases where there is no delimiter between the * digits. If we see this: * - * only digits, 6 or 8 bytes then it might be ddmmyy and ddmmyyyy - * (or similar) + * only digits, 6 or 8 bytes then it might be ddmmyy and ddmmyyyy (or + * similar) * * we reduce it to a string with delimiters and continue processing - * */ + */ /* check if we have only digits */ reading_digit = 1; - for (i = 0; str[i]; i++) { - if (!isdigit(str[i])) { + for (i = 0; str[i]; i++) + { + if (!isdigit(str[i])) + { reading_digit = 0; break; } } - if (reading_digit) { - int frag_length[3]; - int target_pos; + if (reading_digit) + { + int frag_length[3]; + int target_pos; i = strlen(str); - if (i != 8 && i != 6) { + if (i != 8 && i != 6) + { errno = PGTYPES_DATE_ERR_ENOSHORTDATE; return -1; } /* okay, this really is the special case */ - /* as long as the string, one additional byte for the - * terminator and 2 for the delimiters between the 3 fiedls - * */ + /* + * as long as the string, one additional byte for the terminator + * and 2 for the delimiters between the 3 fiedls + */ str_copy = pgtypes_alloc(strlen(str) + 1 + 2); - if (!str_copy) { + if (!str_copy) return -1; - } /* determine length of the fragments */ - if (i == 6) { - frag_length[0] = 2; frag_length[1] = 2; frag_length[2] = 2; - } else { - if (fmt_token_order[0] == 'y') { - frag_length[0] = 4; frag_length[1] = 2; frag_length[2] = 2; - } else if (fmt_token_order[1] == 'y') { - frag_length[0] = 2; frag_length[1] = 4; frag_length[2] = 2; - } else { - frag_length[0] = 2; frag_length[1] = 2; frag_length[2] = 4; + if (i == 6) + { + frag_length[0] = 2; + frag_length[1] = 2; + frag_length[2] = 2; + } + else + { + if (fmt_token_order[0] == 'y') + { + frag_length[0] = 4; + frag_length[1] = 2; + frag_length[2] = 2; + } + else if (fmt_token_order[1] == 'y') + { + frag_length[0] = 2; + frag_length[1] = 4; + frag_length[2] = 2; + } + else + { + frag_length[0] = 2; + frag_length[1] = 2; + frag_length[2] = 4; } } target_pos = 0; - /* XXX: Here we could calculate the positions of the tokens - * and save the for loop down there where we again check - * with isdigit() for digits. */ - for (i = 0; i < 3; i++) { - int start_pos = 0; - if (i >= 1) { start_pos += frag_length[0]; } - if (i == 2) { start_pos += frag_length[1]; } + + /* + * XXX: Here we could calculate the positions of the tokens and + * save the for loop down there where we again check with + * isdigit() for digits. + */ + for (i = 0; i < 3; i++) + { + int start_pos = 0; + + if (i >= 1) + start_pos += frag_length[0]; + if (i == 2) + start_pos += frag_length[1]; strncpy(str_copy + target_pos, str + start_pos, - frag_length[i]); + frag_length[i]); target_pos += frag_length[i]; - if (i != 2) { + if (i != 2) + { str_copy[target_pos] = ' '; target_pos++; } } str_copy[target_pos] = '\0'; - } else { + } + else + { str_copy = pgtypes_strdup(str); - if (!str_copy) { + if (!str_copy) return -1; - } /* convert the whole string to lower case */ - for (i = 0; str_copy[i]; i++) { + for (i = 0; str_copy[i]; i++) str_copy[i] = (char) tolower(str_copy[i]); - } } /* look for numerical tokens */ reading_digit = 0; - token_count = 0; - for (i = 0; i < strlen(str_copy); i++) { - if (!isdigit(str_copy[i]) && reading_digit) { + token_count = 0; + for (i = 0; i < strlen(str_copy); i++) + { + if (!isdigit(str_copy[i]) && reading_digit) + { /* the token is finished */ - token[token_count][1] = i-1; + token[token_count][1] = i - 1; reading_digit = 0; token_count++; - } else if (isdigit(str_copy[i]) && !reading_digit) { + } + else if (isdigit(str_copy[i]) && !reading_digit) + { /* we have found a token */ token[token_count][0] = i; reading_digit = 1; } } - /* we're at the end of the input string, but maybe we are still reading a - * number... */ - if (reading_digit) { - token[token_count][1] = i-1; + + /* + * we're at the end of the input string, but maybe we are still + * reading a number... + */ + if (reading_digit) + { + token[token_count][1] = i - 1; token_count++; } - if (token_count < 2) { - /* not all tokens found, no way to find 2 missing tokens - * with string matches */ + if (token_count < 2) + { + /* + * not all tokens found, no way to find 2 missing tokens with + * string matches + */ free(str_copy); errno = PGTYPES_DATE_ERR_ENOTDMY; return -1; } - if (token_count != 3) { - /* not all tokens found but we may find another one with - * string matches by testing for the months names and months - * abbreviations */ - char *month_lower_tmp = pgtypes_alloc(PGTYPES_DATE_MONTH_MAXLENGTH); - char *start_pos; - int j; - int offset; - int found = 0; - char** list; + if (token_count != 3) + { + /* + * not all tokens found but we may find another one with string + * matches by testing for the months names and months + * abbreviations + */ + char *month_lower_tmp = pgtypes_alloc(PGTYPES_DATE_MONTH_MAXLENGTH); + char *start_pos; + int j; + int offset; + int found = 0; + char **list; - if (!month_lower_tmp) { + if (!month_lower_tmp) + { /* free variables we alloc'ed before */ free(str_copy); return -1; } list = pgtypes_date_months; - for (i = 0; list[i]; i++) { - for (j = 0; j < PGTYPES_DATE_MONTH_MAXLENGTH; j++) { + for (i = 0; list[i]; i++) + { + for (j = 0; j < PGTYPES_DATE_MONTH_MAXLENGTH; j++) + { month_lower_tmp[j] = (char) tolower(list[i][j]); - if (!month_lower_tmp[j]) { + if (!month_lower_tmp[j]) + { /* properly terminated */ break; } } - if ((start_pos = strstr(str_copy, month_lower_tmp))) { + if ((start_pos = strstr(str_copy, month_lower_tmp))) + { offset = start_pos - str_copy; - /* sort the new token into the numeric - * tokens, shift them if necessary */ - if (offset < token[0][0]) { + + /* + * sort the new token into the numeric tokens, shift them + * if necessary + */ + if (offset < token[0][0]) + { token[2][0] = token[1][0]; token[2][1] = token[1][1]; token[1][0] = token[0][0]; token[1][1] = token[0][1]; token_count = 0; - } else if (offset < token[1][0]) { + } + else if (offset < token[1][0]) + { token[2][0] = token[1][0]; token[2][1] = token[1][1]; token_count = 1; - } else { - token_count = 2; } + else + token_count = 2; token[token_count][0] = offset; token[token_count][1] = offset + strlen(month_lower_tmp) - 1; - /* the value is the index of the month in - * the array of months + 1 (January is month - * 0) */ - token_values[token_count] = i+1; + + /* + * the value is the index of the month in the array of + * months + 1 (January is month 0) + */ + token_values[token_count] = i + 1; found = 1; break; } - /* evil[tm] hack: - * if we read the pgtypes_date_months and haven't - * found a match, reset list to point to - * pgtypes_date_months_short and reset the counter - * variable i */ - if (list == pgtypes_date_months) { - if (list[i+1] == NULL) { + + /* + * evil[tm] hack: if we read the pgtypes_date_months and + * haven't found a match, reset list to point to + * pgtypes_date_months_short and reset the counter variable i + */ + if (list == pgtypes_date_months) + { + if (list[i + 1] == NULL) + { list = months; i = -1; } } } - if (!found) { + if (!found) + { free(month_lower_tmp); free(str_copy); errno = PGTYPES_DATE_ERR_ENOTDMY; return -1; } - /* here we found a month. token[token_count] and + /* + * here we found a month. token[token_count] and * token_values[token_count] reflect the month's details. * * only the month can be specified with a literal. Here we can do a * quick check if the month is at the right position according to - * the format string because we can check if the token that - * we expect to be the month is at the position of the only - * token that already has a value. If we wouldn't check here - * we could say "December 4 1990" with a fmt string of - * "dd mm yy" for 12 April 1990. + * the format string because we can check if the token that we + * expect to be the month is at the position of the only token + * that already has a value. If we wouldn't check here we could + * say "December 4 1990" with a fmt string of "dd mm yy" for 12 + * April 1990. */ - if (fmt_token_order[token_count] != 'm') { + if (fmt_token_order[token_count] != 'm') + { /* deal with the error later on */ token_values[token_count] = -1; } @@ -544,24 +650,24 @@ PGTYPESdate_defmt_asc(Date *d, char *fmt, char *str) } /* terminate the tokens with ASCII-0 and get their values */ - for (i = 0; i < 3; i++) { + for (i = 0; i < 3; i++) + { *(str_copy + token[i][1] + 1) = '\0'; /* A month already has a value set, check for token_value == -1 */ - if (token_values[i] == -1) { + if (token_values[i] == -1) + { errno = 0; token_values[i] = strtol(str_copy + token[i][0], (char **) NULL, 10); /* strtol sets errno in case of an error */ - if (errno) { + if (errno) token_values[i] = -1; - } } - if (fmt_token_order[i] == 'd') { + if (fmt_token_order[i] == 'd') tm.tm_mday = token_values[i]; - } else if (fmt_token_order[i] == 'm') { + else if (fmt_token_order[i] == 'm') tm.tm_mon = token_values[i]; - } else if (fmt_token_order[i] == 'y') { + else if (fmt_token_order[i] == 'y') tm.tm_year = token_values[i]; - } } free(str_copy); @@ -577,7 +683,7 @@ PGTYPESdate_defmt_asc(Date *d, char *fmt, char *str) return -1; } - if (tm.tm_mday == 31 && (tm.tm_mon == 4 || tm.tm_mon == 6 || tm.tm_mon == 9 || tm.tm_mon ==11)) + if (tm.tm_mday == 31 && (tm.tm_mon == 4 || tm.tm_mon == 6 || tm.tm_mon == 9 || tm.tm_mon == 11)) { errno = PGTYPES_DATE_BAD_DAY; return -1; diff --git a/src/interfaces/ecpg/pgtypeslib/dt.h b/src/interfaces/ecpg/pgtypeslib/dt.h index e756c9c72d..ba6a38f2bd 100644 --- a/src/interfaces/ecpg/pgtypeslib/dt.h +++ b/src/interfaces/ecpg/pgtypeslib/dt.h @@ -3,7 +3,7 @@ #include -#define MAXTZLEN 10 +#define MAXTZLEN 10 #ifdef HAVE_INT64_TIMESTAMP @@ -17,10 +17,10 @@ typedef double fsec_t; #define JROUND(j) (rint(((double) (j))*TIME_PREC_INV)/TIME_PREC_INV) #endif -#define USE_POSTGRES_DATES 0 -#define USE_ISO_DATES 1 -#define USE_SQL_DATES 2 -#define USE_GERMAN_DATES 3 +#define USE_POSTGRES_DATES 0 +#define USE_ISO_DATES 1 +#define USE_SQL_DATES 2 +#define USE_GERMAN_DATES 3 #define DAGO "ago" #define EPOCH "epoch" @@ -49,7 +49,7 @@ typedef double fsec_t; #define DA_D "ad" #define DB_C "bc" #define DTIMEZONE "timezone" -#define DCURRENT "current" +#define DCURRENT "current" /* * Fundamental time field definitions for parsing. @@ -275,13 +275,12 @@ do { \ #define DT_NOBEGIN (-DBL_MAX) #define DT_NOEND (DBL_MAX) #endif - #endif /* HAVE_INT64_TIMESTAMP */ -#define TIMESTAMP_NOBEGIN(j) do {j = DT_NOBEGIN;} while (0) -#define TIMESTAMP_NOEND(j) do {j = DT_NOEND;} while (0) +#define TIMESTAMP_NOBEGIN(j) do {j = DT_NOBEGIN;} while (0) +#define TIMESTAMP_NOEND(j) do {j = DT_NOEND;} while (0) #define TIMESTAMP_IS_NOBEGIN(j) ((j) == DT_NOBEGIN) -#define TIMESTAMP_IS_NOEND(j) ((j) == DT_NOEND) +#define TIMESTAMP_IS_NOEND(j) ((j) == DT_NOEND) #define TIMESTAMP_NOT_FINITE(j) (TIMESTAMP_IS_NOBEGIN(j) || TIMESTAMP_IS_NOEND(j)) int DecodeTimeOnly(char **field, int *ftype, @@ -292,31 +291,30 @@ int DecodeInterval(char **field, int *ftype, int nf, int *dtype, struct tm * tm, fsec_t *fsec); -int EncodeTimeOnly(struct tm * tm, fsec_t fsec, int *tzp, int style, char *str); -int EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str, bool); -int EncodeInterval(struct tm * tm, fsec_t fsec, int style, char *str); +int EncodeTimeOnly(struct tm * tm, fsec_t fsec, int *tzp, int style, char *str); +int EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str, bool); +int EncodeInterval(struct tm * tm, fsec_t fsec, int style, char *str); -int tm2timestamp(struct tm *, fsec_t, int *, Timestamp *); +int tm2timestamp(struct tm *, fsec_t, int *, Timestamp *); -int DecodeUnits(int field, char *lowtoken, int *val); -bool ClearDateCache(bool, bool, bool); +int DecodeUnits(int field, char *lowtoken, int *val); +bool ClearDateCache(bool, bool, bool); -int j2day(int jd); +int j2day(int jd); -bool CheckDateTokenTables(void); +bool CheckDateTokenTables(void); -int EncodeDateOnly(struct tm *, int, char *, bool); -void GetEpochTime(struct tm *); -int ParseDateTime(char *, char *, char **, int *, int, int *, char **); -int DecodeDateTime(char **, int *, int, int *, struct tm *, fsec_t *, int *, bool); -void j2date(int, int *, int *, int *); -void GetCurrentDateTime(struct tm*); -int date2j(int, int, int); +int EncodeDateOnly(struct tm *, int, char *, bool); +void GetEpochTime(struct tm *); +int ParseDateTime(char *, char *, char **, int *, int, int *, char **); +int DecodeDateTime(char **, int *, int, int *, struct tm *, fsec_t *, int *, bool); +void j2date(int, int *, int *, int *); +void GetCurrentDateTime(struct tm *); +int date2j(int, int, int); -extern char* pgtypes_date_weekdays_short[]; -extern char* pgtypes_date_months[]; -extern char* months[]; -extern char* days[]; +extern char *pgtypes_date_weekdays_short[]; +extern char *pgtypes_date_months[]; +extern char *months[]; +extern char *days[]; #endif /* DT_H */ - diff --git a/src/interfaces/ecpg/pgtypeslib/dt_common.c b/src/interfaces/ecpg/pgtypeslib/dt_common.c index 89f50fe9a9..c4d28b0349 100644 --- a/src/interfaces/ecpg/pgtypeslib/dt_common.c +++ b/src/interfaces/ecpg/pgtypeslib/dt_common.c @@ -8,18 +8,18 @@ #include "dt.h" #include "pgtypes_timestamp.h" -static int day_tab[2][13] = { - {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}, - {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}}; +static int day_tab[2][13] = { + {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}, +{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}}; typedef long AbsoluteTime; - -#define ABS_SIGNBIT ((char) 0200) -#define POS(n) (n) -#define NEG(n) ((n)|ABS_SIGNBIT) -#define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */ -#define VALMASK ((char) 0177) -#define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c)) + +#define ABS_SIGNBIT ((char) 0200) +#define POS(n) (n) +#define NEG(n) ((n)|ABS_SIGNBIT) +#define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */ +#define VALMASK ((char) 0177) +#define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c)) static datetkn datetktbl[] = { /* text, token, lexval */ @@ -497,41 +497,41 @@ static datetkn deltatktbl[] = { static unsigned int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0]; static unsigned int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0]; -static datetkn *datecache[MAXDATEFIELDS] = {NULL}; +static datetkn *datecache[MAXDATEFIELDS] = {NULL}; -static datetkn *deltacache[MAXDATEFIELDS] = {NULL}; +static datetkn *deltacache[MAXDATEFIELDS] = {NULL}; -char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL}; +char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL}; -char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", NULL}; +char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", NULL}; -char* pgtypes_date_weekdays_short[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL}; +char *pgtypes_date_weekdays_short[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL}; -char* pgtypes_date_months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", NULL}; +char *pgtypes_date_months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", NULL}; static datetkn * datebsearch(char *key, datetkn *base, unsigned int nel) { - datetkn *last = base + nel - 1, - *position; - int result; + datetkn *last = base + nel - 1, + *position; + int result; while (last >= base) - { - position = base + ((last - base) >> 1); - result = key[0] - position->token[0]; - if (result == 0) - { - result = strncmp(key, position->token, TOKMAXLEN); - if (result == 0) - return position; - } - if (result < 0) - last = position - 1; - else - base = position + 1; - } - return NULL; + { + position = base + ((last - base) >> 1); + result = key[0] - position->token[0]; + if (result == 0) + { + result = strncmp(key, position->token, TOKMAXLEN); + if (result == 0) + return position; + } + if (result < 0) + last = position - 1; + else + base = position + 1; + } + return NULL; } /* DecodeUnits() @@ -580,7 +580,7 @@ DecodeUnits(int field, char *lowtoken, int *val) * * Rewritten to eliminate overflow problems. This now allows the * routines to work correctly for all Julian day counts from - * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming + * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming * a 32-bit integer. Longer types should also work to the limits * of their precision. */ @@ -591,18 +591,21 @@ date2j(int y, int m, int d) int julian; int century; - if (m > 2) { + if (m > 2) + { m += 1; y += 4800; - } else { + } + else + { m += 13; y += 4799; } - century = y/100; - julian = y*365 - 32167; - julian += y/4 - century + century/4; - julian += 7834*m/256 + d; + century = y / 100; + julian = y * 365 - 32167; + julian += y / 4 - century + century / 4; + julian += 7834 * m / 256 + d; return julian; } /* date2j() */ @@ -610,25 +613,25 @@ date2j(int y, int m, int d) void j2date(int jd, int *year, int *month, int *day) { - unsigned int julian; - unsigned int quad; - unsigned int extra; + unsigned int julian; + unsigned int quad; + unsigned int extra; int y; julian = jd; julian += 32044; - quad = julian/146097; - extra = (julian - quad*146097)*4 + 3; - julian += 60 + quad*3 + extra/146097; - quad = julian/1461; - julian -= quad*1461; + quad = julian / 146097; + extra = (julian - quad * 146097) * 4 + 3; + julian += 60 + quad * 3 + extra / 146097; + quad = julian / 1461; + julian -= quad * 1461; y = julian * 4 / 1461; julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366)) + 123; - y += quad*4; + y += quad * 4; *year = y - 4800; quad = julian * 2141 / 65536; - *day = julian - 7834*quad/256; + *day = julian - 7834 * quad / 256; *month = (quad + 10) % 12 + 1; return; @@ -637,13 +640,13 @@ j2date(int jd, int *year, int *month, int *day) int j2day(int date) { - unsigned int day; + unsigned int day; - day = date; - day += 1; - day %= 7; - return (int) day; -} /*j2day() */ + day = date; + day += 1; + day %= 7; + return (int) day; +} /* j2day() */ /* DecodeSpecial() * Decode text string using lookup table. @@ -753,14 +756,14 @@ EncodeDateOnly(struct tm * tm, int style, char *str, bool EuroDates) static void TrimTrailingZeros(char *str) { - int len = strlen(str); - - /* chop off trailing zeros... but leave at least 2 fractional digits */ - while ((*(str + len - 1) == '0') && (*(str + len - 3) != '.')) - { - len--; - *(str + len) = '\0'; - } + int len = strlen(str); + + /* chop off trailing zeros... but leave at least 2 fractional digits */ + while ((*(str + len - 1) == '0') && (*(str + len - 3) != '.')) + { + len--; + *(str + len) = '\0'; + } } /* EncodeDateTime() @@ -791,8 +794,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -841,8 +844,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -887,8 +890,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -941,8 +944,8 @@ EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, cha sprintf((str + 10), " %02d:%02d", tm->tm_hour, tm->tm_min); /* - * Print fractional seconds if any. The field widths here should - * be at least equal to MAX_TIMESTAMP_PRECISION. + * Print fractional seconds if any. The field widths here + * should be at least equal to MAX_TIMESTAMP_PRECISION. * * In float mode, don't print fractional seconds before 1 AD, * since it's unlikely there's any precision left ... @@ -1041,21 +1044,22 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) * We have a brute force time zone per SQL99? Then use it without * change since we have already rotated to the time zone. */ - *tzp = -tm->tm_gmtoff; /* tm_gmtoff is Sun/DEC-ism */ + *tzp = -tm->tm_gmtoff; /* tm_gmtoff is Sun/DEC-ism */ + /* * XXX FreeBSD man pages indicate that this should work - tgl * 97/04/23 */ if (tzn != NULL) { - /* - * Copy no more than MAXTZLEN bytes of timezone to tzn, in - * case it contains an error message, which doesn't fit in - * the buffer - */ - StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1); - if (strlen(tm->tm_zone) > MAXTZLEN) - tm->tm_isdst = -1; + /* + * Copy no more than MAXTZLEN bytes of timezone to tzn, in + * case it contains an error message, which doesn't fit in the + * buffer + */ + StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1); + if (strlen(tm->tm_zone) > MAXTZLEN) + tm->tm_isdst = -1; } } else @@ -1063,19 +1067,19 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) #elif defined(HAVE_INT_TIMEZONE) if (tzp != NULL) { - *tzp = ((tm->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL); + *tzp = ((tm->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL); - if (tzn != NULL) - { - /* - * Copy no more than MAXTZLEN bytes of timezone to tzn, in - * case it contains an error message, which doesn't fit in - * the buffer - */ - StrNCpy(*tzn, tzname[tm->tm_isdst], MAXTZLEN + 1); - if (strlen(tzname[tm->tm_isdst]) > MAXTZLEN) - tm->tm_isdst = -1; - } + if (tzn != NULL) + { + /* + * Copy no more than MAXTZLEN bytes of timezone to tzn, in + * case it contains an error message, which doesn't fit in the + * buffer + */ + StrNCpy(*tzn, tzname[tm->tm_isdst], MAXTZLEN + 1); + if (strlen(tzname[tm->tm_isdst]) > MAXTZLEN) + tm->tm_isdst = -1; + } } else tm->tm_isdst = -1; @@ -1245,33 +1249,33 @@ static void dt2time(double jd, int *hour, int *min, int *sec, fsec_t *fsec) { #ifdef HAVE_INT64_TIMESTAMP - int64 time; + int64 time; #else - double time; + double time; #endif time = jd; #ifdef HAVE_INT64_TIMESTAMP - *hour = (time / INT64CONST(3600000000)); - time -= ((*hour) * INT64CONST(3600000000)); - *min = (time / INT64CONST(60000000)); - time -= ((*min) * INT64CONST(60000000)); - *sec = (time / INT64CONST(1000000)); - *fsec = (time - (*sec * INT64CONST(1000000))); + *hour = (time / INT64CONST(3600000000)); + time -= ((*hour) * INT64CONST(3600000000)); + *min = (time / INT64CONST(60000000)); + time -= ((*min) * INT64CONST(60000000)); + *sec = (time / INT64CONST(1000000)); + *fsec = (time - (*sec * INT64CONST(1000000))); #else - *hour = (time / 3600); - time -= ((*hour) * 3600); + *hour = (time / 3600); + time -= ((*hour) * 3600); *min = (time / 60); - time -= ((*min) * 60); - *sec = time; - *fsec = JROUND(time - *sec); + time -= ((*min) * 60); + *sec = time; + *fsec = JROUND(time - *sec); #endif - return; -} /* dt2time() */ + return; +} /* dt2time() */ + + - - /* DecodeNumberField() * Interpret numeric string as a concatenated date or time field. * Use the context of previously decoded fields to help with @@ -1279,7 +1283,7 @@ dt2time(double jd, int *hour, int *min, int *sec, fsec_t *fsec) */ static int DecodeNumberField(int len, char *str, int fmask, - int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits, bool EuroDates) +int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits, bool EuroDates) { char *cp; @@ -1386,7 +1390,7 @@ DecodeNumberField(int len, char *str, int fmask, */ static int DecodeNumber(int flen, char *str, int fmask, - int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits, bool EuroDates) +int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits, bool EuroDates) { int val; char *cp; @@ -1405,7 +1409,7 @@ DecodeNumber(int flen, char *str, int fmask, */ if ((cp - str) > 2) return DecodeNumberField(flen, str, (fmask | DTK_DATE_M), - tmask, tm, fsec, is2digits, EuroDates); + tmask, tm, fsec, is2digits, EuroDates); *fsec = strtod(cp, &cp); if (*cp != '\0') @@ -1797,7 +1801,7 @@ DecodePosixTimezone(char *str, int *tzp) */ int ParseDateTime(char *timestr, char *lowstr, - char **field, int *ftype, int maxfields, int *numfields, char **endstr) + char **field, int *ftype, int maxfields, int *numfields, char **endstr) { int nf = 0; char *lp = lowstr; @@ -1980,7 +1984,7 @@ ParseDateTime(char *timestr, char *lowstr, */ int DecodeDateTime(char **field, int *ftype, int nf, - int *dtype, struct tm * tm, fsec_t *fsec, int *tzp, bool EuroDates) + int *dtype, struct tm * tm, fsec_t *fsec, int *tzp, bool EuroDates) { int fmask = 0, tmask, @@ -2085,7 +2089,7 @@ DecodeDateTime(char **field, int *ftype, int nf, * concatenated time */ if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], fmask, - &tmask, tm, fsec, &is2digits, EuroDates)) < 0) + &tmask, tm, fsec, &is2digits, EuroDates)) < 0) return -1; /* @@ -2272,7 +2276,7 @@ DecodeDateTime(char **field, int *ftype, int nf, case DTK_TIME: /* previous field was "t" for ISO time */ if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], (fmask | DTK_DATE_M), - &tmask, tm, fsec, &is2digits, EuroDates)) < 0) + &tmask, tm, fsec, &is2digits, EuroDates)) < 0) return -1; if (tmask != DTK_TIME_M) @@ -2310,18 +2314,18 @@ DecodeDateTime(char **field, int *ftype, int nf, * later. Example: 20011223 or 040506 */ if ((ftype[i] = DecodeNumberField(flen, field[i], fmask, - &tmask, tm, fsec, &is2digits, EuroDates)) < 0) + &tmask, tm, fsec, &is2digits, EuroDates)) < 0) return -1; } else if (flen > 4) { if ((ftype[i] = DecodeNumberField(flen, field[i], fmask, - &tmask, tm, fsec, &is2digits, EuroDates)) < 0) + &tmask, tm, fsec, &is2digits, EuroDates)) < 0) return -1; } /* otherwise it is a single date/time field... */ else if (DecodeNumber(flen, field[i], fmask, - &tmask, tm, fsec, &is2digits, EuroDates) != 0) + &tmask, tm, fsec, &is2digits, EuroDates) != 0) return -1; } break; @@ -2565,110 +2569,130 @@ DecodeDateTime(char **field, int *ftype, int nf, * * */ -static char* find_end_token(char* str, char* fmt) { - /* str: here is28the day12the hour - * fmt: here is%dthe day%hthe hour +static char * +find_end_token(char *str, char *fmt) +{ + /* + * str: here is28the day12the hour fmt: here is%dthe day%hthe hour * - * we extract the 28, we read the percent sign and the type "d" - * then this functions gets called as - * find_end_token("28the day12the hour", "the day%hthehour") + * we extract the 28, we read the percent sign and the type "d" then this + * functions gets called as find_end_token("28the day12the hour", "the + * day%hthehour") * - * fmt points to "the day%hthehour", next_percent points to - * %hthehour and we have to find a match for everything between - * these positions ("the day"). We look for "the day" in str and - * know that the pattern we are about to scan ends where this string - * starts (right after the "28") + * fmt points to "the day%hthehour", next_percent points to %hthehour and + * we have to find a match for everything between these positions + * ("the day"). We look for "the day" in str and know that the pattern + * we are about to scan ends where this string starts (right after the + * "28") * * At the end, *fmt is '\0' and *str isn't. end_position then is * unchanged. */ - char* end_position = NULL; - char* next_percent, *subst_location = NULL; - int scan_offset = 0; - char last_char; + char *end_position = NULL; + char *next_percent, + *subst_location = NULL; + int scan_offset = 0; + char last_char; /* are we at the end? */ - if (!*fmt) { + if (!*fmt) + { end_position = fmt; return end_position; } /* not at the end */ - while (fmt[scan_offset] == '%' && fmt[scan_offset+1]) { - /* there is no delimiter, skip to the next delimiter - * if we're reading a number and then something that is not - * a number "9:15pm", we might be able to recover with the - * strtol end pointer. Go for the next percent sign */ + while (fmt[scan_offset] == '%' && fmt[scan_offset + 1]) + { + /* + * there is no delimiter, skip to the next delimiter if we're + * reading a number and then something that is not a number + * "9:15pm", we might be able to recover with the strtol end + * pointer. Go for the next percent sign + */ scan_offset += 2; } - next_percent = strchr(fmt+scan_offset, '%'); - if (next_percent) { - /* we don't want to allocate extra memory, so we temporarily - * set the '%' sign to '\0' and call strstr - * However since we allow whitespace to float around - * everything, we have to shorten the pattern until we reach - * a non-whitespace character */ - + next_percent = strchr(fmt + scan_offset, '%'); + if (next_percent) + { + /* + * we don't want to allocate extra memory, so we temporarily set + * the '%' sign to '\0' and call strstr However since we allow + * whitespace to float around everything, we have to shorten the + * pattern until we reach a non-whitespace character + */ + subst_location = next_percent; - while(*(subst_location-1) == ' ' && subst_location-1 > fmt+scan_offset) { + while (*(subst_location - 1) == ' ' && subst_location - 1 > fmt + scan_offset) subst_location--; - } last_char = *subst_location; *subst_location = '\0'; - /* the haystack is the str and the needle is the original - * fmt but it ends at the position where the next percent - * sign would be */ - /* There is one special case. Imagine: - * str = " 2", fmt = "%d %...", - * since we want to allow blanks as "dynamic" padding we - * have to accept this. Now, we are called with a fmt of - * " %..." and look for " " in str. We find it at the first - * position and never read the 2... */ - while (*str == ' ') { str++; } - end_position = strstr(str, fmt+scan_offset); + /* + * the haystack is the str and the needle is the original fmt but + * it ends at the position where the next percent sign would be + */ + + /* + * There is one special case. Imagine: str = " 2", fmt = "%d + * %...", since we want to allow blanks as "dynamic" padding we + * have to accept this. Now, we are called with a fmt of " %..." + * and look for " " in str. We find it at the first position and + * never read the 2... + */ + while (*str == ' ') + str++; + end_position = strstr(str, fmt + scan_offset); *subst_location = last_char; - } else { - /* there is no other percent sign. So everything up to - * the end has to match. */ + } + else + { + /* + * there is no other percent sign. So everything up to the end has + * to match. + */ end_position = str + strlen(str); } - if (!end_position) { - /* maybe we have the following case: + if (!end_position) + { + /* + * maybe we have the following case: * - * str = "4:15am" - * fmt = "%M:%S %p" + * str = "4:15am" fmt = "%M:%S %p" * * at this place we could have * - * str = "15am" - * fmt = " %p" + * str = "15am" fmt = " %p" * - * and have set fmt to " " because overwrote the % sign with - * a NULL + * and have set fmt to " " because overwrote the % sign with a NULL * - * In this case where we would have to match a space but - * can't find it, set end_position to the end of the string */ - if ((fmt+scan_offset)[0] == ' ' && fmt+scan_offset+1 == subst_location) { + * In this case where we would have to match a space but can't find + * it, set end_position to the end of the string + */ + if ((fmt + scan_offset)[0] == ' ' && fmt + scan_offset + 1 == subst_location) end_position = str + strlen(str); - } } return end_position; } -static int pgtypes_defmt_scan(union un_fmt_comb* scan_val, int scan_type, char** pstr, char* pfmt) { - /* scan everything between pstr and pstr_end. - * This is not including the last character so we might set it to - * '\0' for the parsing */ +static int +pgtypes_defmt_scan(union un_fmt_comb * scan_val, int scan_type, char **pstr, char *pfmt) +{ + /* + * scan everything between pstr and pstr_end. This is not including + * the last character so we might set it to '\0' for the parsing + */ - char last_char; - int err = 0; - char* pstr_end; - char* strtol_end = NULL; - - while (**pstr == ' ') { pstr++; } + char last_char; + int err = 0; + char *pstr_end; + char *strtol_end = NULL; + + while (**pstr == ' ') + pstr++; pstr_end = find_end_token(*pstr, pfmt); - if (!pstr_end) { + if (!pstr_end) + { /* there was an error, no match */ err = 1; return err; @@ -2676,63 +2700,80 @@ static int pgtypes_defmt_scan(union un_fmt_comb* scan_val, int scan_type, char** last_char = *pstr_end; *pstr_end = '\0'; - switch(scan_type) { + switch (scan_type) + { case PGTYPES_TYPE_UINT: - /* numbers may be blank-padded, this is the only - * deviation from the fmt-string we accept */ - while (**pstr == ' ') { (*pstr)++; } + + /* + * numbers may be blank-padded, this is the only deviation + * from the fmt-string we accept + */ + while (**pstr == ' ') + (*pstr)++; errno = 0; scan_val->uint_val = (unsigned int) strtol(*pstr, &strtol_end, 10); - if (errno) { err = 1; } + if (errno) + err = 1; break; case PGTYPES_TYPE_UINT_LONG: - while (**pstr == ' ') { (*pstr)++; } + while (**pstr == ' ') + (*pstr)++; errno = 0; scan_val->uint_val = (unsigned long int) strtol(*pstr, &strtol_end, 10); - if (errno) { err = 1; } + if (errno) + err = 1; break; case PGTYPES_TYPE_STRING_MALLOCED: - if (pstr) { + if (pstr) scan_val->str_val = pgtypes_strdup(*pstr); - } } - if (strtol_end && *strtol_end) { + if (strtol_end && *strtol_end) *pstr = strtol_end; - } else { + else *pstr = pstr_end; - } *pstr_end = last_char; return err; } /* XXX range checking */ -int PGTYPEStimestamp_defmt_scan(char**, char*, Timestamp *, int*, int*, int*, - int*, int*, int*, int*); +int PGTYPEStimestamp_defmt_scan(char **, char *, Timestamp *, int *, int *, int *, + int *, int *, int *, int *); -int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, - int* year, int* month, int* day, - int* hour, int* minute, int* second, - int* tz) { +int +PGTYPEStimestamp_defmt_scan(char **str, char *fmt, Timestamp *d, + int *year, int *month, int *day, + int *hour, int *minute, int *second, + int *tz) +{ union un_fmt_comb scan_val; - int scan_type; + int scan_type; - char *pstr, *pfmt, *tmp; - int err = 1; - int j; - struct tm tm; + char *pstr, + *pfmt, + *tmp; + int err = 1; + int j; + struct tm tm; pfmt = fmt; pstr = *str; - - while (*pfmt) { + + while (*pfmt) + { err = 0; - while (*pfmt == ' ') { pfmt++; } - while (*pstr == ' ') { pstr++; } - if (*pfmt != '%') { - if (*pfmt == *pstr) { + while (*pfmt == ' ') + pfmt++; + while (*pstr == ' ') + pstr++; + if (*pfmt != '%') + { + if (*pfmt == *pstr) + { pfmt++; pstr++; - } else { + } + else + { /* XXX Error: no match */ err = 1; return err; @@ -2741,17 +2782,22 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, } /* here *pfmt equals '%' */ pfmt++; - switch(*pfmt) { + switch (*pfmt) + { case 'a': pfmt++; - /* we parse the day and see if it is a week - * day but we do not check if the week day - * really matches the date - * */ - err = 1; j = 0; - while(pgtypes_date_weekdays_short[j]) { + + /* + * we parse the day and see if it is a week day but we do + * not check if the week day really matches the date + */ + err = 1; + j = 0; + while (pgtypes_date_weekdays_short[j]) + { if (strncmp(pgtypes_date_weekdays_short[j], pstr, - strlen(pgtypes_date_weekdays_short[j])) == 0) { + strlen(pgtypes_date_weekdays_short[j])) == 0) + { /* found it */ err = 0; pstr += strlen(pgtypes_date_weekdays_short[j]); @@ -2763,9 +2809,12 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, case 'A': /* see note above */ pfmt++; - err = 1; j = 0; - while(days[j]) { - if (strncmp(days[j], pstr, strlen(days[j])) == 0) { + err = 1; + j = 0; + while (days[j]) + { + if (strncmp(days[j], pstr, strlen(days[j])) == 0) + { /* found it */ err = 0; pstr += strlen(days[j]); @@ -2777,13 +2826,16 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, case 'b': case 'h': pfmt++; - err = 1; j = 0; - while(months[j]) { - if (strncmp(months[j], pstr, strlen(months[j])) == 0) { + err = 1; + j = 0; + while (months[j]) + { + if (strncmp(months[j], pstr, strlen(months[j])) == 0) + { /* found it */ err = 0; pstr += strlen(months[j]); - *month = j+1; + *month = j + 1; break; } j++; @@ -2792,13 +2844,16 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, case 'B': /* see note above */ pfmt++; - err = 1; j = 0; - while(pgtypes_date_months[j]) { - if (strncmp(pgtypes_date_months[j], pstr, strlen(pgtypes_date_months[j])) == 0) { + err = 1; + j = 0; + while (pgtypes_date_months[j]) + { + if (strncmp(pgtypes_date_months[j], pstr, strlen(pgtypes_date_months[j])) == 0) + { /* found it */ err = 0; pstr += strlen(pgtypes_date_months[j]); - *month = j+1; + *month = j + 1; break; } j++; @@ -2821,9 +2876,11 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, *day = scan_val.uint_val; break; case 'D': - /* we have to concatenate the strings in - * order to be able to find the end of the - * substitution */ + + /* + * we have to concatenate the strings in order to be able + * to find the end of the substitution + */ pfmt++; tmp = pgtypes_alloc(strlen("%m/%d/%y") + strlen(pstr) + 1); strcpy(tmp, "%m/%d/%y"); @@ -2838,17 +2895,19 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, *month = scan_val.uint_val; break; case 'y': - case 'g': /* XXX difference to y (ISO) */ + case 'g': /* XXX difference to y (ISO) */ pfmt++; scan_type = PGTYPES_TYPE_UINT; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - if (*year < 0) { + if (*year < 0) + { /* not yet set */ *year = scan_val.uint_val; - } else { - *year += scan_val.uint_val; } - if (*year < 100) { *year += 1900; } + else + *year += scan_val.uint_val; + if (*year < 100) + *year += 1900; break; case 'G': /* XXX difference to %V (ISO) */ @@ -2870,10 +2929,12 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, pfmt++; scan_type = PGTYPES_TYPE_UINT; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - /* XXX what should we do with that? - * We could say that it's sufficient if we - * have the year and the day within the year - * to get at least a specific day. */ + + /* + * XXX what should we do with that? We could say that it's + * sufficient if we have the year and the day within the + * year to get at least a specific day. + */ break; case 'M': pfmt++; @@ -2883,23 +2944,66 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, break; case 'n': pfmt++; - if (*pstr == '\n') { pstr++; } else { err = 1; } + if (*pstr == '\n') + pstr++; + else + err = 1; break; case 'p': err = 1; pfmt++; - if (strncmp(pstr, "am", 2) == 0) { *hour += 0; err = 0; pstr += 2; } - if (strncmp(pstr, "a.m.", 4) == 0) { *hour += 0; err = 0; pstr += 4; } - if (strncmp(pstr, "pm", 2) == 0) { *hour += 12; err = 0; pstr += 2; } - if (strncmp(pstr, "p.m.", 4) == 0) { *hour += 12; err = 0; pstr += 4; } - break; + if (strncmp(pstr, "am", 2) == 0) + { + *hour += 0; + err = 0; + pstr += 2; + } + if (strncmp(pstr, "a.m.", 4) == 0) + { + *hour += 0; + err = 0; + pstr += 4; + } + if (strncmp(pstr, "pm", 2) == 0) + { + *hour += 12; + err = 0; + pstr += 2; + } + if (strncmp(pstr, "p.m.", 4) == 0) + { + *hour += 12; + err = 0; + pstr += 4; + } + break; case 'P': err = 1; pfmt++; - if (strncmp(pstr, "AM", 2) == 0) { *hour += 0; err = 0; pstr += 2; } - if (strncmp(pstr, "A.M.", 4) == 0) { *hour += 0; err = 0; pstr += 4; } - if (strncmp(pstr, "PM", 2) == 0) { *hour += 12; err = 0; pstr += 2; } - if (strncmp(pstr, "P.M.", 4) == 0) { *hour += 12; err = 0; pstr += 4; } + if (strncmp(pstr, "AM", 2) == 0) + { + *hour += 0; + err = 0; + pstr += 2; + } + if (strncmp(pstr, "A.M.", 4) == 0) + { + *hour += 0; + err = 0; + pstr += 4; + } + if (strncmp(pstr, "PM", 2) == 0) + { + *hour += 12; + err = 0; + pstr += 2; + } + if (strncmp(pstr, "P.M.", 4) == 0) + { + *hour += 12; + err = 0; + pstr += 4; + } break; case 'r': pfmt++; @@ -2923,8 +3027,9 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); /* number of seconds in scan_val.luint_val */ { - struct tm *tms; - time_t et = (time_t) scan_val.luint_val; + struct tm *tms; + time_t et = (time_t) scan_val.luint_val; + tms = gmtime(&et); *year = tms->tm_year; *month = tms->tm_mon; @@ -2942,7 +3047,10 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, break; case 't': pfmt++; - if (*pstr == '\t') { pstr++; } else { err = 1; } + if (*pstr == '\t') + pstr++; + else + err = 1; break; case 'T': pfmt++; @@ -2956,31 +3064,36 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, pfmt++; scan_type = PGTYPES_TYPE_UINT; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - if (scan_val.uint_val < 1 || scan_val.uint_val > 7) { err = 1; } + if (scan_val.uint_val < 1 || scan_val.uint_val > 7) + err = 1; break; case 'U': pfmt++; scan_type = PGTYPES_TYPE_UINT; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - if (scan_val.uint_val < 0 || scan_val.uint_val > 53) { err = 1; } + if (scan_val.uint_val < 0 || scan_val.uint_val > 53) + err = 1; break; case 'V': pfmt++; scan_type = PGTYPES_TYPE_UINT; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - if (scan_val.uint_val < 1 || scan_val.uint_val > 53) { err = 1; } + if (scan_val.uint_val < 1 || scan_val.uint_val > 53) + err = 1; break; case 'w': pfmt++; scan_type = PGTYPES_TYPE_UINT; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - if (scan_val.uint_val < 0 || scan_val.uint_val > 6) { err = 1; } + if (scan_val.uint_val < 0 || scan_val.uint_val > 6) + err = 1; break; case 'W': pfmt++; scan_type = PGTYPES_TYPE_UINT; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - if (scan_val.uint_val < 0 || scan_val.uint_val > 53) { err = 1; } + if (scan_val.uint_val < 0 || scan_val.uint_val > 53) + err = 1; break; case 'x': case 'X': @@ -2996,7 +3109,8 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, pfmt++; scan_type = PGTYPES_TYPE_STRING_MALLOCED; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - if (!err) { + if (!err) + { err = DecodeTimezone(scan_val.str_val, tz); free(scan_val.str_val); } @@ -3005,16 +3119,20 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, pfmt++; scan_type = PGTYPES_TYPE_STRING_MALLOCED; err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt); - /* XXX use DecodeSpecial instead ? - it's - * declared static but the arrays as well. - * :-( */ - for (j = 0; !err && j < szdatetktbl; j++) { - if (strcasecmp(datetktbl[j].token, scan_val.str_val) == 0) { - /* tz calculates the offset - * for the seconds, the - * timezone value of the - * datetktbl table is in - * quarter hours */ + + /* + * XXX use DecodeSpecial instead ? - it's declared static + * but the arrays as well. :-( + */ + for (j = 0; !err && j < szdatetktbl; j++) + { + if (strcasecmp(datetktbl[j].token, scan_val.str_val) == 0) + { + /* + * tz calculates the offset for the seconds, the + * timezone value of the datetktbl table is in + * quarter hours + */ *tz = -15 * 60 * datetktbl[j].value; break; } @@ -3026,26 +3144,62 @@ int PGTYPEStimestamp_defmt_scan(char** str, char* fmt, Timestamp *d, break; case '%': pfmt++; - if (*pstr == '%') { pstr++; } else { err = 1; } + if (*pstr == '%') + pstr++; + else + err = 1; break; default: err = 1; } } - if (!err) { - if (*second < 0) { *second = 0; } - if (*minute < 0) { *minute = 0; } - if (*hour < 0) { *hour = 0; } - if (*day < 0) { err = 1; *day = 1; } - if (*month < 0) { err = 1; *month = 1; } - if (*year < 0) { err = 1; *year = 1970; } + if (!err) + { + if (*second < 0) + *second = 0; + if (*minute < 0) + *minute = 0; + if (*hour < 0) + *hour = 0; + if (*day < 0) + { + err = 1; + *day = 1; + } + if (*month < 0) + { + err = 1; + *month = 1; + } + if (*year < 0) + { + err = 1; + *year = 1970; + } - if (*second > 59) { err = 1; *second = 0; } - if (*minute > 59) { err = 1; *minute = 0; } - if (*hour > 23) { err = 1; *hour = 0; } - if (*month > 12) { err = 1; *month = 1; } - if (*day > day_tab[isleap(*year)][*month-1]) { - *day = day_tab[isleap(*year)][*month-1]; + if (*second > 59) + { + err = 1; + *second = 0; + } + if (*minute > 59) + { + err = 1; + *minute = 0; + } + if (*hour > 23) + { + err = 1; + *hour = 0; + } + if (*month > 12) + { + err = 1; + *month = 1; + } + if (*day > day_tab[isleap(*year)][*month - 1]) + { + *day = day_tab[isleap(*year)][*month - 1]; err = 1; } diff --git a/src/interfaces/ecpg/pgtypeslib/extern.h b/src/interfaces/ecpg/pgtypeslib/extern.h index 8004e3d421..110f56b5c9 100644 --- a/src/interfaces/ecpg/pgtypeslib/extern.h +++ b/src/interfaces/ecpg/pgtypeslib/extern.h @@ -9,44 +9,46 @@ #define PGTYPES_TYPE_STRING_MALLOCED 1 #define PGTYPES_TYPE_STRING_CONSTANT 2 #define PGTYPES_TYPE_CHAR 3 -#define PGTYPES_TYPE_DOUBLE_NF 4 /* no fractional part */ +#define PGTYPES_TYPE_DOUBLE_NF 4 /* no fractional part */ #define PGTYPES_TYPE_INT64 5 #define PGTYPES_TYPE_UINT 6 -#define PGTYPES_TYPE_UINT_2_LZ 7 /* 2 digits, pad with leading zero */ -#define PGTYPES_TYPE_UINT_2_LS 8 /* 2 digits, pad with leading space */ +#define PGTYPES_TYPE_UINT_2_LZ 7 /* 2 digits, pad with + * leading zero */ +#define PGTYPES_TYPE_UINT_2_LS 8 /* 2 digits, pad with + * leading space */ #define PGTYPES_TYPE_UINT_3_LZ 9 #define PGTYPES_TYPE_UINT_4_LZ 10 #define PGTYPES_TYPE_UINT_LONG 11 #define PGTYPES_FMT_NUM_MAX_DIGITS 40 -union un_fmt_comb { - char* str_val; - unsigned int uint_val; - char char_val; - unsigned long int luint_val; - double double_val; +union un_fmt_comb +{ + char *str_val; + unsigned int uint_val; + char char_val; + unsigned long int luint_val; + double double_val; #ifdef HAVE_INT64_TIMESTAMP - int64 int64_val; + int64 int64_val; #endif }; -int pgtypes_fmt_replace(union un_fmt_comb, int, char**, int*); +int pgtypes_fmt_replace(union un_fmt_comb, int, char **, int *); -char *pgtypes_alloc(long); -char *pgtypes_strdup(char *); +char *pgtypes_alloc(long); +char *pgtypes_strdup(char *); #ifndef bool #define bool char #endif /* ndef bool */ #ifndef FALSE -#define FALSE 0 +#define FALSE 0 #endif /* FALSE */ #ifndef TRUE -#define TRUE 1 -#endif /* TRUE */ - -#endif /* __PGTYPES_COMMON_H__ */ +#define TRUE 1 +#endif /* TRUE */ +#endif /* __PGTYPES_COMMON_H__ */ diff --git a/src/interfaces/ecpg/pgtypeslib/interval.c b/src/interfaces/ecpg/pgtypeslib/interval.c index 0646f480f4..efde760c87 100644 --- a/src/interfaces/ecpg/pgtypeslib/interval.c +++ b/src/interfaces/ecpg/pgtypeslib/interval.c @@ -743,7 +743,7 @@ tm2interval(struct tm * tm, fsec_t fsec, Interval *span) Interval * PGTYPESinterval_from_asc(char *str, char **endptr) { - Interval *result = NULL; + Interval *result = NULL; fsec_t fsec; struct tm tt, *tm = &tt; @@ -752,8 +752,8 @@ PGTYPESinterval_from_asc(char *str, char **endptr) char *field[MAXDATEFIELDS]; int ftype[MAXDATEFIELDS]; char lowstr[MAXDATELEN + MAXDATEFIELDS]; - char *realptr; - char **ptr = (endptr != NULL) ? endptr : &realptr; + char *realptr; + char **ptr = (endptr != NULL) ? endptr : &realptr; tm->tm_year = 0; tm->tm_mon = 0; @@ -791,7 +791,7 @@ PGTYPESinterval_from_asc(char *str, char **endptr) errno = PGTYPES_INTVL_BAD_INTERVAL; return NULL; } - + return result; } @@ -802,7 +802,7 @@ PGTYPESinterval_to_asc(Interval *span) *tm = &tt; fsec_t fsec; char buf[MAXDATELEN + 1]; - int DateStyle=0; + int DateStyle = 0; if (interval2tm(*span, tm, &fsec) != 0) { @@ -815,11 +815,11 @@ PGTYPESinterval_to_asc(Interval *span) errno = PGTYPES_INTVL_BAD_INTERVAL; return NULL; } - - return pgtypes_strdup(buf); + + return pgtypes_strdup(buf); } -int +int PGTYPESinterval_copy(Interval *intvlsrc, Interval *intrcldest) { intrcldest->time = intvlsrc->time; @@ -827,4 +827,3 @@ PGTYPESinterval_copy(Interval *intvlsrc, Interval *intrcldest) return 0; } - diff --git a/src/interfaces/ecpg/pgtypeslib/numeric.c b/src/interfaces/ecpg/pgtypeslib/numeric.c index 6ac9ae48ee..5811be61c8 100644 --- a/src/interfaces/ecpg/pgtypeslib/numeric.c +++ b/src/interfaces/ecpg/pgtypeslib/numeric.c @@ -5,17 +5,17 @@ #include "extern.h" #include "pgtypes_error.h" -#define Max(x, y) ((x) > (y) ? (x) : (y)) -#define Min(x, y) ((x) < (y) ? (x) : (y)) +#define Max(x, y) ((x) > (y) ? (x) : (y)) +#define Min(x, y) ((x) < (y) ? (x) : (y)) -#define init_var(v) memset(v,0,sizeof(Numeric)) +#define init_var(v) memset(v,0,sizeof(Numeric)) #define digitbuf_alloc(size) ((NumericDigit *) pgtypes_alloc(size)) -#define digitbuf_free(buf) \ - do { \ - if ((buf) != NULL) \ - free(buf); \ - } while (0) +#define digitbuf_free(buf) \ + do { \ + if ((buf) != NULL) \ + free(buf); \ + } while (0) #include "pgtypes_numeric.h" @@ -27,7 +27,7 @@ * typmod field. * ---------- */ -static int +static int apply_typmod(Numeric *var, long typmod) { int precision; @@ -37,7 +37,7 @@ apply_typmod(Numeric *var, long typmod) /* Do nothing if we have a default typmod (-1) */ if (typmod < (long) (VARHDRSZ)) - return(0); + return (0); typmod -= VARHDRSZ; precision = (typmod >> 16) & 0xffff; @@ -102,9 +102,9 @@ apply_typmod(Numeric *var, long typmod) #endif /* ---------- - * alloc_var() - - * - * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding) + * alloc_var() - + * + * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding) * ---------- */ static int @@ -120,17 +120,16 @@ alloc_var(Numeric *var, int ndigits) return 0; } -Numeric * +Numeric * PGTYPESnumeric_new(void) { - Numeric *var; - - if ((var = (Numeric *)pgtypes_alloc(sizeof(Numeric))) == NULL) + Numeric *var; + + if ((var = (Numeric *) pgtypes_alloc(sizeof(Numeric))) == NULL) return NULL; - if (alloc_var(var, 0) < 0) { + if (alloc_var(var, 0) < 0) return NULL; - } return var; } @@ -141,11 +140,11 @@ PGTYPESnumeric_new(void) * Parse a string and put the number into a variable * ---------- */ -static int +static int set_var_from_str(char *str, char **ptr, Numeric *dest) { - bool have_dp = FALSE; - int i = 0; + bool have_dp = FALSE; + int i = 0; *ptr = str; while (*(*ptr)) @@ -182,7 +181,7 @@ set_var_from_str(char *str, char **ptr, Numeric *dest) if (!isdigit((unsigned char) *(*ptr))) { - errno=PGTYPES_NUM_BAD_NUMERIC; + errno = PGTYPES_NUM_BAD_NUMERIC; return -1; } @@ -259,7 +258,7 @@ set_var_from_str(char *str, char **ptr, Numeric *dest) dest->weight = 0; dest->rscale = dest->dscale; - return(0); + return (0); } @@ -308,7 +307,7 @@ get_str_from_var(Numeric *var, int dscale) /* * Allocate space for the result */ - if ((str = (char *)pgtypes_alloc(Max(0, dscale) + Max(0, var->weight) + 4)) == NULL) + if ((str = (char *) pgtypes_alloc(Max(0, dscale) + Max(0, var->weight) + 4)) == NULL) return NULL; cp = str; @@ -360,17 +359,18 @@ get_str_from_var(Numeric *var, int dscale) Numeric * PGTYPESnumeric_from_asc(char *str, char **endptr) { - Numeric *value = (Numeric *)pgtypes_alloc(sizeof(Numeric)); - int ret; + Numeric *value = (Numeric *) pgtypes_alloc(sizeof(Numeric)); + int ret; + #if 0 - long typmod = -1; + long typmod = -1; #endif - char *realptr; - char **ptr = (endptr != NULL) ? endptr : &realptr; - + char *realptr; + char **ptr = (endptr != NULL) ? endptr : &realptr; + if (!value) return (NULL); - + ret = set_var_from_str(str, ptr, value); if (ret) return (NULL); @@ -379,8 +379,8 @@ PGTYPESnumeric_from_asc(char *str, char **endptr) ret = apply_typmod(value, typmod); if (ret) return (NULL); -#endif - return(value); +#endif + return (value); } char * @@ -389,7 +389,7 @@ PGTYPESnumeric_to_asc(Numeric *num, int dscale) if (dscale <= 0) dscale = num->dscale; - return(get_str_from_var(num, dscale)); + return (get_str_from_var(num, dscale)); } /* ---------- @@ -410,7 +410,7 @@ zero_var(Numeric *var) var->sign = NUMERIC_POS; /* anything but NAN... */ } -void +void PGTYPESnumeric_free(Numeric *var) { digitbuf_free(var->buf); @@ -913,7 +913,7 @@ PGTYPESnumeric_sub(Numeric *var1, Numeric *var2, Numeric *result) * mul_var() - * * Multiplication on variable level. Product of var1 * var2 is stored - * in result. Accuracy of result is determined by global_rscale. + * in result. Accuracy of result is determined by global_rscale. * ---------- */ int @@ -929,7 +929,7 @@ PGTYPESnumeric_mul(Numeric *var1, Numeric *var2, Numeric *result) i1, i2; long sum = 0; - int global_rscale = var1->rscale + var2->rscale; + int global_rscale = var1->rscale + var2->rscale; res_weight = var1->weight + var2->weight + 2; res_ndigits = var1->ndigits + var2->ndigits + 1; @@ -939,7 +939,7 @@ PGTYPESnumeric_mul(Numeric *var1, Numeric *var2, Numeric *result) res_sign = NUMERIC_NEG; if ((res_buf = digitbuf_alloc(res_ndigits)) == NULL) - return -1; + return -1; res_digits = res_buf; memset(res_digits, 0, res_ndigits); @@ -1054,8 +1054,8 @@ select_div_scale(Numeric *var1, Numeric *var2, int *rscale) } /* - * Estimate weight of quotient. If the two first digits are equal, - * we can't be sure, but assume that var1 is less than var2. + * Estimate weight of quotient. If the two first digits are equal, we + * can't be sure, but assume that var1 is less than var2. */ qweight = weight1 - weight2; if (firstdigit1 <= firstdigit2) @@ -1081,8 +1081,8 @@ PGTYPESnumeric_div(Numeric *var1, Numeric *var2, Numeric *result) int res_ndigits; int res_sign; int res_weight; - Numeric dividend; - Numeric divisor[10]; + Numeric dividend; + Numeric divisor[10]; int ndigits_tmp; int weight_tmp; int rscale_tmp; @@ -1093,16 +1093,16 @@ PGTYPESnumeric_div(Numeric *var1, Numeric *var2, Numeric *result) long first_div; int first_nextdigit; int stat = 0; - int rscale; - int res_dscale = select_div_scale(var1, var2, &rscale); - + int rscale; + int res_dscale = select_div_scale(var1, var2, &rscale); + /* * First of all division by zero check */ ndigits_tmp = var2->ndigits + 1; if (ndigits_tmp == 1) { - errno= PGTYPES_NUM_DIVIDE_ZERO; + errno = PGTYPES_NUM_DIVIDE_ZERO; return -1; } @@ -1281,29 +1281,30 @@ PGTYPESnumeric_div(Numeric *var1, Numeric *var2, Numeric *result) int -PGTYPESnumeric_cmp(Numeric *var1, Numeric *var2) { +PGTYPESnumeric_cmp(Numeric *var1, Numeric *var2) +{ /* use cmp_abs function to calculate the result */ /* both are positive: normal comparation with cmp_abs */ - if (var1->sign == NUMERIC_POS && var2->sign == NUMERIC_POS) { + if (var1->sign == NUMERIC_POS && var2->sign == NUMERIC_POS) return cmp_abs(var1, var2); - } /* both are negative: return the inverse of the normal comparation */ - if (var1->sign == NUMERIC_NEG && var2->sign == NUMERIC_NEG) { - /* instead of inverting the result, we invert the paramter - * ordering */ + if (var1->sign == NUMERIC_NEG && var2->sign == NUMERIC_NEG) + { + /* + * instead of inverting the result, we invert the paramter + * ordering + */ return cmp_abs(var2, var1); } /* one is positive, one is negative: trivial */ - if (var1->sign == NUMERIC_POS && var2->sign == NUMERIC_NEG) { + if (var1->sign == NUMERIC_POS && var2->sign == NUMERIC_NEG) return 1; - } - if (var1->sign == NUMERIC_NEG && var2->sign == NUMERIC_POS) { + if (var1->sign == NUMERIC_NEG && var2->sign == NUMERIC_POS) return -1; - } errno = PGTYPES_NUM_BAD_NUMERIC; return INT_MAX; @@ -1311,67 +1312,79 @@ PGTYPESnumeric_cmp(Numeric *var1, Numeric *var2) { } int -PGTYPESnumeric_from_int(signed int int_val, Numeric *var) { +PGTYPESnumeric_from_int(signed int int_val, Numeric *var) +{ /* implicit conversion */ signed long int long_int = int_val; + return PGTYPESnumeric_from_long(long_int, var); } int -PGTYPESnumeric_from_long(signed long int long_val, Numeric *var) { +PGTYPESnumeric_from_long(signed long int long_val, Numeric *var) +{ /* calculate the size of the long int number */ /* a number n needs log_10 n digits */ - /* however we multiply by 10 each time and compare instead of - * calculating the logarithm */ - int size = 0; - int i; + /* + * however we multiply by 10 each time and compare instead of + * calculating the logarithm + */ + + int size = 0; + int i; signed long int abs_long_val = long_val; signed long int extract; signed long int reach_limit; - - if (abs_long_val < 0) { + + if (abs_long_val < 0) + { abs_long_val *= -1; var->sign = NUMERIC_NEG; - } else { - var->sign = NUMERIC_POS; } + else + var->sign = NUMERIC_POS; reach_limit = 1; - do { + do + { size++; reach_limit *= 10; - } while ((reach_limit-1) < abs_long_val); + } while ((reach_limit - 1) < abs_long_val); /* always add a .0 */ size++; - if (alloc_var(var, size) < 0) { + if (alloc_var(var, size) < 0) return -1; - } var->rscale = 1; var->dscale = 1; var->weight = size - 2; i = 0; - do { + do + { reach_limit /= 10; extract = abs_long_val - (abs_long_val % reach_limit); var->digits[i] = extract / reach_limit; abs_long_val -= extract; i++; - /* we can abandon if abs_long_val reaches 0, because the - * memory is initialized properly and filled with '0', so - * converting 10000 in only one step is no problem */ + + /* + * we can abandon if abs_long_val reaches 0, because the memory is + * initialized properly and filled with '0', so converting 10000 + * in only one step is no problem + */ } while (abs_long_val > 0); return 0; } int -PGTYPESnumeric_copy(Numeric *src, Numeric *dst) { - int i; +PGTYPESnumeric_copy(Numeric *src, Numeric *dst) +{ + int i; zero_var(dst); @@ -1383,9 +1396,8 @@ PGTYPESnumeric_copy(Numeric *src, Numeric *dst) { if (alloc_var(dst, src->ndigits) != 0) return -1; - for (i = 0; i < src->ndigits; i++) { + for (i = 0; i < src->ndigits; i++) dst->digits[i] = src->digits[i]; - } return 0; } @@ -1393,12 +1405,12 @@ PGTYPESnumeric_copy(Numeric *src, Numeric *dst) { int PGTYPESnumeric_from_double(double d, Numeric *dst) { - char buffer[100]; - Numeric *tmp; - + char buffer[100]; + Numeric *tmp; + if (sprintf(buffer, "%f", d) == 0) return -1; - + if ((tmp = PGTYPESnumeric_from_asc(buffer, NULL)) == NULL) return -1; if (PGTYPESnumeric_copy(tmp, dst) != 0) @@ -1425,17 +1437,18 @@ numericvar_to_double_no_overflow(Numeric *var, double *dp) free(tmp); errno = PGTYPES_NUM_BAD_NUMERIC; return -1; - } + } *dp = val; free(tmp); return 0; } int -PGTYPESnumeric_to_double(Numeric* nv, double* dp) { - double tmp; - int i; - +PGTYPESnumeric_to_double(Numeric *nv, double *dp) +{ + double tmp; + int i; + if ((i = numericvar_to_double_no_overflow(nv, &tmp)) != 0) return -1; *dp = tmp; @@ -1443,72 +1456,79 @@ PGTYPESnumeric_to_double(Numeric* nv, double* dp) { } int -PGTYPESnumeric_to_int(Numeric* nv, int* ip) { - long l; - int i; - +PGTYPESnumeric_to_int(Numeric *nv, int *ip) +{ + long l; + int i; + if ((i = PGTYPESnumeric_to_long(nv, &l)) != 0) return i; - if (l < -INT_MAX || l > INT_MAX) { + if (l < -INT_MAX || l > INT_MAX) + { errno = PGTYPES_NUM_OVERFLOW; return -1; - } + } *ip = (int) l; return 0; } int -PGTYPESnumeric_to_long(Numeric* nv, long* lp) { - int i; - long l = 0; +PGTYPESnumeric_to_long(Numeric *nv, long *lp) +{ + int i; + long l = 0; - for (i = 1; i < nv->weight + 2; i++) { + for (i = 1; i < nv->weight + 2; i++) + { l *= 10; l += nv->buf[i]; } - if (nv->buf[i] >= 5) { + if (nv->buf[i] >= 5) + { /* round up */ l++; } - if (l > LONG_MAX || l < 0) { + if (l > LONG_MAX || l < 0) + { errno = PGTYPES_NUM_OVERFLOW; return -1; } - - if (nv->sign == NUMERIC_NEG) { + + if (nv->sign == NUMERIC_NEG) l *= -1; - } *lp = l; return 0; } int -PGTYPESnumeric_to_decimal(Numeric *src, Decimal *dst) { - int i; +PGTYPESnumeric_to_decimal(Numeric *src, Decimal * dst) +{ + int i; - if (src->ndigits > DECSIZE) { + if (src->ndigits > DECSIZE) + { errno = PGTYPES_NUM_OVERFLOW; return -1; } - + dst->weight = src->weight; dst->rscale = src->rscale; dst->dscale = src->dscale; dst->sign = src->sign; dst->ndigits = src->ndigits; - for (i = 0; i < src->ndigits; i++) { + for (i = 0; i < src->ndigits; i++) dst->digits[i] = src->digits[i]; - } return 0; } int -PGTYPESnumeric_from_decimal(Decimal *src, Numeric *dst) { - int i; +PGTYPESnumeric_from_decimal(Decimal * src, Numeric *dst) +{ + int i; zero_var(dst); @@ -1520,9 +1540,8 @@ PGTYPESnumeric_from_decimal(Decimal *src, Numeric *dst) { if (alloc_var(dst, src->ndigits) != 0) return -1; - for (i = 0; i < src->ndigits; i++) { + for (i = 0; i < src->ndigits; i++) dst->digits[i] = src->digits[i]; - } return 0; } diff --git a/src/interfaces/ecpg/pgtypeslib/timestamp.c b/src/interfaces/ecpg/pgtypeslib/timestamp.c index 4d1a13d9e5..8a96d696b4 100644 --- a/src/interfaces/ecpg/pgtypeslib/timestamp.c +++ b/src/interfaces/ecpg/pgtypeslib/timestamp.c @@ -13,8 +13,8 @@ #include "pgtypes_date.h" #include "datetime.h" -int PGTYPEStimestamp_defmt_scan(char**, char*, Timestamp *, int*, int*, int*, - int*, int*, int*, int*); +int PGTYPEStimestamp_defmt_scan(char **, char *, Timestamp *, int *, int *, int *, + int *, int *, int *, int *); #ifdef HAVE_INT64_TIMESTAMP static int64 @@ -89,7 +89,8 @@ static Timestamp SetEpochTimestamp(void) { Timestamp dt; - struct tm tt, *tm = &tt; + struct tm tt, + *tm = &tt; GetEpochTime(tm); tm2timestamp(tm, 0, NULL, &dt); @@ -101,6 +102,7 @@ dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec) { #ifdef HAVE_INT64_TIMESTAMP int64 time; + #else double time; #endif @@ -142,8 +144,8 @@ static int timestamp2tm(Timestamp dt, int *tzp, struct tm * tm, fsec_t *fsec, char **tzn) { #ifdef HAVE_INT64_TIMESTAMP - int date, - date0; + int date, + date0; int64 time; #else @@ -255,8 +257,8 @@ timestamp2tm(Timestamp dt, int *tzp, struct tm * tm, fsec_t *fsec, char **tzn) } /* timestamp2tm() */ /* EncodeSpecialTimestamp() - * * Convert reserved timestamp data type to string. - * */ + * * Convert reserved timestamp data type to string. + * */ static int EncodeSpecialTimestamp(Timestamp dt, char *str) { @@ -274,21 +276,24 @@ Timestamp PGTYPEStimestamp_from_asc(char *str, char **endptr) { Timestamp result; + #ifdef HAVE_INT64_TIMESTAMP int64 noresult = 0; + #else double noresult = 0.0; #endif fsec_t fsec; - struct tm tt, *tm = &tt; - int tz; - int dtype; - int nf; - char *field[MAXDATEFIELDS]; - int ftype[MAXDATEFIELDS]; + struct tm tt, + *tm = &tt; + int tz; + int dtype; + int nf; + char *field[MAXDATEFIELDS]; + int ftype[MAXDATEFIELDS]; char lowstr[MAXDATELEN + MAXDATEFIELDS]; - char *realptr; - char **ptr = (endptr != NULL) ? endptr : &realptr; + char *realptr; + char **ptr = (endptr != NULL) ? endptr : &realptr; errno = 0; if (strlen(str) >= sizeof(lowstr)) @@ -298,12 +303,12 @@ PGTYPEStimestamp_from_asc(char *str, char **endptr) } if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf, ptr) != 0) - || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz, 0) != 0)) + || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz, 0) != 0)) { - errno = PGTYPES_TS_BAD_TIMESTAMP; - return (noresult); - } - + errno = PGTYPES_TS_BAD_TIMESTAMP; + return (noresult); + } + switch (dtype) { case DTK_DATE: @@ -343,11 +348,13 @@ PGTYPEStimestamp_from_asc(char *str, char **endptr) char * PGTYPEStimestamp_to_asc(Timestamp tstamp) { - struct tm tt, *tm = &tt; + struct tm tt, + *tm = &tt; char buf[MAXDATELEN + 1]; - char *tzn = NULL; + char *tzn = NULL; fsec_t fsec; - int DateStyle = 1; /* this defaults to ISO_DATES, shall we make it an option? */ + int DateStyle = 1; /* this defaults to ISO_DATES, shall we + * make it an option? */ if (TIMESTAMP_NOT_FINITE(tstamp)) EncodeSpecialTimestamp(tstamp, buf); @@ -362,31 +369,34 @@ PGTYPEStimestamp_to_asc(Timestamp tstamp) } void -PGTYPEStimestamp_current (Timestamp *ts) +PGTYPEStimestamp_current(Timestamp *ts) { struct tm tm; - + GetCurrentDateTime(&tm); tm2timestamp(&tm, 0, NULL, ts); return; } static int -dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, - char* output, int *pstr_len, char *fmtstr) +dttofmtasc_replace(Timestamp *ts, Date dDate, int dow, struct tm * tm, + char *output, int *pstr_len, char *fmtstr) { union un_fmt_comb replace_val; - int replace_type; - int i; - char* p = fmtstr; - char* q = output; + int replace_type; + int i; + char *p = fmtstr; + char *q = output; - while (*p) { - if (*p == '%') { + while (*p) + { + if (*p == '%') + { p++; /* fix compiler warning */ replace_type = PGTYPES_TYPE_NOTHING; - switch (*p) { + switch (*p) + { case 'a': replace_val.str_val = pgtypes_date_weekdays_short[dow]; replace_type = PGTYPES_TYPE_STRING_CONSTANT; @@ -416,19 +426,21 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, replace_type = PGTYPES_TYPE_UINT_2_LZ; break; case 'D': - /* ts, dDate, dow, tm is - * information about the timestamp + + /* + * ts, dDate, dow, tm is information about the + * timestamp * - * q is the start of the current - * output buffer + * q is the start of the current output buffer * - * pstr_len is a pointer to the - * remaining size of output, i.e. - * the size of q */ + * pstr_len is a pointer to the remaining size of output, + * i.e. the size of q + */ i = dttofmtasc_replace(ts, dDate, dow, tm, - q, pstr_len, - "%m/%d/%y"); - if (i) { return i; } + q, pstr_len, + "%m/%d/%y"); + if (i) + return i; break; case 'e': replace_val.uint_val = tm->tm_mday; @@ -436,19 +448,23 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, break; case 'E': { - char tmp[4] = "%Ex"; + char tmp[4] = "%Ex"; + p++; - if (*p == '\0') { + if (*p == '\0') return -1; - } tmp[2] = *p; /* XXX: fall back to strftime */ - /* strftime's month is 0 - * based, ours is 1 based */ + + /* + * strftime's month is 0 based, ours is 1 based + */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, tmp, tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -460,8 +476,10 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, /* XXX: fall back to strftime */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, "%G", tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -471,12 +489,15 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, case 'g': /* XXX: fall back to strftime */ { - char *fmt = "%g"; /* Keep compiler quiet about 2-digit year */ - + char *fmt = "%g"; /* Keep compiler quiet + * about 2-digit year */ + tm->tm_mon -= 1; i = strftime(q, *pstr_len, fmt, tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -517,32 +538,32 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, replace_type = PGTYPES_TYPE_CHAR; break; case 'p': - if (tm->tm_hour < 12) { + if (tm->tm_hour < 12) replace_val.str_val = "AM"; - } else { + else replace_val.str_val = "PM"; - } replace_type = PGTYPES_TYPE_STRING_CONSTANT; break; case 'P': - if (tm->tm_hour < 12) { + if (tm->tm_hour < 12) replace_val.str_val = "am"; - } else { + else replace_val.str_val = "pm"; - } replace_type = PGTYPES_TYPE_STRING_CONSTANT; break; case 'r': i = dttofmtasc_replace(ts, dDate, dow, tm, - q, pstr_len, - "%I:%M:%S %p"); - if (i) { return i; } + q, pstr_len, + "%I:%M:%S %p"); + if (i) + return i; break; case 'R': i = dttofmtasc_replace(ts, dDate, dow, tm, - q, pstr_len, - "%H:%M"); - if (i) { return i; } + q, pstr_len, + "%H:%M"); + if (i) + return i; break; case 's': #ifdef HAVE_INT64_TIMESTAMP @@ -563,12 +584,14 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, break; case 'T': i = dttofmtasc_replace(ts, dDate, dow, tm, - q, pstr_len, - "%H:%M:%S"); - if (i) { return i; } + q, pstr_len, + "%H:%M:%S"); + if (i) + return i; break; case 'u': - if (dow == 0) { dow = 7; } + if (dow == 0) + dow = 7; replace_val.uint_val = dow; replace_type = PGTYPES_TYPE_UINT; break; @@ -576,8 +599,10 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, /* XXX: fall back to strftime */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, "%U", tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -587,8 +612,10 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, case 'V': /* XXX: fall back to strftime */ i = strftime(q, *pstr_len, "%V", tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -602,8 +629,10 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, /* XXX: fall back to strftime */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, "%U", tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -613,12 +642,15 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, case 'x': /* XXX: fall back to strftime */ { - char *fmt = "%x"; /* Keep compiler quiet about 2-digit year */ + char *fmt = "%x"; /* Keep compiler quiet + * about 2-digit year */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, fmt, tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -630,8 +662,10 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, /* XXX: fall back to strftime */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, "%X", tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -650,8 +684,10 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, /* XXX: fall back to strftime */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, "%z", tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -662,8 +698,10 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, /* XXX: fall back to strftime */ tm->tm_mon -= 1; i = strftime(q, *pstr_len, "%Z", tm); - if (i == 0) { return -1; } - while (*q) { + if (i == 0) + return -1; + while (*q) + { q++; (*pstr_len)--; } @@ -676,41 +714,53 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, break; case '\0': /* fmtstr: blabla%' */ - /* this is not compliant to the - * specification */ + + /* + * this is not compliant to the specification + */ return -1; default: - /* if we don't know the pattern, we - * just copy it */ - if (*pstr_len > 1) { + + /* + * if we don't know the pattern, we just copy it + */ + if (*pstr_len > 1) + { *q = '%'; - q++; (*pstr_len)--; - if (*pstr_len > 1) { + q++; + (*pstr_len)--; + if (*pstr_len > 1) + { *q = *p; - q++; (*pstr_len)--; - } else { + q++; + (*pstr_len)--; + } + else + { *q = '\0'; return -1; } *q = '\0'; - } else { - return -1; } + else + return -1; break; } i = pgtypes_fmt_replace(replace_val, replace_type, &q, pstr_len); - if (i) { + if (i) return i; - } - } else { - if (*pstr_len > 1) { + } + else + { + if (*pstr_len > 1) + { *q = *p; (*pstr_len)--; q++; *q = '\0'; - } else { - return -1; } + else + return -1; } p++; } @@ -719,12 +769,12 @@ dttofmtasc_replace (Timestamp *ts, Date dDate, int dow, struct tm* tm, int -PGTYPEStimestamp_fmt_asc (Timestamp *ts, char *output, int str_len, char *fmtstr) +PGTYPEStimestamp_fmt_asc(Timestamp *ts, char *output, int str_len, char *fmtstr) { - struct tm tm; - fsec_t fsec; - Date dDate; - int dow; + struct tm tm; + fsec_t fsec; + Date dDate; + int dow; dDate = PGTYPESdate_from_timestamp(*ts); dow = PGTYPESdate_dayofweek(dDate); @@ -734,12 +784,10 @@ PGTYPEStimestamp_fmt_asc (Timestamp *ts, char *output, int str_len, char *fmtstr } int -PGTYPEStimestamp_sub (Timestamp *ts1, Timestamp *ts2, Interval *iv) +PGTYPEStimestamp_sub(Timestamp *ts1, Timestamp *ts2, Interval *iv) { if (TIMESTAMP_NOT_FINITE(*ts1) || TIMESTAMP_NOT_FINITE(*ts2)) - { return PGTYPES_TS_ERR_EINFTIME; - } else #ifdef HAVE_INT64_TIMESTAMP iv->time = (ts1 - ts2); @@ -752,28 +800,40 @@ PGTYPEStimestamp_sub (Timestamp *ts1, Timestamp *ts2, Interval *iv) return 0; } -int PGTYPEStimestamp_defmt_asc(char* str, char *fmt, Timestamp *d) { - int year, month, day; - int hour, minute, second; - int tz; +int +PGTYPEStimestamp_defmt_asc(char *str, char *fmt, Timestamp *d) +{ + int year, + month, + day; + int hour, + minute, + second; + int tz; - int i; - char* mstr; - char* mfmt; + int i; + char *mstr; + char *mfmt; - if (!fmt) { + if (!fmt) fmt = "%Y-%m-%d %H:%M:%S"; - } - if (!fmt[0]) { + if (!fmt[0]) return 1; - } mstr = pgtypes_strdup(str); mfmt = pgtypes_strdup(fmt); - /* initialize with impossible values so that we can see if the - * fields where specified at all */ + + /* + * initialize with impossible values so that we can see if the fields + * where specified at all + */ /* XXX ambiguity with 1 BC for year? */ - year = -1; month = -1; day = -1; hour = 0; minute = -1; second = -1; + year = -1; + month = -1; + day = -1; + hour = 0; + minute = -1; + second = -1; tz = 0; i = PGTYPEStimestamp_defmt_scan(&mstr, mfmt, d, &year, &month, &day, &hour, &minute, &second, &tz); @@ -781,4 +841,3 @@ int PGTYPEStimestamp_defmt_asc(char* str, char *fmt, Timestamp *d) { free(mfmt); return i; } - diff --git a/src/interfaces/ecpg/preproc/c_keywords.c b/src/interfaces/ecpg/preproc/c_keywords.c index 7b19227375..fa2ee17f61 100644 --- a/src/interfaces/ecpg/preproc/c_keywords.c +++ b/src/interfaces/ecpg/preproc/c_keywords.c @@ -28,24 +28,24 @@ static ScanKeyword ScanKeywords[] = { {"enum", SQL_ENUM}, {"extern", S_EXTERN}, {"float", FLOAT_P}, - {"hour", HOUR_P}, + {"hour", HOUR_P}, {"int", INT_P}, {"long", SQL_LONG}, {"minute", MINUTE_P}, - {"month", MONTH_P}, + {"month", MONTH_P}, {"register", S_REGISTER}, - {"second", SECOND_P}, + {"second", SECOND_P}, {"short", SQL_SHORT}, {"signed", SQL_SIGNED}, {"static", S_STATIC}, {"struct", SQL_STRUCT}, - {"to", TO}, + {"to", TO}, {"typedef", S_TYPEDEF}, {"union", UNION}, {"unsigned", SQL_UNSIGNED}, {"varchar", VARCHAR}, {"volatile", S_VOLATILE}, - {"year", YEAR_P}, + {"year", YEAR_P}, }; ScanKeyword * diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c index fb0f6dcb85..7cf8eeebb2 100644 --- a/src/interfaces/ecpg/preproc/ecpg.c +++ b/src/interfaces/ecpg/preproc/ecpg.c @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/preproc/ecpg.c,v 1.76 2003/08/01 08:21:04 meskes Exp $ */ +/* $Header: /cvsroot/pgsql/src/interfaces/ecpg/preproc/ecpg.c,v 1.77 2003/08/04 00:43:33 momjian Exp $ */ /* New main for ecpg, the PostgreSQL embedded SQL precompiler. */ /* (C) Michael Meskes Feb 5th, 1998 */ @@ -23,7 +23,7 @@ int ret_value = 0, system_includes = false, force_indicator = true; -enum COMPAT_MODE compat = ECPG_COMPAT_PGSQL; +enum COMPAT_MODE compat = ECPG_COMPAT_PGSQL; struct _include_path *include_paths = NULL; struct cursor *cur = NULL; @@ -49,7 +49,7 @@ help(const char *progname) " \"INFORMIX\"\n" " \"INFORMIX_SE\"\n"); printf(" -r