diff options
author | Bruce Momjian <bruce@momjian.us> | 2001-10-25 05:50:21 +0000 |
---|---|---|
committer | Bruce Momjian <bruce@momjian.us> | 2001-10-25 05:50:21 +0000 |
commit | b81844b1738c584d92330a5ccd0fbd8b603d2886 (patch) | |
tree | 4fae0d4cd26048177fc5cd1a2dd91abc99ba0f99 /src/backend | |
parent | 59da2105d8e6d95345b3b942a2e2aba8cead4838 (diff) | |
download | postgresql-b81844b1738c584d92330a5ccd0fbd8b603d2886.tar.gz |
pgindent run on all C files. Java run to follow. initdb/regression
tests pass.
Diffstat (limited to 'src/backend')
316 files changed, 7786 insertions, 7564 deletions
diff --git a/src/backend/access/common/heaptuple.c b/src/backend/access/common/heaptuple.c index ef6cedd92d..5b005b3163 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.73 2001/08/23 23:06:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/common/heaptuple.c,v 1.74 2001/10/25 05:49:20 momjian Exp $ * * NOTES * The old interface functions have been converted to macros @@ -241,7 +241,6 @@ nocachegetattr(HeapTuple tuple, } else { - /* * there's a null somewhere in the tuple */ @@ -347,7 +346,6 @@ nocachegetattr(HeapTuple tuple, (HeapTupleNoNulls(tuple) || !att_isnull(j, bp)) && (HeapTupleAllFixed(tuple) || att[j]->attlen > 0)); j++) { - /* * Fix me when going to a machine with more than a four-byte * word! @@ -546,7 +544,6 @@ heap_deformtuple(HeapTuple tuple, nulls[i] = ' '; } } - #endif /* ---------------- @@ -739,7 +736,7 @@ heap_freetuple(HeapTuple htup) * * This routine forms a HeapTuple by copying the given structure (tuple * data) and adding a generic header. Note that the tuple data is - * presumed to contain no null fields. It is typically only useful + * presumed to contain no null fields. It is typically only useful * for null-free system tables. * ---------------- */ @@ -771,7 +768,7 @@ heap_addheader(int natts, /* max domain index */ td->t_hoff = hoff; td->t_natts = natts; - td->t_infomask = HEAP_XMAX_INVALID; /* XXX sufficient? */ + td->t_infomask = HEAP_XMAX_INVALID; /* XXX sufficient? */ memcpy((char *) td + hoff, structure, structlen); diff --git a/src/backend/access/common/indextuple.c b/src/backend/access/common/indextuple.c index 5c165e2c77..ad6e7cc4e5 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.54 2001/03/22 06:16:06 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/common/indextuple.c,v 1.55 2001/10/25 05:49:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -49,7 +49,6 @@ index_formtuple(TupleDesc tupleDescriptor, #ifdef TOAST_INDEX_HACK Datum untoasted_value[INDEX_MAX_KEYS]; bool untoasted_free[INDEX_MAX_KEYS]; - #endif if (numberOfAttributes > INDEX_MAX_KEYS) @@ -338,7 +337,6 @@ nocache_index_getattr(IndexTuple tup, for (; j <= attnum; j++) { - /* * Fix me when going to a machine with more than a four-byte * word! diff --git a/src/backend/access/common/printtup.c b/src/backend/access/common/printtup.c index da95edfc1f..ea10330bf8 100644 --- a/src/backend/access/common/printtup.c +++ b/src/backend/access/common/printtup.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/common/printtup.c,v 1.59 2001/03/22 06:16:06 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/common/printtup.c,v 1.60 2001/10/25 05:49:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -197,7 +197,6 @@ printtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) continue; if (OidIsValid(thisState->typoutput)) { - /* * If we have a toasted datum, forcibly detoast it here to * avoid memory leakage inside the type's output routine. @@ -306,7 +305,6 @@ debugtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) if (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. @@ -401,7 +399,6 @@ printtup_internal(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self) /* send # of bytes, and opaque data */ if (thisState->typisvarlena) { - /* * If we have a toasted datum, must detoast before sending. */ diff --git a/src/backend/access/common/tupdesc.c b/src/backend/access/common/tupdesc.c index 37e895479e..4b9d53df34 100644 --- a/src/backend/access/common/tupdesc.c +++ b/src/backend/access/common/tupdesc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/common/tupdesc.c,v 1.75 2001/06/25 21:11:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/common/tupdesc.c,v 1.76 2001/10/25 05:49:20 momjian Exp $ * * NOTES * some of the executor utility code such as "ExecTypeFromTL" should be @@ -238,9 +238,9 @@ equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2) Form_pg_attribute attr2 = tupdesc2->attrs[i]; /* - * We do not need to check every single field here: we can disregard - * attrelid, attnum (it was used to place the row in the attrs array) - * and everything derived from the column datatype. + * We do not need to check every single field here: we can + * disregard attrelid, attnum (it was used to place the row in the + * attrs array) and everything derived from the column datatype. */ if (strcmp(NameStr(attr1->attname), NameStr(attr2->attname)) != 0) return false; @@ -399,7 +399,6 @@ TupleDescInitEntry(TupleDesc desc, 0, 0, 0); if (!HeapTupleIsValid(tuple)) { - /* * here type info does not exist yet so we just fill the attribute * with dummy information and return false. @@ -585,7 +584,6 @@ BuildDescForRelation(List *schema, char *relname) typenameTypeId(typename), atttypmod, attdim, attisset)) { - /* * if TupleDescInitEntry() fails, it means there is no type in * the system catalogs. So now we check if the type name diff --git a/src/backend/access/gist/gist.c b/src/backend/access/gist/gist.c index 4a702fe317..0c4e698f01 100644 --- a/src/backend/access/gist/gist.c +++ b/src/backend/access/gist/gist.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/gist/gist.c,v 1.84 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/gist/gist.c,v 1.85 2001/10/25 05:49:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -36,26 +36,26 @@ /* group flags ( in gistSplit ) */ #define LEFT_ADDED 0x01 -#define RIGHT_ADDED 0x02 +#define RIGHT_ADDED 0x02 #define BOTH_ADDED ( LEFT_ADDED | RIGHT_ADDED ) /* * This defines only for shorter code, used in gistgetadjusted * and gistadjsubkey only */ -#define FILLITEM(evp, isnullkey, okey, okeyb, rkey, rkeyb) do { \ - if ( isnullkey ) { \ - gistentryinit((evp), rkey, r, (Page) NULL , \ - (OffsetNumber) 0, rkeyb, FALSE); \ - } else { \ - gistentryinit((evp), okey, r, (Page) NULL, \ - (OffsetNumber) 0, okeyb, FALSE); \ - } \ +#define FILLITEM(evp, isnullkey, okey, okeyb, rkey, rkeyb) do { \ + if ( isnullkey ) { \ + gistentryinit((evp), rkey, r, (Page) NULL , \ + (OffsetNumber) 0, rkeyb, FALSE); \ + } else { \ + gistentryinit((evp), okey, r, (Page) NULL, \ + (OffsetNumber) 0, okeyb, FALSE); \ + } \ } while(0) #define FILLEV(isnull1, key1, key1b, isnull2, key2, key2b) do { \ - FILLITEM(*ev0p, isnull1, key1, key1b, key2, key2b); \ - FILLITEM(*ev1p, isnull2, key2, key2b, key1, key1b); \ + FILLITEM(*ev0p, isnull1, key1, key1b, key2, key2b); \ + FILLITEM(*ev1p, isnull2, key2, key2b, key1, key1b); \ } while(0); /* Working state for gistbuild and its callback */ @@ -69,11 +69,11 @@ typedef struct /* non-export function prototypes */ static void gistbuildCallback(Relation index, - HeapTuple htup, - Datum *attdata, - char *nulls, - bool tupleIsAlive, - void *state); + HeapTuple htup, + Datum *attdata, + char *nulls, + bool tupleIsAlive, + void *state); static void gistdoinsert(Relation r, IndexTuple itup, InsertIndexResult *res, @@ -103,14 +103,14 @@ static IndexTuple gistgetadjusted(Relation r, IndexTuple oldtup, IndexTuple addtup, GISTSTATE *giststate); -static int gistfindgroup( GISTSTATE *giststate, - GISTENTRY *valvec, GIST_SPLITVEC * spl ); +static int gistfindgroup(GISTSTATE *giststate, + GISTENTRY *valvec, GIST_SPLITVEC *spl); static void gistadjsubkey(Relation r, - IndexTuple *itup, int *len, - GIST_SPLITVEC *v, - GISTSTATE *giststate); -static IndexTuple gistFormTuple( GISTSTATE *giststate, - Relation r, Datum attdata[], int datumsize[], bool isnull[] ); + IndexTuple *itup, int *len, + GIST_SPLITVEC *v, + GISTSTATE *giststate); +static IndexTuple gistFormTuple(GISTSTATE *giststate, + Relation r, Datum attdata[], int datumsize[], bool isnull[]); static IndexTuple *gistSplit(Relation r, Buffer buffer, IndexTuple *itup, @@ -124,6 +124,7 @@ static OffsetNumber gistchoose(Relation r, Page p, IndexTuple it, GISTSTATE *giststate); static void gistdelete(Relation r, ItemPointer tid); + #ifdef GIST_PAGEADDITEM static IndexTuple gist_tuple_replacekey(Relation r, GISTENTRY entry, IndexTuple t); @@ -132,14 +133,15 @@ static void gistcentryinit(GISTSTATE *giststate, int nkey, GISTENTRY *e, Datum k, Relation r, Page pg, OffsetNumber o, int b, bool l, bool isNull); -static void gistDeCompressAtt( GISTSTATE *giststate, Relation r, - IndexTuple tuple, Page p, OffsetNumber o, - GISTENTRY attdata[], bool decompvec[], bool isnull[] ); -static void gistFreeAtt( Relation r, GISTENTRY attdata[], bool decompvec[] ); -static void gistpenalty( GISTSTATE *giststate, int attno, +static void gistDeCompressAtt(GISTSTATE *giststate, Relation r, + IndexTuple tuple, Page p, OffsetNumber o, + GISTENTRY attdata[], bool decompvec[], bool isnull[]); +static void gistFreeAtt(Relation r, GISTENTRY attdata[], bool decompvec[]); +static void gistpenalty(GISTSTATE *giststate, int attno, GISTENTRY *key1, bool isNull1, - GISTENTRY *key2, bool isNull2, - float *penalty ); + GISTENTRY *key2, bool isNull2, + float *penalty); + #undef GISTDEBUG #ifdef GISTDEBUG @@ -182,7 +184,7 @@ gistbuild(PG_FUNCTION_ARGS) /* do the heap scan */ reltuples = IndexBuildHeapScan(heap, index, indexInfo, - gistbuildCallback, (void *) &buildstate); + gistbuildCallback, (void *) &buildstate); /* okay, all heap tuples are indexed */ @@ -208,7 +210,7 @@ gistbuild(PG_FUNCTION_ARGS) UpdateStats(irelid, buildstate.indtuples); } - freeGISTstate( &buildstate.giststate ); + freeGISTstate(&buildstate.giststate); #ifdef GISTDEBUG gist_dumptree(index, 0, GISTP_ROOT, 0); #endif @@ -227,28 +229,31 @@ gistbuildCallback(Relation index, bool tupleIsAlive, void *state) { - GISTBuildState *buildstate = (GISTBuildState *) state; + GISTBuildState *buildstate = (GISTBuildState *) state; IndexTuple itup; bool compvec[INDEX_MAX_KEYS]; GISTENTRY tmpcentry; int i; - /* GiST cannot index tuples with leading NULLs */ - if ( nulls[0] == 'n' ) - return; + /* GiST cannot index tuples with leading NULLs */ + if (nulls[0] == 'n') + return; /* immediately compress keys to normalize */ for (i = 0; i < buildstate->numindexattrs; i++) { - if ( nulls[i]=='n' ) { + if (nulls[i] == 'n') + { attdata[i] = (Datum) 0; compvec[i] = FALSE; - } else { + } + else + { gistcentryinit(&buildstate->giststate, i, &tmpcentry, attdata[i], - (Relation) NULL, (Page) NULL, (OffsetNumber) 0, - -1 /* size is currently bogus */ , TRUE, FALSE); + (Relation) NULL, (Page) NULL, (OffsetNumber) 0, + -1 /* size is currently bogus */ , TRUE, FALSE); if (attdata[i] != tmpcentry.key && - !( isAttByVal(&buildstate->giststate, i))) + !(isAttByVal(&buildstate->giststate, i))) compvec[i] = TRUE; else compvec[i] = FALSE; @@ -262,10 +267,10 @@ gistbuildCallback(Relation index, /* * Since we already have the index relation locked, we call - * gistdoinsert directly. Normal access method calls dispatch - * through gistinsert, which locks the relation for write. This - * is the right thing to do if you're inserting single tups, but - * not when you're initializing the whole index at once. + * gistdoinsert directly. Normal access method calls dispatch through + * gistinsert, which locks the relation for write. This is the right + * thing to do if you're inserting single tups, but not when you're + * initializing the whole index at once. */ gistdoinsert(index, itup, NULL, &buildstate->giststate); @@ -291,6 +296,7 @@ gistinsert(PG_FUNCTION_ARGS) Datum *datum = (Datum *) PG_GETARG_POINTER(1); char *nulls = (char *) PG_GETARG_POINTER(2); ItemPointer ht_ctid = (ItemPointer) PG_GETARG_POINTER(3); + #ifdef NOT_USED Relation heapRel = (Relation) PG_GETARG_POINTER(4); #endif @@ -303,29 +309,33 @@ gistinsert(PG_FUNCTION_ARGS) /* * Since GIST is not marked "amconcurrent" in pg_am, caller should - * have acquired exclusive lock on index relation. We need no locking + * have acquired exclusive lock on index relation. We need no locking * here. */ - /* GiST cannot index tuples with leading NULLs */ - if ( nulls[0] == 'n' ) { + /* GiST cannot index tuples with leading NULLs */ + if (nulls[0] == 'n') + { res = NULL; PG_RETURN_POINTER(res); - } + } initGISTstate(&giststate, r); /* immediately compress keys to normalize */ for (i = 0; i < r->rd_att->natts; i++) { - if ( nulls[i]=='n' ) { + if (nulls[i] == 'n') + { datum[i] = (Datum) 0; compvec[i] = FALSE; - } else { + } + else + { gistcentryinit(&giststate, i, &tmpentry, datum[i], - (Relation) NULL, (Page) NULL, (OffsetNumber) 0, - -1 /* size is currently bogus */ , TRUE, FALSE ); - if (datum[i] != tmpentry.key && !( isAttByVal( &giststate, i))) + (Relation) NULL, (Page) NULL, (OffsetNumber) 0, + -1 /* size is currently bogus */ , TRUE, FALSE); + if (datum[i] != tmpentry.key && !(isAttByVal(&giststate, i))) compvec[i] = TRUE; else compvec[i] = FALSE; @@ -342,7 +352,7 @@ gistinsert(PG_FUNCTION_ARGS) if (compvec[i] == TRUE) pfree(DatumGetPointer(datum[i])); pfree(itup); - freeGISTstate( &giststate ); + freeGISTstate(&giststate); PG_RETURN_POINTER(res); } @@ -376,12 +386,12 @@ gistPageAddItem(GISTSTATE *giststate, * offset for insertion */ datum = index_getattr(itup, 1, r->rd_att, &IsNull); - gistdentryinit(giststate, 0,dentry, datum, + gistdentryinit(giststate, 0, dentry, datum, (Relation) 0, (Page) 0, (OffsetNumber) InvalidOffsetNumber, - ATTSIZE( datum, r, 1, IsNull ), + ATTSIZE(datum, r, 1, IsNull), FALSE, IsNull); - gistcentryinit(giststate, 0,&tmpcentry, dentry->key, r, page, + gistcentryinit(giststate, 0, &tmpcentry, dentry->key, r, page, offsetNumber, dentry->bytes, FALSE); *newtup = gist_tuple_replacekey(r, tmpcentry, itup); retval = PageAddItem(page, (Item) *newtup, IndexTupleSize(*newtup), @@ -392,7 +402,7 @@ gistPageAddItem(GISTSTATE *giststate, /* be tidy */ if (DatumGetPointer(tmpcentry.key) != NULL && tmpcentry.key != dentry->key && - tmpcentry.key != datum ) + tmpcentry.key != datum) pfree(DatumGetPointer(tmpcentry.key)); return (retval); } @@ -471,6 +481,7 @@ gistlayerinsert(Relation r, BlockNumber blkno, if (!(ret & SPLITED)) { IndexTuple newtup = gistgetadjusted(r, oldtup, (*itup)[0], giststate); + if (!newtup) { /* not need to update key */ @@ -492,8 +503,10 @@ gistlayerinsert(Relation r, BlockNumber blkno, if (gistnospace(page, (*itup), *len)) { /* no space for insertion */ - IndexTuple *itvec, *newitup; - int tlen,oldlen; + IndexTuple *itvec, + *newitup; + int tlen, + oldlen; ret |= SPLITED; itvec = gistreadbuffer(r, buffer, &tlen); @@ -503,9 +516,9 @@ gistlayerinsert(Relation r, BlockNumber blkno, (opaque->flags & F_LEAF) ? res : NULL); /* res only for * inserting in leaf */ ReleaseBuffer(buffer); - do - pfree( (*itup)[ oldlen-1 ] ); - while ( (--oldlen) > 0 ); + do + pfree((*itup)[oldlen - 1]); + while ((--oldlen) > 0); pfree((*itup)); pfree(itvec); *itup = newitup; @@ -539,7 +552,8 @@ gistlayerinsert(Relation r, BlockNumber blkno, * parent */ IndexTuple newtup = gistunion(r, (*itup), *len, giststate); - ItemPointerSet(&(newtup->t_tid), blkno, 1); + + ItemPointerSet(&(newtup->t_tid), blkno, 1); for (i = 0; i < *len; i++) pfree((*itup)[i]); @@ -560,10 +574,11 @@ gistwritebuffer(Relation r, Page page, IndexTuple *itup, { OffsetNumber l = InvalidOffsetNumber; int i; + #ifdef GIST_PAGEADDITEM GISTENTRY tmpdentry; IndexTuple newtup; - bool IsNull; + bool IsNull; #endif for (i = 0; i < len; i++) { @@ -573,13 +588,13 @@ gistwritebuffer(Relation r, Page page, IndexTuple *itup, off, LP_USED, &tmpdentry, &newtup); off = OffsetNumberNext(off); if (DatumGetPointer(tmpdentry.key) != NULL && - tmpdentry.key != index_getattr(itup[i], 1, r->rd_att, &IsNull)) + tmpdentry.key != index_getattr(itup[i], 1, r->rd_att, &IsNull)) pfree(DatumGetPointer(tmpdentry.key)); if (itup[i] != newtup) pfree(newtup); #else l = PageAddItem(page, (Item) itup[i], IndexTupleSize(itup[i]), - off, LP_USED); + off, LP_USED); if (l == InvalidOffsetNumber) elog(ERROR, "gist: failed to add index item to %s", RelationGetRelationName(r)); @@ -618,7 +633,7 @@ gistreadbuffer(Relation r, Buffer buffer, int *len /* out */ ) *len = maxoff; itvec = palloc(sizeof(IndexTuple) * maxoff); for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) - itvec[i-1] = (IndexTuple) PageGetItem(p, PageGetItemId(p, i)); + itvec[i - 1] = (IndexTuple) PageGetItem(p, PageGetItemId(p, i)); return itvec; } @@ -639,74 +654,85 @@ gistjoinvector(IndexTuple *itvec, int *len, IndexTuple *additvec, int addlen) * return union of itup vector */ static IndexTuple -gistunion(Relation r, IndexTuple *itvec, int len, GISTSTATE *giststate) { +gistunion(Relation r, IndexTuple *itvec, int len, GISTSTATE *giststate) +{ Datum attr[INDEX_MAX_KEYS]; - bool whatfree[INDEX_MAX_KEYS]; + bool whatfree[INDEX_MAX_KEYS]; char isnull[INDEX_MAX_KEYS]; bytea *evec; Datum datum; int datumsize, - i,j; + i, + j; GISTENTRY centry[INDEX_MAX_KEYS]; - bool *needfree; - IndexTuple newtup; - bool IsNull; - int reallen; + bool *needfree; + IndexTuple newtup; + bool IsNull; + int reallen; - needfree = (bool *) palloc((( len==1 ) ? 2 : len ) * sizeof(bool)); - evec = (bytea *) palloc((( len==1 ) ? 2 : len ) * sizeof(GISTENTRY) + VARHDRSZ); + needfree = (bool *) palloc(((len == 1) ? 2 : len) * sizeof(bool)); + evec = (bytea *) palloc(((len == 1) ? 2 : len) * sizeof(GISTENTRY) + VARHDRSZ); - for (j = 0; j < r->rd_att->natts; j++) { - reallen=0; - for (i = 0; i < len; i++) { - datum = index_getattr(itvec[i], j+1, giststate->tupdesc, &IsNull); - if ( IsNull ) continue; + for (j = 0; j < r->rd_att->natts; j++) + { + reallen = 0; + for (i = 0; i < len; i++) + { + datum = index_getattr(itvec[i], j + 1, giststate->tupdesc, &IsNull); + if (IsNull) + continue; gistdentryinit(giststate, j, &((GISTENTRY *) VARDATA(evec))[reallen], datum, - (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, - ATTSIZE( datum, giststate->tupdesc, j+1, IsNull ), FALSE, IsNull); - if ( (!isAttByVal(giststate,j)) && - ((GISTENTRY *) VARDATA(evec))[reallen].key != datum ) + (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, + ATTSIZE(datum, giststate->tupdesc, j + 1, IsNull), FALSE, IsNull); + if ((!isAttByVal(giststate, j)) && + ((GISTENTRY *) VARDATA(evec))[reallen].key != datum) needfree[reallen] = TRUE; else needfree[reallen] = FALSE; reallen++; } - if ( reallen == 0 ) { + if (reallen == 0) + { attr[j] = (Datum) 0; isnull[j] = 'n'; whatfree[j] = FALSE; - } else { - if ( reallen == 1 ) { + } + else + { + if (reallen == 1) + { VARATT_SIZEP(evec) = 2 * sizeof(GISTENTRY) + VARHDRSZ; - gistentryinit(((GISTENTRY *) VARDATA(evec))[1], - ((GISTENTRY *) VARDATA(evec))[0].key, r, (Page) NULL, - (OffsetNumber) 0, ((GISTENTRY *) VARDATA(evec))[0].bytes, FALSE); + gistentryinit(((GISTENTRY *) VARDATA(evec))[1], + ((GISTENTRY *) VARDATA(evec))[0].key, r, (Page) NULL, + (OffsetNumber) 0, ((GISTENTRY *) VARDATA(evec))[0].bytes, FALSE); - } else { - VARATT_SIZEP(evec) = reallen * sizeof(GISTENTRY) + VARHDRSZ; } + else + VARATT_SIZEP(evec) = reallen * sizeof(GISTENTRY) + VARHDRSZ; datum = FunctionCall2(&giststate->unionFn[j], - PointerGetDatum(evec), - PointerGetDatum(&datumsize)); - + PointerGetDatum(evec), + PointerGetDatum(&datumsize)); + for (i = 0; i < reallen; i++) - if ( needfree[i] ) + if (needfree[i]) pfree(DatumGetPointer(((GISTENTRY *) VARDATA(evec))[i].key)); gistcentryinit(giststate, j, ¢ry[j], datum, - (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, - datumsize, FALSE, FALSE); + (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, + datumsize, FALSE, FALSE); isnull[j] = ' '; - attr[j] = centry[j].key; - if ( !isAttByVal( giststate, j ) ) { + attr[j] = centry[j].key; + if (!isAttByVal(giststate, j)) + { whatfree[j] = TRUE; - if ( centry[j].key != datum ) + if (centry[j].key != datum) pfree(DatumGetPointer(datum)); - } else + } + else whatfree[j] = FALSE; } } @@ -716,7 +742,7 @@ gistunion(Relation r, IndexTuple *itvec, int len, GISTSTATE *giststate) { newtup = (IndexTuple) index_formtuple(giststate->tupdesc, attr, isnull); for (j = 0; j < r->rd_att->natts; j++) - if ( whatfree[j] ) + if (whatfree[j]) pfree(DatumGetPointer(attr[j])); return newtup; @@ -732,7 +758,8 @@ gistgetadjusted(Relation r, IndexTuple oldtup, IndexTuple addtup, GISTSTATE *gis bytea *evec; Datum datum; int datumsize; - bool result, neednew = false; + bool result, + neednew = false; char isnull[INDEX_MAX_KEYS], whatfree[INDEX_MAX_KEYS]; Datum attr[INDEX_MAX_KEYS]; @@ -744,104 +771,125 @@ gistgetadjusted(Relation r, IndexTuple oldtup, IndexTuple addtup, GISTSTATE *gis bool olddec[INDEX_MAX_KEYS], adddec[INDEX_MAX_KEYS]; bool oldisnull[INDEX_MAX_KEYS], - addisnull[INDEX_MAX_KEYS]; + addisnull[INDEX_MAX_KEYS]; IndexTuple newtup = NULL; - int j; + int j; evec = (bytea *) palloc(2 * sizeof(GISTENTRY) + VARHDRSZ); VARATT_SIZEP(evec) = 2 * sizeof(GISTENTRY) + VARHDRSZ; ev0p = &((GISTENTRY *) VARDATA(evec))[0]; ev1p = &((GISTENTRY *) VARDATA(evec))[1]; - - gistDeCompressAtt( giststate, r, oldtup, (Page) NULL, - (OffsetNumber) 0, oldatt, olddec, oldisnull); - gistDeCompressAtt( giststate, r, addtup, (Page) NULL, - (OffsetNumber) 0, addatt, adddec, addisnull); + gistDeCompressAtt(giststate, r, oldtup, (Page) NULL, + (OffsetNumber) 0, oldatt, olddec, oldisnull); + + gistDeCompressAtt(giststate, r, addtup, (Page) NULL, + (OffsetNumber) 0, addatt, adddec, addisnull); + - - for( j=0; j<r->rd_att->natts; j++ ) { - if ( oldisnull[j] && addisnull[j] ) { + for (j = 0; j < r->rd_att->natts; j++) + { + if (oldisnull[j] && addisnull[j]) + { isnull[j] = 'n'; attr[j] = (Datum) 0; whatfree[j] = FALSE; - } else { + } + else + { FILLEV( - oldisnull[j], oldatt[j].key, oldatt[j].bytes, - addisnull[j], addatt[j].key, addatt[j].bytes - ); - + oldisnull[j], oldatt[j].key, oldatt[j].bytes, + addisnull[j], addatt[j].key, addatt[j].bytes + ); + datum = FunctionCall2(&giststate->unionFn[j], - PointerGetDatum(evec), - PointerGetDatum(&datumsize)); + PointerGetDatum(evec), + PointerGetDatum(&datumsize)); - if ( oldisnull[j] || addisnull[j] ) { - if ( oldisnull[j] ) + if (oldisnull[j] || addisnull[j]) + { + if (oldisnull[j]) neednew = true; - } else { + } + else + { FunctionCall3(&giststate->equalFn[j], - ev0p->key, - datum, - PointerGetDatum(&result)); - - if ( !result ) + ev0p->key, + datum, + PointerGetDatum(&result)); + + if (!result) neednew = true; } - if ( olddec[j] ) pfree( DatumGetPointer(oldatt[j].key) ); - if ( adddec[j] ) pfree( DatumGetPointer(addatt[j].key) ); + if (olddec[j]) + pfree(DatumGetPointer(oldatt[j].key)); + if (adddec[j]) + pfree(DatumGetPointer(addatt[j].key)); gistcentryinit(giststate, j, ¢ry[j], datum, - (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, - datumsize, FALSE, FALSE); - + (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, + datumsize, FALSE, FALSE); + isnull[j] = ' '; - attr[j] = centry[j].key; - if ( (!isAttByVal( giststate, j ) ) ) { + attr[j] = centry[j].key; + if ((!isAttByVal(giststate, j))) + { whatfree[j] = TRUE; - if ( centry[j].key != datum ) + if (centry[j].key != datum) pfree(DatumGetPointer(datum)); - } else + } + else whatfree[j] = FALSE; } - } + } pfree(evec); - if (neednew) { + if (neednew) + { /* need to update key */ newtup = (IndexTuple) index_formtuple(giststate->tupdesc, attr, isnull); newtup->t_tid = oldtup->t_tid; } - + for (j = 0; j < r->rd_att->natts; j++) - if ( whatfree[j] ) + if (whatfree[j]) pfree(DatumGetPointer(attr[j])); return newtup; } static void -gistunionsubkey( Relation r, GISTSTATE *giststate, IndexTuple *itvec, GIST_SPLITVEC * spl ) { - int i,j,lr; +gistunionsubkey(Relation r, GISTSTATE *giststate, IndexTuple *itvec, GIST_SPLITVEC *spl) +{ + int i, + j, + lr; Datum *attr; - bool *needfree, IsNull; - int len, *attrsize; - OffsetNumber *entries; - bytea *evec; + bool *needfree, + IsNull; + int len, + *attrsize; + OffsetNumber *entries; + bytea *evec; Datum datum; - int datumsize; - int reallen; - bool *isnull; + int datumsize; + int reallen; + bool *isnull; - for(lr=0;lr<=1;lr++) { - if ( lr ) { + for (lr = 0; lr <= 1; lr++) + { + if (lr) + { attrsize = spl->spl_lattrsize; attr = spl->spl_lattr; len = spl->spl_nleft; entries = spl->spl_left; isnull = spl->spl_lisnull; - } else { + } + else + { attrsize = spl->spl_rattrsize; attr = spl->spl_rattr; len = spl->spl_nright; @@ -849,58 +897,64 @@ gistunionsubkey( Relation r, GISTSTATE *giststate, IndexTuple *itvec, GIST_SPLIT isnull = spl->spl_risnull; } - needfree = (bool *) palloc( (( len==1 ) ? 2 : len ) * sizeof(bool)); - evec = (bytea *) palloc( (( len==1 ) ? 2 : len ) * sizeof(GISTENTRY) + VARHDRSZ); - for (j = 1; j < r->rd_att->natts; j++) { + needfree = (bool *) palloc(((len == 1) ? 2 : len) * sizeof(bool)); + evec = (bytea *) palloc(((len == 1) ? 2 : len) * sizeof(GISTENTRY) + VARHDRSZ); + for (j = 1; j < r->rd_att->natts; j++) + { reallen = 0; - for (i = 0; i < len; i++) { - if ( spl->spl_idgrp[ entries[i] ] ) + for (i = 0; i < len; i++) + { + if (spl->spl_idgrp[entries[i]]) continue; - datum = index_getattr(itvec[ entries[i]-1 ], j+1, + datum = index_getattr(itvec[entries[i] - 1], j + 1, giststate->tupdesc, &IsNull); - if ( IsNull ) + if (IsNull) continue; gistdentryinit(giststate, j, &((GISTENTRY *) VARDATA(evec))[reallen], datum, (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, - ATTSIZE( datum, giststate->tupdesc, j+1, IsNull ), FALSE, IsNull); - if ( (!isAttByVal( giststate, j )) && - ((GISTENTRY *) VARDATA(evec))[reallen].key != datum ) + ATTSIZE(datum, giststate->tupdesc, j + 1, IsNull), FALSE, IsNull); + if ((!isAttByVal(giststate, j)) && + ((GISTENTRY *) VARDATA(evec))[reallen].key != datum) needfree[reallen] = TRUE; else needfree[reallen] = FALSE; reallen++; - - } - if ( reallen == 0 ) + + } + if (reallen == 0) { datum = (Datum) 0; datumsize = 0; isnull[j] = true; - } else { + } + else + { /* - * ((GISTENTRY *) VARDATA(evec))[0].bytes may be not defined, - * so form union with itself + * ((GISTENTRY *) VARDATA(evec))[0].bytes may be not + * defined, so form union with itself */ - if ( reallen == 1 ) { + if (reallen == 1) + { VARATT_SIZEP(evec) = 2 * sizeof(GISTENTRY) + VARHDRSZ; - memcpy( (void*) &((GISTENTRY *) VARDATA(evec))[1], - (void*) &((GISTENTRY *) VARDATA(evec))[0], - sizeof( GISTENTRY ) ); - } else + memcpy((void *) &((GISTENTRY *) VARDATA(evec))[1], + (void *) &((GISTENTRY *) VARDATA(evec))[0], + sizeof(GISTENTRY)); + } + else VARATT_SIZEP(evec) = reallen * sizeof(GISTENTRY) + VARHDRSZ; datum = FunctionCall2(&giststate->unionFn[j], - PointerGetDatum(evec), - PointerGetDatum(&datumsize)); + PointerGetDatum(evec), + PointerGetDatum(&datumsize)); isnull[j] = false; - } + } for (i = 0; i < reallen; i++) - if ( needfree[i] ) + if (needfree[i]) pfree(DatumGetPointer(((GISTENTRY *) VARDATA(evec))[i].key)); - + attr[j] = datum; attrsize[j] = datumsize; } @@ -910,51 +964,63 @@ gistunionsubkey( Relation r, GISTSTATE *giststate, IndexTuple *itvec, GIST_SPLIT } /* - * find group in vector with equial value + * find group in vector with equial value */ static int -gistfindgroup( GISTSTATE *giststate, GISTENTRY *valvec, GIST_SPLITVEC * spl ) { - int i,j,len; - int curid = 1; - bool result; - - /* - * first key is always not null (see gistinsert), - * so we may not check for nulls - */ - - for(i=0; i<spl->spl_nleft; i++) { - if ( spl->spl_idgrp[ spl->spl_left[i] ]) continue; +gistfindgroup(GISTSTATE *giststate, GISTENTRY *valvec, GIST_SPLITVEC *spl) +{ + int i, + j, + len; + int curid = 1; + bool result; + + /* + * first key is always not null (see gistinsert), so we may not check + * for nulls + */ + + for (i = 0; i < spl->spl_nleft; i++) + { + if (spl->spl_idgrp[spl->spl_left[i]]) + continue; len = 0; /* find all equal value in right part */ - for(j=0; j < spl->spl_nright; j++) { - if ( spl->spl_idgrp[ spl->spl_right[j] ]) continue; + for (j = 0; j < spl->spl_nright; j++) + { + if (spl->spl_idgrp[spl->spl_right[j]]) + continue; FunctionCall3(&giststate->equalFn[0], - valvec[ spl->spl_left[i] ].key, - valvec[ spl->spl_right[j] ].key, + valvec[spl->spl_left[i]].key, + valvec[spl->spl_right[j]].key, PointerGetDatum(&result)); - if ( result ) { - spl->spl_idgrp[ spl->spl_right[j] ] = curid; + if (result) + { + spl->spl_idgrp[spl->spl_right[j]] = curid; len++; } } /* find all other equal value in left part */ - if ( len ) { - /* add current val to list of equial values*/ - spl->spl_idgrp[ spl->spl_left[i] ]=curid; + if (len) + { + /* add current val to list of equial values */ + spl->spl_idgrp[spl->spl_left[i]] = curid; /* searching .. */ - for(j=i+1; j < spl->spl_nleft; j++) { - if ( spl->spl_idgrp[ spl->spl_left[j] ]) continue; + for (j = i + 1; j < spl->spl_nleft; j++) + { + if (spl->spl_idgrp[spl->spl_left[j]]) + continue; FunctionCall3(&giststate->equalFn[0], - valvec[ spl->spl_left[i] ].key, - valvec[ spl->spl_left[j] ].key, + valvec[spl->spl_left[i]].key, + valvec[spl->spl_left[j]].key, PointerGetDatum(&result)); - if ( result ) { - spl->spl_idgrp[ spl->spl_left[j] ] = curid; + if (result) + { + spl->spl_idgrp[spl->spl_left[j]] = curid; len++; } } - spl->spl_ngrp[curid] = len+1; + spl->spl_ngrp[curid] = len + 1; curid++; } } @@ -968,40 +1034,50 @@ gistfindgroup( GISTSTATE *giststate, GISTENTRY *valvec, GIST_SPLITVEC * spl ) { */ static void gistadjsubkey(Relation r, - IndexTuple *itup, /* contains compressed entry */ - int *len, - GIST_SPLITVEC *v, - GISTSTATE *giststate - ) { - int curlen; - OffsetNumber *curwpos; - bool decfree[INDEX_MAX_KEYS]; - GISTENTRY entry,identry[INDEX_MAX_KEYS], *ev0p, *ev1p; - float lpenalty, rpenalty; - bytea *evec; - int datumsize; - bool isnull[INDEX_MAX_KEYS]; - int i,j; + IndexTuple *itup, /* contains compressed entry */ + int *len, + GIST_SPLITVEC *v, + GISTSTATE *giststate +) +{ + int curlen; + OffsetNumber *curwpos; + bool decfree[INDEX_MAX_KEYS]; + GISTENTRY entry, + identry[INDEX_MAX_KEYS], + *ev0p, + *ev1p; + float lpenalty, + rpenalty; + bytea *evec; + int datumsize; + bool isnull[INDEX_MAX_KEYS]; + int i, + j; Datum datum; /* clear vectors */ curlen = v->spl_nleft; curwpos = v->spl_left; - for( i=0; i<v->spl_nleft;i++ ) - if ( v->spl_idgrp[ v->spl_left[i] ] == 0 ) { + for (i = 0; i < v->spl_nleft; i++) + if (v->spl_idgrp[v->spl_left[i]] == 0) + { *curwpos = v->spl_left[i]; curwpos++; - } else + } + else curlen--; v->spl_nleft = curlen; curlen = v->spl_nright; curwpos = v->spl_right; - for( i=0; i<v->spl_nright;i++ ) - if ( v->spl_idgrp[ v->spl_right[i] ] == 0 ) { + for (i = 0; i < v->spl_nright; i++) + if (v->spl_idgrp[v->spl_right[i]] == 0) + { *curwpos = v->spl_right[i]; curwpos++; - } else + } + else curlen--; v->spl_nright = curlen; @@ -1011,82 +1087,98 @@ gistadjsubkey(Relation r, ev1p = &((GISTENTRY *) VARDATA(evec))[1]; /* add equivalent tuple */ - for(i = 0; i< *len; i++) { - if ( v->spl_idgrp[ i+1 ]==0 ) /* already inserted */ + for (i = 0; i < *len; i++) + { + if (v->spl_idgrp[i + 1] == 0) /* already inserted */ continue; - gistDeCompressAtt( giststate, r, itup[i], (Page) NULL, (OffsetNumber) 0, - identry, decfree, isnull); + gistDeCompressAtt(giststate, r, itup[i], (Page) NULL, (OffsetNumber) 0, + identry, decfree, isnull); - v->spl_ngrp[ v->spl_idgrp[ i+1 ] ]--; - if ( v->spl_ngrp[ v->spl_idgrp[ i+1 ] ] == 0 && - (v->spl_grpflag[ v->spl_idgrp[ i+1 ] ] & BOTH_ADDED) != BOTH_ADDED ) { + v->spl_ngrp[v->spl_idgrp[i + 1]]--; + if (v->spl_ngrp[v->spl_idgrp[i + 1]] == 0 && + (v->spl_grpflag[v->spl_idgrp[i + 1]] & BOTH_ADDED) != BOTH_ADDED) + { /* force last in group */ rpenalty = 1.0; - lpenalty = ( v->spl_grpflag[ v->spl_idgrp[ i+1 ] ] & LEFT_ADDED ) ? 2.0 : 0.0; - } else { - /*where?*/ - for( j=1; j<r->rd_att->natts; j++ ) { - gistentryinit(entry,v->spl_lattr[j], r, (Page) NULL, - (OffsetNumber) 0, v->spl_lattrsize[j], FALSE); - gistpenalty( giststate, j, &entry, v->spl_lisnull[j], - &identry[j], isnull[j], &lpenalty); - - gistentryinit(entry,v->spl_rattr[j], r, (Page) NULL, - (OffsetNumber) 0, v->spl_rattrsize[j], FALSE); - gistpenalty( giststate, j, &entry, v->spl_risnull[j], - &identry[j], isnull[j], &rpenalty); - - if ( lpenalty != rpenalty ) + lpenalty = (v->spl_grpflag[v->spl_idgrp[i + 1]] & LEFT_ADDED) ? 2.0 : 0.0; + } + else + { + /* where? */ + for (j = 1; j < r->rd_att->natts; j++) + { + gistentryinit(entry, v->spl_lattr[j], r, (Page) NULL, + (OffsetNumber) 0, v->spl_lattrsize[j], FALSE); + gistpenalty(giststate, j, &entry, v->spl_lisnull[j], + &identry[j], isnull[j], &lpenalty); + + gistentryinit(entry, v->spl_rattr[j], r, (Page) NULL, + (OffsetNumber) 0, v->spl_rattrsize[j], FALSE); + gistpenalty(giststate, j, &entry, v->spl_risnull[j], + &identry[j], isnull[j], &rpenalty); + + if (lpenalty != rpenalty) break; } } /* add */ - if ( lpenalty < rpenalty ) { - v->spl_grpflag[ v->spl_idgrp[ i+1 ] ] |= LEFT_ADDED; - v->spl_left[ v->spl_nleft ] = i+1; + if (lpenalty < rpenalty) + { + v->spl_grpflag[v->spl_idgrp[i + 1]] |= LEFT_ADDED; + v->spl_left[v->spl_nleft] = i + 1; v->spl_nleft++; - for( j=1; j<r->rd_att->natts; j++ ) { - if ( isnull[j] && v->spl_lisnull[j] ) { + for (j = 1; j < r->rd_att->natts; j++) + { + if (isnull[j] && v->spl_lisnull[j]) + { v->spl_lattr[j] = (Datum) 0; v->spl_lattrsize[j] = 0; - } else { + } + else + { FILLEV( - v->spl_lisnull[j], v->spl_lattr[j], v->spl_lattrsize[j], - isnull[j], identry[j].key, identry[j].bytes - ); + v->spl_lisnull[j], v->spl_lattr[j], v->spl_lattrsize[j], + isnull[j], identry[j].key, identry[j].bytes + ); datum = FunctionCall2(&giststate->unionFn[j], - PointerGetDatum(evec), - PointerGetDatum(&datumsize)); + PointerGetDatum(evec), + PointerGetDatum(&datumsize)); - if ( (!isAttByVal( giststate, j )) && !v->spl_lisnull[j] ) - pfree( DatumGetPointer(v->spl_lattr[j]) ); + if ((!isAttByVal(giststate, j)) && !v->spl_lisnull[j]) + pfree(DatumGetPointer(v->spl_lattr[j])); v->spl_lattr[j] = datum; v->spl_lattrsize[j] = datumsize; v->spl_lisnull[j] = false; } } - } else { - v->spl_grpflag[ v->spl_idgrp[ i+1 ] ] |= RIGHT_ADDED; - v->spl_right[ v->spl_nright ] = i+1; + } + else + { + v->spl_grpflag[v->spl_idgrp[i + 1]] |= RIGHT_ADDED; + v->spl_right[v->spl_nright] = i + 1; v->spl_nright++; - for( j=1; j<r->rd_att->natts; j++ ) { - if ( isnull[j] && v->spl_risnull[j] ) { + for (j = 1; j < r->rd_att->natts; j++) + { + if (isnull[j] && v->spl_risnull[j]) + { v->spl_rattr[j] = (Datum) 0; v->spl_rattrsize[j] = 0; - } else { + } + else + { FILLEV( - v->spl_risnull[j], v->spl_rattr[j], v->spl_rattrsize[j], - isnull[j], identry[j].key, identry[j].bytes - ); + v->spl_risnull[j], v->spl_rattr[j], v->spl_rattrsize[j], + isnull[j], identry[j].key, identry[j].bytes + ); datum = FunctionCall2(&giststate->unionFn[j], - PointerGetDatum(evec), - PointerGetDatum(&datumsize)); + PointerGetDatum(evec), + PointerGetDatum(&datumsize)); - if ( (!isAttByVal( giststate, j)) && !v->spl_risnull[j] ) - pfree( DatumGetPointer(v->spl_rattr[j]) ); + if ((!isAttByVal(giststate, j)) && !v->spl_risnull[j]) + pfree(DatumGetPointer(v->spl_rattr[j])); v->spl_rattr[j] = datum; v->spl_rattrsize[j] = datumsize; @@ -1094,8 +1186,8 @@ gistadjsubkey(Relation r, } } - } - gistFreeAtt( r, identry, decfree ); + } + gistFreeAtt(r, identry, decfree); } pfree(evec); } @@ -1125,11 +1217,12 @@ gistSplit(Relation r, GIST_SPLITVEC v; bytea *entryvec; bool *decompvec; - int i,j, + int i, + j, nlen; - int MaxGrpId = 1; + int MaxGrpId = 1; Datum datum; - bool IsNull; + bool IsNull; p = (Page) BufferGetPage(buffer); opaque = (GISTPageOpaque) PageGetSpecialPointer(p); @@ -1168,57 +1261,62 @@ gistSplit(Relation r, for (i = 1; i <= *len; i++) { datum = index_getattr(itup[i - 1], 1, giststate->tupdesc, &IsNull); - gistdentryinit(giststate, 0,&((GISTENTRY *) VARDATA(entryvec))[i], - datum, r, p, i, - ATTSIZE( datum, giststate->tupdesc, 1, IsNull ), FALSE, IsNull); - if ( (!isAttByVal(giststate,0)) && ((GISTENTRY *) VARDATA(entryvec))[i].key != datum ) + gistdentryinit(giststate, 0, &((GISTENTRY *) VARDATA(entryvec))[i], + datum, r, p, i, + ATTSIZE(datum, giststate->tupdesc, 1, IsNull), FALSE, IsNull); + if ((!isAttByVal(giststate, 0)) && ((GISTENTRY *) VARDATA(entryvec))[i].key != datum) decompvec[i] = TRUE; else decompvec[i] = FALSE; } - /* now let the user-defined picksplit function set up the split vector; - in entryvec have no null value!! */ + /* + * now let the user-defined picksplit function set up the split + * vector; in entryvec have no null value!! + */ FunctionCall2(&giststate->picksplitFn[0], PointerGetDatum(entryvec), PointerGetDatum(&v)); - /* compatibility with old code */ - if ( v.spl_left[ v.spl_nleft-1 ] == InvalidOffsetNumber ) - v.spl_left[ v.spl_nleft-1 ] = (OffsetNumber)*len; - if ( v.spl_right[ v.spl_nright-1 ] == InvalidOffsetNumber ) - v.spl_right[ v.spl_nright-1 ] = (OffsetNumber)*len; - - v.spl_lattr[0] = v.spl_ldatum; + /* compatibility with old code */ + if (v.spl_left[v.spl_nleft - 1] == InvalidOffsetNumber) + v.spl_left[v.spl_nleft - 1] = (OffsetNumber) *len; + if (v.spl_right[v.spl_nright - 1] == InvalidOffsetNumber) + v.spl_right[v.spl_nright - 1] = (OffsetNumber) *len; + + v.spl_lattr[0] = v.spl_ldatum; v.spl_rattr[0] = v.spl_rdatum; v.spl_lisnull[0] = false; v.spl_risnull[0] = false; - /* if index is multikey, then we must to try get smaller - * bounding box for subkey(s) - */ - if ( r->rd_att->natts > 1 ) { - v.spl_idgrp = (int*) palloc( sizeof(int) * (*len + 1) ); - MemSet((void*)v.spl_idgrp, 0, sizeof(int) * (*len + 1) ); - v.spl_grpflag = (char*) palloc( sizeof(char) * (*len + 1) ); - MemSet((void*)v.spl_grpflag, 0, sizeof(char) * (*len + 1) ); - v.spl_ngrp = (int*) palloc( sizeof(int) * (*len + 1) ); + /* + * if index is multikey, then we must to try get smaller bounding box + * for subkey(s) + */ + if (r->rd_att->natts > 1) + { + v.spl_idgrp = (int *) palloc(sizeof(int) * (*len + 1)); + MemSet((void *) v.spl_idgrp, 0, sizeof(int) * (*len + 1)); + v.spl_grpflag = (char *) palloc(sizeof(char) * (*len + 1)); + MemSet((void *) v.spl_grpflag, 0, sizeof(char) * (*len + 1)); + v.spl_ngrp = (int *) palloc(sizeof(int) * (*len + 1)); - MaxGrpId = gistfindgroup( giststate, (GISTENTRY *) VARDATA(entryvec), &v ); + MaxGrpId = gistfindgroup(giststate, (GISTENTRY *) VARDATA(entryvec), &v); /* form union of sub keys for each page (l,p) */ - gistunionsubkey( r, giststate, itup, &v ); + gistunionsubkey(r, giststate, itup, &v); - /* if possible, we insert equivalent tuples - * with control by penalty for a subkey(s) - */ - if ( MaxGrpId > 1 ) - gistadjsubkey( r,itup,len, &v, giststate ); + /* + * if possible, we insert equivalent tuples with control by + * penalty for a subkey(s) + */ + if (MaxGrpId > 1) + gistadjsubkey(r, itup, len, &v, giststate); - pfree( v.spl_idgrp ); - pfree( v.spl_grpflag ); - pfree( v.spl_ngrp ); - } + pfree(v.spl_idgrp); + pfree(v.spl_grpflag); + pfree(v.spl_ngrp); + } /* clean up the entry vector: its keys need to be deleted, too */ for (i = 1; i <= *len; i++) @@ -1231,11 +1329,11 @@ gistSplit(Relation r, lvectup = (IndexTuple *) palloc(sizeof(IndexTuple) * v.spl_nleft); rvectup = (IndexTuple *) palloc(sizeof(IndexTuple) * v.spl_nright); - for(i=0; i<v.spl_nleft;i++) - lvectup[i] = itup[ v.spl_left[i] - 1 ]; + for (i = 0; i < v.spl_nleft; i++) + lvectup[i] = itup[v.spl_left[i] - 1]; - for(i=0; i<v.spl_nright;i++) - rvectup[i] = itup[ v.spl_right[i] - 1 ]; + for (i = 0; i < v.spl_nright; i++) + rvectup[i] = itup[v.spl_right[i] - 1]; /* write on disk (may be need another split) */ @@ -1245,9 +1343,9 @@ gistSplit(Relation r, newtup = gistSplit(r, rightbuf, rvectup, &nlen, giststate, (res && rvectup[nlen - 1] == itup[*len - 1]) ? res : NULL); ReleaseBuffer(rightbuf); - for( j=1; j<r->rd_att->natts; j++ ) - if ( (!isAttByVal(giststate,j)) && !v.spl_risnull[j] ) - pfree( DatumGetPointer(v.spl_rattr[j]) ); + for (j = 1; j < r->rd_att->natts; j++) + if ((!isAttByVal(giststate, j)) && !v.spl_risnull[j]) + pfree(DatumGetPointer(v.spl_rattr[j])); } else { @@ -1261,7 +1359,7 @@ gistSplit(Relation r, nlen = 1; newtup = (IndexTuple *) palloc(sizeof(IndexTuple) * 1); - newtup[0] = gistFormTuple( giststate, r, v.spl_rattr, v.spl_rattrsize, v.spl_risnull ); + newtup[0] = gistFormTuple(giststate, r, v.spl_rattr, v.spl_rattrsize, v.spl_risnull); ItemPointerSet(&(newtup[0]->t_tid), rbknum, 1); } @@ -1275,9 +1373,9 @@ gistSplit(Relation r, (res && lvectup[llen - 1] == itup[*len - 1]) ? res : NULL); ReleaseBuffer(leftbuf); - for( j=1; j<r->rd_att->natts; j++ ) - if ( (!isAttByVal(giststate,j)) && !v.spl_lisnull[j] ) - pfree( DatumGetPointer(v.spl_lattr[j]) ); + for (j = 1; j < r->rd_att->natts; j++) + if ((!isAttByVal(giststate, j)) && !v.spl_lisnull[j]) + pfree(DatumGetPointer(v.spl_lattr[j])); newtup = gistjoinvector(newtup, &nlen, lntup, llen); pfree(lntup); @@ -1297,7 +1395,7 @@ gistSplit(Relation r, nlen += 1; newtup = (IndexTuple *) repalloc((void *) newtup, sizeof(IndexTuple) * nlen); - newtup[nlen - 1] = gistFormTuple( giststate, r, v.spl_lattr, v.spl_lattrsize, v.spl_lisnull ); + newtup[nlen - 1] = gistFormTuple(giststate, r, v.spl_lattr, v.spl_lattrsize, v.spl_lisnull); ItemPointerSet(&(newtup[nlen - 1]->t_tid), lbknum, 1); } @@ -1359,47 +1457,56 @@ gistchoose(Relation r, Page p, IndexTuple it, /* it has compressed entry */ Datum datum; float usize; OffsetNumber which; - float sum_grow, which_grow[INDEX_MAX_KEYS]; + float sum_grow, + which_grow[INDEX_MAX_KEYS]; GISTENTRY entry, identry[INDEX_MAX_KEYS]; - bool IsNull, decompvec[INDEX_MAX_KEYS], isnull[INDEX_MAX_KEYS]; - int j; + bool IsNull, + decompvec[INDEX_MAX_KEYS], + isnull[INDEX_MAX_KEYS]; + int j; maxoff = PageGetMaxOffsetNumber(p); *which_grow = -1.0; which = -1; - sum_grow=1; - gistDeCompressAtt( giststate, r, - it, (Page) NULL, (OffsetNumber) 0, - identry, decompvec, isnull ); + sum_grow = 1; + gistDeCompressAtt(giststate, r, + it, (Page) NULL, (OffsetNumber) 0, + identry, decompvec, isnull); for (i = FirstOffsetNumber; i <= maxoff && sum_grow; i = OffsetNumberNext(i)) { - IndexTuple itup = (IndexTuple) PageGetItem(p, PageGetItemId(p, i)); - sum_grow=0; - for (j=0; j<r->rd_att->natts; j++) { - datum = index_getattr(itup, j+1, giststate->tupdesc, &IsNull); - gistdentryinit(giststate, j, &entry, datum, r, p, i, ATTSIZE( datum, giststate->tupdesc, j+1, IsNull ), FALSE, IsNull); - gistpenalty( giststate, j, &entry, IsNull, &identry[j], isnull[j], &usize); - - if ( (!isAttByVal(giststate,j)) && entry.key != datum) + IndexTuple itup = (IndexTuple) PageGetItem(p, PageGetItemId(p, i)); + + sum_grow = 0; + for (j = 0; j < r->rd_att->natts; j++) + { + datum = index_getattr(itup, j + 1, giststate->tupdesc, &IsNull); + gistdentryinit(giststate, j, &entry, datum, r, p, i, ATTSIZE(datum, giststate->tupdesc, j + 1, IsNull), FALSE, IsNull); + gistpenalty(giststate, j, &entry, IsNull, &identry[j], isnull[j], &usize); + + if ((!isAttByVal(giststate, j)) && entry.key != datum) pfree(DatumGetPointer(entry.key)); - if ( which_grow[j]<0 || usize < which_grow[j] ) { + if (which_grow[j] < 0 || usize < which_grow[j]) + { which = i; which_grow[j] = usize; - if ( j<r->rd_att->natts-1 && i==FirstOffsetNumber ) which_grow[j+1]=-1; - sum_grow += which_grow[j]; - } else if ( which_grow[j] == usize ) { + if (j < r->rd_att->natts - 1 && i == FirstOffsetNumber) + which_grow[j + 1] = -1; + sum_grow += which_grow[j]; + } + else if (which_grow[j] == usize) sum_grow += usize; - } else { - sum_grow=1; + else + { + sum_grow = 1; break; } } } - gistFreeAtt( r, identry, decompvec ); + gistFreeAtt(r, identry, decompvec); return which; } @@ -1434,7 +1541,7 @@ gistdelete(Relation r, ItemPointer tid) /* * Since GIST is not marked "amconcurrent" in pg_am, caller should - * have acquired exclusive lock on index relation. We need no locking + * have acquired exclusive lock on index relation. We need no locking * here. */ @@ -1468,7 +1575,7 @@ gistbulkdelete(PG_FUNCTION_ARGS) IndexBulkDeleteCallback callback = (IndexBulkDeleteCallback) PG_GETARG_POINTER(1); void *callback_state = (void *) PG_GETARG_POINTER(2); IndexBulkDeleteResult *result; - BlockNumber num_pages; + BlockNumber num_pages; double tuples_removed; double num_index_tuples; RetrieveIndexResult res; @@ -1479,7 +1586,7 @@ gistbulkdelete(PG_FUNCTION_ARGS) /* * Since GIST is not marked "amconcurrent" in pg_am, caller should - * have acquired exclusive lock on index relation. We need no locking + * have acquired exclusive lock on index relation. We need no locking * here. */ @@ -1542,7 +1649,7 @@ gistbulkdelete(PG_FUNCTION_ARGS) void initGISTstate(GISTSTATE *giststate, Relation index) { - int i; + int i; if (index->rd_att->natts > INDEX_MAX_KEYS) elog(ERROR, "initGISTstate: numberOfAttributes %d > %d", @@ -1553,31 +1660,32 @@ initGISTstate(GISTSTATE *giststate, Relation index) for (i = 0; i < index->rd_att->natts; i++) { fmgr_info_copy(&(giststate->consistentFn[i]), - index_getprocinfo(index, i+1, GIST_CONSISTENT_PROC), + index_getprocinfo(index, i + 1, GIST_CONSISTENT_PROC), CurrentMemoryContext); fmgr_info_copy(&(giststate->unionFn[i]), - index_getprocinfo(index, i+1, GIST_UNION_PROC), + index_getprocinfo(index, i + 1, GIST_UNION_PROC), CurrentMemoryContext); fmgr_info_copy(&(giststate->compressFn[i]), - index_getprocinfo(index, i+1, GIST_COMPRESS_PROC), + index_getprocinfo(index, i + 1, GIST_COMPRESS_PROC), CurrentMemoryContext); fmgr_info_copy(&(giststate->decompressFn[i]), - index_getprocinfo(index, i+1, GIST_DECOMPRESS_PROC), + index_getprocinfo(index, i + 1, GIST_DECOMPRESS_PROC), CurrentMemoryContext); fmgr_info_copy(&(giststate->penaltyFn[i]), - index_getprocinfo(index, i+1, GIST_PENALTY_PROC), + index_getprocinfo(index, i + 1, GIST_PENALTY_PROC), CurrentMemoryContext); fmgr_info_copy(&(giststate->picksplitFn[i]), - index_getprocinfo(index, i+1, GIST_PICKSPLIT_PROC), + index_getprocinfo(index, i + 1, GIST_PICKSPLIT_PROC), CurrentMemoryContext); fmgr_info_copy(&(giststate->equalFn[i]), - index_getprocinfo(index, i+1, GIST_EQUAL_PROC), + index_getprocinfo(index, i + 1, GIST_EQUAL_PROC), CurrentMemoryContext); } } void -freeGISTstate(GISTSTATE *giststate) { +freeGISTstate(GISTSTATE *giststate) +{ /* no work */ } @@ -1592,13 +1700,14 @@ freeGISTstate(GISTSTATE *giststate) { static IndexTuple gist_tuple_replacekey(Relation r, GISTENTRY entry, IndexTuple t) { - bool IsNull; - Datum datum = index_getattr(t, 1, r->rd_att, &IsNull); + bool IsNull; + Datum datum = index_getattr(t, 1, r->rd_att, &IsNull); /* * If new entry fits in index tuple, copy it in. To avoid worrying - * about null-value bitmask, pass it off to the general index_formtuple - * routine if either the previous or new value is NULL. + * about null-value bitmask, pass it off to the general + * index_formtuple routine if either the previous or new value is + * NULL. */ if (!IsNull && DatumGetPointer(entry.key) != NULL && (Size) entry.bytes <= ATTSIZE(datum, r, 1, IsNull)) @@ -1638,7 +1747,7 @@ gistdentryinit(GISTSTATE *giststate, int nkey, GISTENTRY *e, Datum k, Relation r, Page pg, OffsetNumber o, int b, bool l, bool isNull) { - if ( b && ! isNull ) + if (b && !isNull) { GISTENTRY *dep; @@ -1655,9 +1764,7 @@ gistdentryinit(GISTSTATE *giststate, int nkey, GISTENTRY *e, } } else - { gistentryinit(*e, (Datum) 0, r, pg, o, 0, l); - } } @@ -1686,92 +1793,103 @@ gistcentryinit(GISTSTATE *giststate, int nkey, } } else - { gistentryinit(*e, (Datum) 0, r, pg, o, 0, l); - } } static IndexTuple -gistFormTuple( GISTSTATE *giststate, Relation r, - Datum attdata[], int datumsize[], bool isnull[] ) +gistFormTuple(GISTSTATE *giststate, Relation r, + Datum attdata[], int datumsize[], bool isnull[]) { IndexTuple tup; - char isnullchar[INDEX_MAX_KEYS]; - bool whatfree[INDEX_MAX_KEYS]; - GISTENTRY centry[INDEX_MAX_KEYS]; - Datum compatt[INDEX_MAX_KEYS]; - int j; - - for (j = 0; j < r->rd_att->natts; j++) { - if ( isnull[j] ) { + char isnullchar[INDEX_MAX_KEYS]; + bool whatfree[INDEX_MAX_KEYS]; + GISTENTRY centry[INDEX_MAX_KEYS]; + Datum compatt[INDEX_MAX_KEYS]; + int j; + + for (j = 0; j < r->rd_att->natts; j++) + { + if (isnull[j]) + { isnullchar[j] = 'n'; compatt[j] = (Datum) 0; whatfree[j] = FALSE; - } else { + } + else + { gistcentryinit(giststate, j, ¢ry[j], attdata[j], - (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, - datumsize[j], FALSE, FALSE); + (Relation) NULL, (Page) NULL, (OffsetNumber) NULL, + datumsize[j], FALSE, FALSE); isnullchar[j] = ' '; compatt[j] = centry[j].key; - if ( !isAttByVal(giststate,j) ) { + if (!isAttByVal(giststate, j)) + { whatfree[j] = TRUE; - if ( centry[j].key != attdata[j] ) + if (centry[j].key != attdata[j]) pfree(DatumGetPointer(attdata[j])); - } else + } + else whatfree[j] = FALSE; } } tup = (IndexTuple) index_formtuple(giststate->tupdesc, compatt, isnullchar); for (j = 0; j < r->rd_att->natts; j++) - if ( whatfree[j] ) pfree(DatumGetPointer(compatt[j])); + if (whatfree[j]) + pfree(DatumGetPointer(compatt[j])); - return tup; -} + return tup; +} static void -gistDeCompressAtt( GISTSTATE *giststate, Relation r, IndexTuple tuple, Page p, - OffsetNumber o, GISTENTRY attdata[], bool decompvec[], bool isnull[] ) { - int i; - Datum datum; +gistDeCompressAtt(GISTSTATE *giststate, Relation r, IndexTuple tuple, Page p, + OffsetNumber o, GISTENTRY attdata[], bool decompvec[], bool isnull[]) +{ + int i; + Datum datum; - for(i=0; i < r->rd_att->natts; i++ ) { - datum = index_getattr(tuple, i+1, giststate->tupdesc, &isnull[i]); + for (i = 0; i < r->rd_att->natts; i++) + { + datum = index_getattr(tuple, i + 1, giststate->tupdesc, &isnull[i]); gistdentryinit(giststate, i, &attdata[i], - datum, r, p, o, - ATTSIZE( datum, giststate->tupdesc, i+1, isnull[i] ), FALSE, isnull[i]); - if ( isAttByVal(giststate,i) ) + datum, r, p, o, + ATTSIZE(datum, giststate->tupdesc, i + 1, isnull[i]), FALSE, isnull[i]); + if (isAttByVal(giststate, i)) decompvec[i] = FALSE; - else { - if (attdata[i].key == datum || isnull[i] ) + else + { + if (attdata[i].key == datum || isnull[i]) decompvec[i] = FALSE; else decompvec[i] = TRUE; } } -} +} static void -gistFreeAtt( Relation r, GISTENTRY attdata[], bool decompvec[] ) { - int i; - for(i=0; i < r->rd_att->natts; i++ ) - if ( decompvec[i] ) - pfree( DatumGetPointer(attdata[i].key) ); +gistFreeAtt(Relation r, GISTENTRY attdata[], bool decompvec[]) +{ + int i; + + for (i = 0; i < r->rd_att->natts; i++) + if (decompvec[i]) + pfree(DatumGetPointer(attdata[i].key)); } static void -gistpenalty( GISTSTATE *giststate, int attno, - GISTENTRY *key1, bool isNull1, - GISTENTRY *key2, bool isNull2, float *penalty ){ - if ( giststate->penaltyFn[attno].fn_strict && ( isNull1 || isNull2 ) ) - *penalty=0.0; - else +gistpenalty(GISTSTATE *giststate, int attno, + GISTENTRY *key1, bool isNull1, + GISTENTRY *key2, bool isNull2, float *penalty) +{ + if (giststate->penaltyFn[attno].fn_strict && (isNull1 || isNull2)) + *penalty = 0.0; + else FunctionCall3(&giststate->penaltyFn[attno], - PointerGetDatum(key1), - PointerGetDatum(key2), - PointerGetDatum(penalty)); + PointerGetDatum(key1), + PointerGetDatum(key2), + PointerGetDatum(penalty)); } - + #ifdef GISTDEBUG static void gist_dumptree(Relation r, int level, BlockNumber blk, OffsetNumber coff) @@ -1816,7 +1934,6 @@ gist_dumptree(Relation r, int level, BlockNumber blk, OffsetNumber coff) ReleaseBuffer(buffer); pfree(pred); } - #endif /* defined GISTDEBUG */ void diff --git a/src/backend/access/gist/gistget.c b/src/backend/access/gist/gistget.c index be2d749845..ed92258e62 100644 --- a/src/backend/access/gist/gistget.c +++ b/src/backend/access/gist/gistget.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/gist/gistget.c,v 1.30 2001/08/22 18:24:26 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/gist/gistget.c,v 1.31 2001/10/25 05:49:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -251,7 +251,7 @@ gistindex_keytest(IndexTuple tuple, if (key[0].sk_flags & SK_ISNULL) return false; */ - gistdentryinit(giststate, key[0].sk_attno-1, &de, + gistdentryinit(giststate, key[0].sk_attno - 1, &de, datum, r, p, offset, IndexTupleSize(tuple) - sizeof(IndexTupleData), FALSE, isNull); @@ -271,9 +271,9 @@ gistindex_keytest(IndexTuple tuple, ObjectIdGetDatum(key[0].sk_procedure)); } - if ( de.key != datum && ! isAttByVal( giststate, key[0].sk_attno-1 ) ) - if ( DatumGetPointer(de.key) != NULL ) - pfree( DatumGetPointer(de.key) ); + if (de.key != datum && !isAttByVal(giststate, key[0].sk_attno - 1)) + if (DatumGetPointer(de.key) != NULL) + pfree(DatumGetPointer(de.key)); if (DatumGetBool(test) == !!(key[0].sk_flags & SK_NEGATE)) return false; diff --git a/src/backend/access/gist/gistscan.c b/src/backend/access/gist/gistscan.c index 2b65321b03..8623b8f643 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.39 2001/08/22 18:24:26 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/gist/gistscan.c,v 1.40 2001/10/25 05:49:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -112,7 +112,7 @@ gistrescan(PG_FUNCTION_ARGS) s->keyData[i].sk_procedure = RelationGetGISTStrategy(s->relation, s->keyData[i].sk_attno, s->keyData[i].sk_procedure); - s->keyData[i].sk_func = p->giststate->consistentFn[s->keyData[i].sk_attno-1]; + s->keyData[i].sk_func = p->giststate->consistentFn[s->keyData[i].sk_attno - 1]; } } else @@ -137,13 +137,13 @@ gistrescan(PG_FUNCTION_ARGS) /*---------- * s->keyData[i].sk_procedure = - * index_getprocid(s->relation, 1, GIST_CONSISTENT_PROC); + * index_getprocid(s->relation, 1, GIST_CONSISTENT_PROC); *---------- */ s->keyData[i].sk_procedure = RelationGetGISTStrategy(s->relation, s->keyData[i].sk_attno, s->keyData[i].sk_procedure); - s->keyData[i].sk_func = p->giststate->consistentFn[s->keyData[i].sk_attno-1]; + s->keyData[i].sk_func = p->giststate->consistentFn[s->keyData[i].sk_attno - 1]; } } @@ -234,8 +234,8 @@ gistendscan(PG_FUNCTION_ARGS) { gistfreestack(p->s_stack); gistfreestack(p->s_markstk); - if ( p->giststate != NULL ) - freeGISTstate( p->giststate ); + if (p->giststate != NULL) + freeGISTstate(p->giststate); pfree(s->opaque); } @@ -383,7 +383,6 @@ adjustiptr(IndexScanDesc s, } else { - /* * remember that we're before the current * tuple diff --git a/src/backend/access/gist/giststrat.c b/src/backend/access/gist/giststrat.c index e0bae48a3c..db38191d6a 100644 --- a/src/backend/access/gist/giststrat.c +++ b/src/backend/access/gist/giststrat.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/gist/Attic/giststrat.c,v 1.17 2001/05/30 19:53:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/gist/Attic/giststrat.c,v 1.18 2001/10/25 05:49:20 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -121,5 +121,4 @@ RelationInvokeGISTStrategy(Relation r, return (RelationInvokeStrategy(r, &GISTEvaluationData, attnum, s, left, right)); } - #endif diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c index 9b0e6cf28e..177f3648f4 100644 --- a/src/backend/access/hash/hash.c +++ b/src/backend/access/hash/hash.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/hash/hash.c,v 1.52 2001/07/15 22:48:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/hash.c,v 1.53 2001/10/25 05:49:20 momjian Exp $ * * NOTES * This file contains only the public interface routines. @@ -37,11 +37,11 @@ typedef struct } HashBuildState; static void hashbuildCallback(Relation index, - HeapTuple htup, - Datum *attdata, - char *nulls, - bool tupleIsAlive, - void *state); + HeapTuple htup, + Datum *attdata, + char *nulls, + bool tupleIsAlive, + void *state); /* @@ -80,7 +80,7 @@ hashbuild(PG_FUNCTION_ARGS) /* do the heap scan */ reltuples = IndexBuildHeapScan(heap, index, indexInfo, - hashbuildCallback, (void *) &buildstate); + hashbuildCallback, (void *) &buildstate); /* all done */ BuildingHash = false; @@ -121,7 +121,7 @@ hashbuildCallback(Relation index, bool tupleIsAlive, void *state) { - HashBuildState *buildstate = (HashBuildState *) state; + HashBuildState *buildstate = (HashBuildState *) state; IndexTuple itup; HashItem hitem; InsertIndexResult res; @@ -164,6 +164,7 @@ hashinsert(PG_FUNCTION_ARGS) Datum *datum = (Datum *) PG_GETARG_POINTER(1); char *nulls = (char *) PG_GETARG_POINTER(2); ItemPointer ht_ctid = (ItemPointer) PG_GETARG_POINTER(3); + #ifdef NOT_USED Relation heapRel = (Relation) PG_GETARG_POINTER(4); #endif @@ -176,14 +177,13 @@ hashinsert(PG_FUNCTION_ARGS) itup->t_tid = *ht_ctid; /* - * If the single index key is null, we don't insert it into the - * index. Hash tables support scans on '='. Relational algebra - * says that A = B returns null if either A or B is null. This - * means that no qualification used in an index scan could ever - * return true on a null attribute. It also means that indices - * can't be used by ISNULL or NOTNULL scans, but that's an - * artifact of the strategy map architecture chosen in 1986, not - * of the way nulls are handled here. + * If the single index key is null, we don't insert it into the index. + * Hash tables support scans on '='. Relational algebra says that A = + * B returns null if either A or B is null. This means that no + * qualification used in an index scan could ever return true on a + * null attribute. It also means that indices can't be used by ISNULL + * or NOTNULL scans, but that's an artifact of the strategy map + * architecture chosen in 1986, not of the way nulls are handled here. */ if (IndexTupleHasNulls(itup)) { @@ -262,7 +262,6 @@ hashrescan(PG_FUNCTION_ARGS) #ifdef NOT_USED /* XXX surely it's wrong to ignore this? */ bool fromEnd = PG_GETARG_BOOL(1); - #endif ScanKey scankey = (ScanKey) PG_GETARG_POINTER(2); ItemPointer iptr; @@ -412,7 +411,7 @@ hashbulkdelete(PG_FUNCTION_ARGS) IndexBulkDeleteCallback callback = (IndexBulkDeleteCallback) PG_GETARG_POINTER(1); void *callback_state = (void *) PG_GETARG_POINTER(2); IndexBulkDeleteResult *result; - BlockNumber num_pages; + BlockNumber num_pages; double tuples_removed; double num_index_tuples; RetrieveIndexResult res; diff --git a/src/backend/access/hash/hashinsert.c b/src/backend/access/hash/hashinsert.c index 5439dce214..2f99e7426d 100644 --- a/src/backend/access/hash/hashinsert.c +++ b/src/backend/access/hash/hashinsert.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/hash/hashinsert.c,v 1.22 2001/03/07 21:20:26 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/hashinsert.c,v 1.23 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -133,13 +133,11 @@ _hash_insertonpg(Relation rel, while (PageGetFreeSpace(page) < itemsz) { - /* * no space on this page; check for an overflow page */ if (BlockNumberIsValid(pageopaque->hasho_nextblkno)) { - /* * ovfl page exists; go get it. if it doesn't have room, * we'll find out next pass through the loop test above. @@ -152,7 +150,6 @@ _hash_insertonpg(Relation rel, } else { - /* * we're at the end of the bucket chain and we haven't found a * page with enough room. allocate a new overflow page. @@ -184,7 +181,6 @@ _hash_insertonpg(Relation rel, if (res != NULL) { - /* * Increment the number of keys in the table. We switch lock * access type just for a moment to allow greater accessibility to diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c index c9fb065dbd..e41c1bd0a3 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.30 2001/07/15 22:48:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/hashovfl.c,v 1.31 2001/10/25 05:49:21 momjian Exp $ * * NOTES * Overflow pages look like ordinary relation pages. @@ -208,7 +208,6 @@ _hash_getovfladdr(Relation rel, Buffer *metabufp) } else { - /* * Free_bit addresses the last used bit. Bump it to address the * first available bit. diff --git a/src/backend/access/hash/hashpage.c b/src/backend/access/hash/hashpage.c index b8c520e3c0..0fff5a11e6 100644 --- a/src/backend/access/hash/hashpage.c +++ b/src/backend/access/hash/hashpage.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/hash/hashpage.c,v 1.32 2001/07/15 22:48:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/hashpage.c,v 1.33 2001/10/25 05:49:21 momjian Exp $ * * NOTES * Postgres hash pages look like ordinary relation pages. The opaque @@ -50,7 +50,7 @@ static void _hash_splitpage(Relation rel, Buffer metabuf, Bucket obucket, Bucket * system catalogs anyway. * * Note that our page locks are actual lockmanager locks, not buffer - * locks (as are used by btree, for example). This is a good idea because + * locks (as are used by btree, for example). This is a good idea because * the algorithms are not deadlock-free, and we'd better be able to detect * and recover from deadlocks. * @@ -325,7 +325,7 @@ _hash_setpagelock(Relation rel, { switch (access) { - case HASH_WRITE: + case HASH_WRITE: LockPage(rel, blkno, ExclusiveLock); break; case HASH_READ: @@ -349,7 +349,7 @@ _hash_unsetpagelock(Relation rel, { switch (access) { - case HASH_WRITE: + case HASH_WRITE: UnlockPage(rel, blkno, ExclusiveLock); break; case HASH_READ: @@ -369,7 +369,7 @@ _hash_unsetpagelock(Relation rel, * It is safe to delete an item after acquiring a regular WRITE lock on * the page, because no other backend can hold a READ lock on the page, * and that means no other backend currently has an indexscan stopped on - * any item of the item being deleted. Our own backend might have such + * any item of the item being deleted. Our own backend might have such * an indexscan (in fact *will*, since that's how VACUUM found the item * in the first place), but _hash_adjscans will fix the scan position. */ @@ -532,7 +532,6 @@ _hash_splitpage(Relation rel, _hash_relbuf(rel, obuf, HASH_WRITE); if (!BlockNumberIsValid(oblkno)) { - /* * the old bucket is completely empty; of course, the new * bucket will be as well, but since it's a base bucket page @@ -559,7 +558,6 @@ _hash_splitpage(Relation rel, omaxoffnum = PageGetMaxOffsetNumber(opage); for (;;) { - /* * at each iteration through this loop, each of these variables * should be up-to-date: obuf opage oopaque ooffnum omaxoffnum @@ -572,7 +570,6 @@ _hash_splitpage(Relation rel, oblkno = oopaque->hasho_nextblkno; if (BlockNumberIsValid(oblkno)) { - /* * we ran out of tuples on this particular page, but we * have more overflow pages; re-init values. @@ -594,7 +591,6 @@ _hash_splitpage(Relation rel, } else { - /* * we're at the end of the bucket chain, so now we're * really done with everything. before quitting, call @@ -618,7 +614,6 @@ _hash_splitpage(Relation rel, if (bucket == nbucket) { - /* * insert the tuple into the new bucket. if it doesn't fit on * the current page in the new bucket, we must allocate a new @@ -695,7 +690,6 @@ _hash_splitpage(Relation rel, } else { - /* * the tuple stays on this page. we didn't move anything, so * we didn't delete anything and therefore we don't have to diff --git a/src/backend/access/hash/hashsearch.c b/src/backend/access/hash/hashsearch.c index 27ca030118..6ea643dcaf 100644 --- a/src/backend/access/hash/hashsearch.c +++ b/src/backend/access/hash/hashsearch.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/hash/hashsearch.c,v 1.26 2001/03/23 04:49:51 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/hashsearch.c,v 1.27 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -36,7 +36,6 @@ _hash_search(Relation rel, if (scankey == (ScanKey) NULL || (keyDatum = scankey[0].sk_argument) == (Datum) NULL) { - /* * If the scankey argument is NULL, all tuples will satisfy the * scan so we start the scan at the first bucket (bucket 0). diff --git a/src/backend/access/hash/hashstrat.c b/src/backend/access/hash/hashstrat.c index fc5df2372d..a765c2e2b1 100644 --- a/src/backend/access/hash/hashstrat.c +++ b/src/backend/access/hash/hashstrat.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/hash/Attic/hashstrat.c,v 1.18 2001/05/30 19:53:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/hash/Attic/hashstrat.c,v 1.19 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -46,7 +46,6 @@ static StrategyEvaluationData HTEvaluationData = { (StrategyTransformMap) HTNegateCommute, HTEvaluationExpressions }; - #endif /* ---------------------------------------------------------------- @@ -68,7 +67,6 @@ _hash_getstrat(Relation rel, return strat; } - #endif #ifdef NOT_USED @@ -82,5 +80,4 @@ _hash_invokestrat(Relation rel, return (RelationInvokeStrategy(rel, &HTEvaluationData, attno, strat, left, right)); } - #endif diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index c64a19faa6..f73ca50285 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.125 2001/08/23 23:06:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/heap/heapam.c,v 1.126 2001/10/25 05:49:21 momjian Exp $ * * * INTERFACE ROUTINES @@ -116,8 +116,8 @@ heapgettup(Relation relation, { ItemId lpp; Page dp; - BlockNumber page; - BlockNumber pages; + BlockNumber page; + BlockNumber pages; int lines; OffsetNumber lineoff; int linesleft; @@ -350,7 +350,7 @@ heapgettup(Relation relation, /* * return NULL if we've exhausted all the pages */ - if ((dir < 0) ? (page == 0) : (page+1 >= pages)) + if ((dir < 0) ? (page == 0) : (page + 1 >= pages)) { if (BufferIsValid(*buffer)) ReleaseBuffer(*buffer); @@ -429,9 +429,8 @@ fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, ( (Datum) NULL ) - ); + ); } - #endif /* defined(DISABLE_COMPLEX_MACRO) */ @@ -1045,12 +1044,13 @@ heap_insert(Relation relation, HeapTuple tup) if (relation->rd_rel->relhasoids) { /* - * If the object id of this tuple has already been assigned, trust the - * caller. There are a couple of ways this can happen. At initial db - * creation, the backend program sets oids for tuples. When we define - * an index, we set the oid. Finally, in the future, we may allow - * users to set their own object ids in order to support a persistent - * object store (objects need to contain pointers to one another). + * If the object id of this tuple has already been assigned, trust + * the caller. There are a couple of ways this can happen. At + * initial db creation, the backend program sets oids for tuples. + * When we define an index, we set the oid. Finally, in the + * future, we may allow users to set their own object ids in order + * to support a persistent object store (objects need to contain + * pointers to one another). */ if (!OidIsValid(tup->t_data->t_oid)) tup->t_data->t_oid = newoid(); @@ -1478,21 +1478,22 @@ l2: } /* - * Now, do we need a new page for the tuple, or not? This is a bit - * tricky since someone else could have added tuples to the page - * while we weren't looking. We have to recheck the available space - * after reacquiring the buffer lock. But don't bother to do that - * if the former amount of free space is still not enough; it's - * unlikely there's more free now than before. + * Now, do we need a new page for the tuple, or not? This is a + * bit tricky since someone else could have added tuples to the + * page while we weren't looking. We have to recheck the + * available space after reacquiring the buffer lock. But don't + * bother to do that if the former amount of free space is still + * not enough; it's unlikely there's more free now than before. * * What's more, if we need to get a new page, we will need to acquire - * buffer locks on both old and new pages. To avoid deadlock against - * some other backend trying to get the same two locks in the other - * order, we must be consistent about the order we get the locks in. - * We use the rule "lock the lower-numbered page of the relation - * first". To implement this, we must do RelationGetBufferForTuple - * while not holding the lock on the old page, and we must rely on it - * to get the locks on both pages in the correct order. + * buffer locks on both old and new pages. To avoid deadlock + * against some other backend trying to get the same two locks in + * the other order, we must be consistent about the order we get + * the locks in. We use the rule "lock the lower-numbered page of + * the relation first". To implement this, we must do + * RelationGetBufferForTuple while not holding the lock on the old + * page, and we must rely on it to get the locks on both pages in + * the correct order. */ if (newtupsize > pagefree) { @@ -1510,8 +1511,8 @@ l2: { /* * Rats, it doesn't fit anymore. We must now unlock and - * relock to avoid deadlock. Fortunately, this path should - * seldom be taken. + * relock to avoid deadlock. Fortunately, this path + * should seldom be taken. */ LockBuffer(buffer, BUFFER_LOCK_UNLOCK); newbuf = RelationGetBufferForTuple(relation, newtup->t_len, @@ -1534,9 +1535,9 @@ l2: pgstat_count_heap_update(&relation->pgstat_info); /* - * At this point newbuf and buffer are both pinned and locked, - * and newbuf has enough space for the new tuple. If they are - * the same buffer, only one pin is held. + * At this point newbuf and buffer are both pinned and locked, and + * newbuf has enough space for the new tuple. If they are the same + * buffer, only one pin is held. */ /* NO ELOG(ERROR) from here till changes are logged */ @@ -1865,12 +1866,14 @@ log_heap_update(Relation reln, Buffer oldbuf, ItemPointerData from, * Note: xlhdr is declared to have adequate size and correct alignment * for an xl_heap_header. However the two tids, if present at all, * will be packed in with no wasted space after the xl_heap_header; - * they aren't necessarily aligned as implied by this struct declaration. + * they aren't necessarily aligned as implied by this struct + * declaration. */ - struct { - xl_heap_header hdr; - TransactionId tid1; - TransactionId tid2; + struct + { + xl_heap_header hdr; + TransactionId tid1; + TransactionId tid2; } xlhdr; int hsize = SizeOfHeapHeader; xl_heap_update xlrec; @@ -1972,7 +1975,7 @@ heap_xlog_clean(bool redo, XLogRecPtr lsn, XLogRecord *record) if (record->xl_len > SizeOfHeapClean) { - OffsetNumber unbuf[BLCKSZ/sizeof(OffsetNumber)]; + OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)]; OffsetNumber *unused = unbuf; char *unend; ItemId lp; @@ -2084,9 +2087,10 @@ heap_xlog_insert(bool redo, XLogRecPtr lsn, XLogRecord *record) if (redo) { - struct { + struct + { HeapTupleHeaderData hdr; - char data[MaxTupleSize]; + char data[MaxTupleSize]; } tbuf; HeapTupleHeader htup; xl_heap_header xlhdr; @@ -2251,9 +2255,10 @@ newsame:; if (redo) { - struct { + struct + { HeapTupleHeaderData hdr; - char data[MaxTupleSize]; + char data[MaxTupleSize]; } tbuf; xl_heap_header xlhdr; int hsize; diff --git a/src/backend/access/heap/hio.c b/src/backend/access/heap/hio.c index 81a559b37e..44ecb3c8c7 100644 --- a/src/backend/access/heap/hio.c +++ b/src/backend/access/heap/hio.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Id: hio.c,v 1.42 2001/07/13 22:52:58 tgl Exp $ + * $Id: hio.c,v 1.43 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -83,7 +83,7 @@ RelationPutHeapTuple(Relation relation, * NOTE: it is unlikely, but not quite impossible, for otherBuffer to be the * same buffer we select for insertion of the new tuple (this could only * happen if space is freed in that page after heap_update finds there's not - * enough there). In that case, the page will be pinned and locked only once. + * enough there). In that case, the page will be pinned and locked only once. * * Note that we use LockPage(rel, 0) to lock relation for extension. * We can do this as long as in all other places we use page-level locking @@ -115,17 +115,19 @@ RelationGetBufferForTuple(Relation relation, Size len, if (otherBuffer != InvalidBuffer) otherBlock = BufferGetBlockNumber(otherBuffer); else - otherBlock = InvalidBlockNumber; /* just to keep compiler quiet */ + otherBlock = InvalidBlockNumber; /* just to keep compiler + * quiet */ /* * We first try to put the tuple on the same page we last inserted a * tuple on, as cached in the relcache entry. If that doesn't work, - * we ask the shared Free Space Map to locate a suitable page. Since + * we ask the shared Free Space Map to locate a suitable page. Since * the FSM's info might be out of date, we have to be prepared to loop * around and retry multiple times. (To insure this isn't an infinite - * loop, we must update the FSM with the correct amount of free space on - * each page that proves not to be suitable.) If the FSM has no record of - * a page with enough free space, we give up and extend the relation. + * loop, we must update the FSM with the correct amount of free space + * on each page that proves not to be suitable.) If the FSM has no + * record of a page with enough free space, we give up and extend the + * relation. */ targetBlock = relation->rd_targblock; @@ -137,6 +139,7 @@ RelationGetBufferForTuple(Relation relation, Size len, * target. */ targetBlock = GetPageWithFreeSpace(&relation->rd_node, len); + /* * If the FSM knows nothing of the rel, try the last page before * we give up and extend. This avoids one-tuple-per-page syndrome @@ -144,7 +147,7 @@ RelationGetBufferForTuple(Relation relation, Size len, */ if (targetBlock == InvalidBlockNumber) { - BlockNumber nblocks = RelationGetNumberOfBlocks(relation); + BlockNumber nblocks = RelationGetNumberOfBlocks(relation); if (nblocks > 0) targetBlock = nblocks - 1; @@ -154,9 +157,9 @@ RelationGetBufferForTuple(Relation relation, Size len, while (targetBlock != InvalidBlockNumber) { /* - * Read and exclusive-lock the target block, as well as the - * other block if one was given, taking suitable care with - * lock ordering and the possibility they are the same block. + * Read and exclusive-lock the target block, as well as the other + * block if one was given, taking suitable care with lock ordering + * and the possibility they are the same block. */ if (otherBuffer == InvalidBuffer) { @@ -184,9 +187,10 @@ RelationGetBufferForTuple(Relation relation, Size len, LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); LockBuffer(otherBuffer, BUFFER_LOCK_EXCLUSIVE); } + /* - * Now we can check to see if there's enough free space here. - * If so, we're done. + * Now we can check to see if there's enough free space here. If + * so, we're done. */ pageHeader = (Page) BufferGetPage(buffer); pageFreeSpace = PageGetFreeSpace(pageHeader); @@ -196,22 +200,22 @@ RelationGetBufferForTuple(Relation relation, Size len, relation->rd_targblock = targetBlock; return buffer; } + /* - * Not enough space, so we must give up our page locks and - * pin (if any) and prepare to look elsewhere. We don't care - * which order we unlock the two buffers in, so this can be - * slightly simpler than the code above. + * Not enough space, so we must give up our page locks and pin (if + * any) and prepare to look elsewhere. We don't care which order + * we unlock the two buffers in, so this can be slightly simpler + * than the code above. */ LockBuffer(buffer, BUFFER_LOCK_UNLOCK); if (otherBuffer == InvalidBuffer) - { ReleaseBuffer(buffer); - } else if (otherBlock != targetBlock) { LockBuffer(otherBuffer, BUFFER_LOCK_UNLOCK); ReleaseBuffer(buffer); } + /* * Update FSM as to condition of this page, and ask for another * page to try. @@ -225,9 +229,9 @@ RelationGetBufferForTuple(Relation relation, Size len, /* * Have to extend the relation. * - * 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 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. */ if (!relation->rd_myxactonly) LockPage(relation, 0, ExclusiveLock); @@ -236,20 +240,21 @@ RelationGetBufferForTuple(Relation relation, Size len, * XXX This does an lseek - rather expensive - but at the moment it is * the only way to accurately determine how many blocks are in a * relation. Is it worth keeping an accurate file length in shared - * memory someplace, rather than relying on the kernel to do it for us? + * memory someplace, rather than relying on the kernel to do it for + * us? */ buffer = ReadBuffer(relation, 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 (!relation->rd_myxactonly) UnlockPage(relation, 0, ExclusiveLock); /* - * We can be certain that locking the otherBuffer first is OK, - * since it must have a lower page number. + * We can be certain that locking the otherBuffer first is OK, since + * it must have a lower page number. */ if (otherBuffer != InvalidBuffer) LockBuffer(otherBuffer, BUFFER_LOCK_EXCLUSIVE); @@ -273,7 +278,7 @@ RelationGetBufferForTuple(Relation relation, Size len, * * XXX should we enter the new page into the free space map immediately, * or just keep it for this backend's exclusive use in the short run - * (until VACUUM sees it)? Seems to depend on whether you expect the + * (until VACUUM sees it)? Seems to depend on whether you expect the * current backend to make more insertions or not, which is probably a * good bet most of the time. So for now, don't add it to FSM yet. */ diff --git a/src/backend/access/heap/stats.c b/src/backend/access/heap/stats.c index 6dabf49e34..6f5dfbea14 100644 --- a/src/backend/access/heap/stats.c +++ b/src/backend/access/heap/stats.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/heap/Attic/stats.c,v 1.24 2001/03/22 06:16:07 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/heap/Attic/stats.c,v 1.25 2001/10/25 05:49:21 momjian Exp $ * * NOTES * initam should be moved someplace else. @@ -164,7 +164,6 @@ ResetHeapAccessStatistics() time(&stats->local_reset_timestamp); time(&stats->last_request_timestamp); } - #endif #ifdef NOT_USED @@ -200,7 +199,6 @@ GetHeapAccessStatistics() return stats; } - #endif #ifdef NOT_USED @@ -211,7 +209,6 @@ GetHeapAccessStatistics() void PrintHeapAccessStatistics(HeapAccessStatistics stats) { - /* * return nothing if stats aren't valid */ @@ -302,7 +299,6 @@ PrintHeapAccessStatistics(HeapAccessStatistics stats) printf("\n"); } - #endif #ifdef NOT_USED @@ -317,7 +313,6 @@ PrintAndFreeHeapAccessStatistics(HeapAccessStatistics stats) if (stats != NULL) pfree(stats); } - #endif /* ---------------------------------------------------------------- @@ -331,7 +326,6 @@ PrintAndFreeHeapAccessStatistics(HeapAccessStatistics stats) void initam(void) { - /* * initialize heap statistics. */ diff --git a/src/backend/access/heap/tuptoaster.c b/src/backend/access/heap/tuptoaster.c index dd881ca5f0..5ddefde8c7 100644 --- a/src/backend/access/heap/tuptoaster.c +++ b/src/backend/access/heap/tuptoaster.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/heap/tuptoaster.c,v 1.24 2001/08/10 18:57:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/heap/tuptoaster.c,v 1.25 2001/10/25 05:49:21 momjian Exp $ * * * INTERFACE ROUTINES @@ -74,14 +74,13 @@ heap_tuple_toast_attrs(Relation rel, HeapTuple newtup, HeapTuple oldtup) * external storage (possibly still in compressed format). * ---------- */ -varattrib * +varattrib * heap_tuple_fetch_attr(varattrib *attr) { varattrib *result; if (VARATT_IS_EXTERNAL(attr)) { - /* * This is an external stored plain value */ @@ -89,7 +88,6 @@ heap_tuple_fetch_attr(varattrib *attr) } else { - /* * This is a plain value inside of the main tuple - why am I * called? @@ -108,7 +106,7 @@ heap_tuple_fetch_attr(varattrib *attr) * or external storage. * ---------- */ -varattrib * +varattrib * heap_tuple_untoast_attr(varattrib *attr) { varattrib *result; @@ -135,7 +133,6 @@ heap_tuple_untoast_attr(varattrib *attr) } else { - /* * This is an external stored plain value */ @@ -144,7 +141,6 @@ heap_tuple_untoast_attr(varattrib *attr) } else if (VARATT_IS_COMPRESSED(attr)) { - /* * This is a compressed value inside of the main tuple */ @@ -181,8 +177,8 @@ toast_raw_datum_size(Datum value) if (VARATT_IS_COMPRESSED(attr)) { /* - * va_rawsize shows the original data size, whether the datum - * is external or not. + * va_rawsize shows the original data size, whether the datum is + * external or not. */ result = attr->va_content.va_compressed.va_rawsize + VARHDRSZ; } @@ -301,7 +297,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) if (oldtup != NULL) { - /* * For UPDATE get the old and new values of this attribute */ @@ -324,7 +319,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) old_value->va_content.va_external.va_toastrelid != new_value->va_content.va_external.va_toastrelid) { - /* * The old external store value isn't needed any more * after the update @@ -334,7 +328,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) } else { - /* * This attribute isn't changed by this update so we * reuse the original reference to the old value in @@ -348,7 +341,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) } else { - /* * For INSERT simply get the new value */ @@ -372,7 +364,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) */ if (att[i]->attlen == -1) { - /* * If the table's attribute says PLAIN always, force it so. */ @@ -400,7 +391,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) } else { - /* * Not a variable size attribute, plain storage always */ @@ -475,7 +465,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) } else { - /* * incompressible data, ignore on subsequent compression * passes @@ -588,7 +577,6 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup) } else { - /* * incompressible data, ignore on subsequent compression * passes @@ -776,9 +764,10 @@ toast_save_datum(Relation rel, Datum value) Datum t_values[3]; char t_nulls[3]; varattrib *result; - struct { - struct varlena hdr; - char data[TOAST_MAX_CHUNK_SIZE]; + struct + { + struct varlena hdr; + char data[TOAST_MAX_CHUNK_SIZE]; } chunk_data; int32 chunk_size; int32 chunk_seq = 0; @@ -851,12 +840,12 @@ toast_save_datum(Relation rel, Datum value) heap_insert(toastrel, toasttup); /* - * Create the index entry. We cheat a little here by not using + * Create the index entry. We cheat a little here by not using * FormIndexDatum: this relies on the knowledge that the index * columns are the same as the initial columns of the table. * - * Note also that there had better not be any user-created index - * on the TOAST table, since we don't bother to update anything else. + * Note also that there had better not be any user-created index on + * the TOAST table, since we don't bother to update anything else. */ idxres = index_insert(toastidx, t_values, t_nulls, &(toasttup->t_self), @@ -916,8 +905,8 @@ toast_delete_datum(Relation rel, Datum value) toastidx = index_open(toastrel->rd_rel->reltoastidxid); /* - * Setup a scan key to fetch from the index by va_valueid - * (we don't particularly care whether we see them in sequence or not) + * Setup a scan key to fetch from the index by va_valueid (we don't + * particularly care whether we see them in sequence or not) */ ScanKeyEntryInitialize(&toastkey, (bits16) 0, @@ -1096,5 +1085,4 @@ toast_fetch_datum(varattrib *attr) return result; } - #endif /* TUPLE_TOASTER_ACTIVE */ diff --git a/src/backend/access/index/genam.c b/src/backend/access/index/genam.c index 1115fb828b..b03690257c 100644 --- a/src/backend/access/index/genam.c +++ b/src/backend/access/index/genam.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/index/genam.c,v 1.28 2001/06/22 19:16:21 wieck Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/index/genam.c,v 1.29 2001/10/25 05:49:21 momjian Exp $ * * NOTES * many of the old access method routines have been turned into @@ -240,5 +240,4 @@ IndexScanRestorePosition(IndexScanDesc scan) scan->flags = 0x0; /* XXX should have a symbolic name */ } - #endif diff --git a/src/backend/access/index/indexam.c b/src/backend/access/index/indexam.c index 2a1d3294dd..8e1d5b8733 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.53 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/index/indexam.c,v 1.54 2001/10/25 05:49:21 momjian Exp $ * * INTERFACE ROUTINES * index_open - open an index relation by relationId @@ -241,9 +241,9 @@ index_beginscan(Relation relation, pgstat_initstats(&scan->xs_pgstat_info, relation); /* - * We want to look up the amgettuple procedure just once per scan, - * not once per index_getnext call. So do it here and save - * the fmgr info result in the scan descriptor. + * We want to look up the amgettuple procedure just once per scan, not + * once per index_getnext call. So do it here and save the fmgr info + * result in the scan descriptor. */ GET_SCAN_PROCEDURE(beginscan, amgettuple); fmgr_info(procedure, &scan->fn_getnext); @@ -342,8 +342,8 @@ index_getnext(IndexScanDesc scan, pgstat_count_index_scan(&scan->xs_pgstat_info); /* - * have the am's gettuple proc do all the work. - * index_beginscan already set up fn_getnext. + * have the am's gettuple proc do all the work. index_beginscan + * already set up fn_getnext. */ result = (RetrieveIndexResult) DatumGetPointer(FunctionCall2(&scan->fn_getnext, @@ -378,8 +378,8 @@ index_bulk_delete(Relation relation, result = (IndexBulkDeleteResult *) DatumGetPointer(OidFunctionCall3(procedure, PointerGetDatum(relation), - PointerGetDatum((Pointer) callback), - PointerGetDatum(callback_state))); + PointerGetDatum((Pointer) callback), + PointerGetDatum(callback_state))); return result; } diff --git a/src/backend/access/index/istrat.c b/src/backend/access/index/istrat.c index 568581fc18..88d1757e4c 100644 --- a/src/backend/access/index/istrat.c +++ b/src/backend/access/index/istrat.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/index/Attic/istrat.c,v 1.53 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/index/Attic/istrat.c,v 1.54 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -120,9 +120,9 @@ StrategyOperatorIsValid(StrategyOperator operator, StrategyNumber maxStrategy) { return (bool) - (PointerIsValid(operator) && - StrategyNumberIsInBounds(operator->strategy, maxStrategy) && - !(operator->flags & ~(SK_NEGATE | SK_COMMUTE))); + (PointerIsValid(operator) && + StrategyNumberIsInBounds(operator->strategy, maxStrategy) && + !(operator->flags & ~(SK_NEGATE | SK_COMMUTE))); } /* ---------------- @@ -196,7 +196,6 @@ StrategyEvaluationIsValid(StrategyEvaluation evaluation) } return true; } - #endif #ifdef NOT_USED @@ -255,7 +254,6 @@ StrategyTermEvaluate(StrategyTerm term, return result; } - #endif /* ---------------- @@ -453,7 +451,6 @@ RelationInvokeStrategy(Relation relation, /* not reached, just to make compiler happy */ return FALSE; } - #endif /* ---------------- @@ -552,7 +549,7 @@ IndexSupportInitialize(IndexStrategy indexStrategy, { for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++) { - Oid opclass = operatorClassObjectId[attIndex]; + Oid opclass = operatorClassObjectId[attIndex]; RegProcedure *loc; StrategyNumber support; @@ -562,7 +559,7 @@ IndexSupportInitialize(IndexStrategy indexStrategy, { tuple = SearchSysCache(AMPROCNUM, ObjectIdGetDatum(opclass), - Int16GetDatum(support+1), + Int16GetDatum(support + 1), 0, 0); if (HeapTupleIsValid(tuple)) { @@ -581,7 +578,7 @@ IndexSupportInitialize(IndexStrategy indexStrategy, /* Now load the strategy information for the index operators */ for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++) { - Oid opclass = operatorClassObjectId[attIndex]; + Oid opclass = operatorClassObjectId[attIndex]; StrategyMap map; StrategyNumber strategy; @@ -591,7 +588,7 @@ IndexSupportInitialize(IndexStrategy indexStrategy, for (strategy = 1; strategy <= maxStrategyNumber; strategy++) { - ScanKey mapentry = StrategyMapGetScanKeyEntry(map, strategy); + ScanKey mapentry = StrategyMapGetScanKeyEntry(map, strategy); tuple = SearchSysCache(AMOPSTRATEGY, ObjectIdGetDatum(opclass), @@ -643,5 +640,4 @@ IndexStrategyDisplay(IndexStrategy indexStrategy, } } } - #endif /* defined(ISTRATDEBUG) */ diff --git a/src/backend/access/nbtree/nbtcompare.c b/src/backend/access/nbtree/nbtcompare.c index b1affe2018..a4ba587053 100644 --- a/src/backend/access/nbtree/nbtcompare.c +++ b/src/backend/access/nbtree/nbtcompare.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtcompare.c,v 1.42 2001/05/03 19:00:36 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtcompare.c,v 1.43 2001/10/25 05:49:21 momjian Exp $ * * NOTES * @@ -25,7 +25,7 @@ * NOTE: although any negative int32 is acceptable for reporting "<", * and any positive int32 is acceptable for reporting ">", routines * that work on 32-bit or wider datatypes can't just return "a - b". - * That could overflow and give the wrong answer. Also, one should not + * That could overflow and give the wrong answer. Also, one should not * return INT_MIN to report "<", since some callers will negate the result. * * NOTE: it is critical that the comparison function impose a total order diff --git a/src/backend/access/nbtree/nbtinsert.c b/src/backend/access/nbtree/nbtinsert.c index bc250cd48e..1d3a7e82ab 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.86 2001/09/29 23:49:51 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtinsert.c,v 1.87 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -1100,7 +1100,7 @@ _bt_checksplitloc(FindSplitData *state, OffsetNumber firstright, * If we are not on the leaf level, we will be able to discard the key * data from the first item that winds up on the right page. */ - if (! state->is_leaf) + if (!state->is_leaf) rightfree += (int) firstrightitemsz - (int) (MAXALIGN(sizeof(BTItemData)) + sizeof(ItemIdData)); @@ -1115,7 +1115,8 @@ _bt_checksplitloc(FindSplitData *state, OffsetNumber firstright, { /* * On a rightmost page, try to equalize right free space with - * twice the left free space. See comments for _bt_findsplitloc. + * twice the left free space. See comments for + * _bt_findsplitloc. */ delta = (2 * leftfree) - rightfree; } @@ -1618,7 +1619,6 @@ _bt_fixlevel(Relation rel, Buffer buf, BlockNumber limit) for (;;) { - /* * Read up to 2 more child pages and look for pointers to them in * *saved* parent page diff --git a/src/backend/access/nbtree/nbtpage.c b/src/backend/access/nbtree/nbtpage.c index 376274c562..2e6eb20cd4 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.53 2001/07/15 22:48:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtpage.c,v 1.54 2001/10/25 05:49:21 momjian Exp $ * * NOTES * Postgres btree pages look like ordinary relation pages. The opaque @@ -153,7 +153,6 @@ _bt_getroot(Relation rel, int access) */ if (metad->btm_root == P_NONE) { - /* * Get, initialize, write, and leave a lock of the appropriate * type on the new root page. Since this is the first page in @@ -209,7 +208,6 @@ _bt_getroot(Relation rel, int access) } else { - /* * Metadata initialized by someone else. In order to * guarantee no deadlocks, we have to release the metadata @@ -237,7 +235,6 @@ _bt_getroot(Relation rel, int access) if (!P_ISROOT(rootopaque)) { - /* * It happened, but if root page splitter failed to create new * root page then we'll go in loop trying to call _bt_getroot @@ -402,7 +399,6 @@ _bt_wrtnorelbuf(Relation rel, Buffer buf) void _bt_pageinit(Page page, Size size) { - /* * Cargo_cult programming -- don't really need this to be zero, but * creating new pages is an infrequent occurrence and it makes me feel diff --git a/src/backend/access/nbtree/nbtree.c b/src/backend/access/nbtree/nbtree.c index b142645624..e49f06b1c3 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.82 2001/07/15 22:48:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtree.c,v 1.83 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,6 +37,7 @@ typedef struct bool haveDead; Relation heapRel; BTSpool *spool; + /* * spool2 is needed only when the index is an unique index. Dead * tuples are put into spool2 instead of spool in order to avoid @@ -58,11 +59,11 @@ bool FixBTree = true; static void _bt_restscan(IndexScanDesc scan); static void btbuildCallback(Relation index, - HeapTuple htup, - Datum *attdata, - char *nulls, - bool tupleIsAlive, - void *state); + HeapTuple htup, + Datum *attdata, + char *nulls, + bool tupleIsAlive, + void *state); /* @@ -134,6 +135,7 @@ btbuild(PG_FUNCTION_ARGS) if (buildstate.usefast) { buildstate.spool = _bt_spoolinit(index, indexInfo->ii_Unique); + /* * Different from spool, the uniqueness isn't checked for spool2. */ @@ -214,7 +216,7 @@ btbuildCallback(Relation index, bool tupleIsAlive, void *state) { - BTBuildState *buildstate = (BTBuildState *) state; + BTBuildState *buildstate = (BTBuildState *) state; IndexTuple itup; BTItem btitem; InsertIndexResult res; @@ -226,9 +228,9 @@ btbuildCallback(Relation index, btitem = _bt_formitem(itup); /* - * if we are doing bottom-up btree build, we insert the index into - * a spool file for subsequent processing. otherwise, we insert - * into the btree. + * if we are doing bottom-up btree build, we insert the index into a + * spool file for subsequent processing. otherwise, we insert into + * the btree. */ if (buildstate->usefast) { @@ -305,7 +307,6 @@ btgettuple(PG_FUNCTION_ARGS) if (ItemPointerIsValid(&(scan->currentItemData))) { - /* * Restore scan position using heap TID returned by previous call * to btgettuple(). _bt_restscan() re-grabs the read lock on the @@ -321,7 +322,7 @@ btgettuple(PG_FUNCTION_ARGS) * Save heap TID to use it in _bt_restscan. Then release the read * lock on the buffer so that we aren't blocking other backends. * - * NOTE: we do keep the pin on the buffer! This is essential to ensure + * NOTE: we do keep the pin on the buffer! This is essential to ensure * that someone else doesn't delete the index entry we are stopped on. */ if (res) @@ -362,7 +363,6 @@ btrescan(PG_FUNCTION_ARGS) #ifdef NOT_USED /* XXX surely it's wrong to ignore this? */ bool fromEnd = PG_GETARG_BOOL(1); - #endif ScanKey scankey = (ScanKey) PG_GETARG_POINTER(2); ItemPointer iptr; @@ -547,7 +547,7 @@ btbulkdelete(PG_FUNCTION_ARGS) IndexBulkDeleteCallback callback = (IndexBulkDeleteCallback) PG_GETARG_POINTER(1); void *callback_state = (void *) PG_GETARG_POINTER(2); IndexBulkDeleteResult *result; - BlockNumber num_pages; + BlockNumber num_pages; double tuples_removed; double num_index_tuples; RetrieveIndexResult res; @@ -559,15 +559,16 @@ btbulkdelete(PG_FUNCTION_ARGS) num_index_tuples = 0; /* - * We use a standard IndexScanDesc scan object, but to speed up the loop, - * we skip most of the wrapper layers of index_getnext and instead call - * _bt_step directly. This implies holding buffer lock on a target page - * throughout the loop over the page's tuples. Initially, we have a read - * lock acquired by _bt_step when we stepped onto the page. If we find - * a tuple we need to delete, we trade in the read lock for an exclusive - * write lock; after that, we hold the write lock until we step off the - * page (fortunately, _bt_relbuf doesn't care which kind of lock it's - * releasing). This should minimize the amount of work needed per page. + * We use a standard IndexScanDesc scan object, but to speed up the + * loop, we skip most of the wrapper layers of index_getnext and + * instead call _bt_step directly. This implies holding buffer lock + * on a target page throughout the loop over the page's tuples. + * Initially, we have a read lock acquired by _bt_step when we stepped + * onto the page. If we find a tuple we need to delete, we trade in + * the read lock for an exclusive write lock; after that, we hold the + * write lock until we step off the page (fortunately, _bt_relbuf + * doesn't care which kind of lock it's releasing). This should + * minimize the amount of work needed per page. */ scan = index_beginscan(rel, false, 0, (ScanKey) NULL); so = (BTScanOpaque) scan->opaque; @@ -579,7 +580,7 @@ btbulkdelete(PG_FUNCTION_ARGS) if (res != NULL) { Buffer buf; - BlockNumber lockedBlock = InvalidBlockNumber; + BlockNumber lockedBlock = InvalidBlockNumber; pfree(res); /* we have the buffer pinned and locked */ @@ -589,11 +590,11 @@ btbulkdelete(PG_FUNCTION_ARGS) do { Page page; - BlockNumber blkno; + BlockNumber blkno; OffsetNumber offnum; BTItem btitem; IndexTuple itup; - ItemPointer htup; + ItemPointer htup; /* current is the next index tuple */ blkno = ItemPointerGetBlockNumber(current); @@ -607,9 +608,10 @@ btbulkdelete(PG_FUNCTION_ARGS) { /* * If this is first deletion on this page, trade in read - * lock for a really-exclusive write lock. Then, step back - * one and re-examine the item, because someone else might - * have inserted an item while we weren't holding the lock! + * lock for a really-exclusive write lock. Then, step + * back one and re-examine the item, because someone else + * might have inserted an item while we weren't holding + * the lock! */ if (blkno != lockedBlock) { @@ -632,8 +634,8 @@ btbulkdelete(PG_FUNCTION_ARGS) * We need to back up the scan one item so that the next * cycle will re-examine the same offnum on this page. * - * For now, just hack the current-item index. Will need - * to be smarter when deletion includes removal of empty + * For now, just hack the current-item index. Will need to + * be smarter when deletion includes removal of empty * index pages. */ current->ip_posid--; diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c index 86ff810845..c1a82f2b85 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.68 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsearch.c,v 1.69 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -589,10 +589,10 @@ _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 - * greater than the scan key and we know that everything on later pages - * is less than or equal to scan key. - * + * possibly at the end of a page on which all the existing items are + * greater than the scan key and we know that everything on later + * pages is less 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 * the scan strategy to find the exact place to start the scan. diff --git a/src/backend/access/nbtree/nbtsort.c b/src/backend/access/nbtree/nbtsort.c index 2aca6bf7cf..4b327bff45 100644 --- a/src/backend/access/nbtree/nbtsort.c +++ b/src/backend/access/nbtree/nbtsort.c @@ -35,7 +35,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsort.c,v 1.60 2001/03/22 03:59:15 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsort.c,v 1.61 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -108,7 +108,7 @@ static void _bt_load(Relation index, BTSpool *btspool, BTSpool *btspool2); /* * create and initialize a spool structure */ -BTSpool * +BTSpool * _bt_spoolinit(Relation index, bool isunique) { BTSpool *btspool = (BTSpool *) palloc(sizeof(BTSpool)); @@ -354,7 +354,6 @@ _bt_buildadd(Relation index, BTPageState *state, BTItem bti) if (pgspc < btisz || pgspc < state->btps_full) { - /* * Item won't fit on this page, or we feel the page is full enough * already. Finish off the page and write it out. @@ -544,7 +543,6 @@ _bt_load(Relation index, BTSpool *btspool, BTSpool *btspool2) if (merge) { - /* * Another BTSpool for dead tuples exists. Now we have to merge * btspool and btspool2. diff --git a/src/backend/access/nbtree/nbtstrat.c b/src/backend/access/nbtree/nbtstrat.c index 4045496979..533af33681 100644 --- a/src/backend/access/nbtree/nbtstrat.c +++ b/src/backend/access/nbtree/nbtstrat.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/Attic/nbtstrat.c,v 1.14 2001/05/30 19:53:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/Attic/nbtstrat.c,v 1.15 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -134,5 +134,4 @@ _bt_invokestrat(Relation rel, return (RelationInvokeStrategy(rel, &BTEvaluationData, attno, strat, left, right)); } - #endif diff --git a/src/backend/access/nbtree/nbtutils.c b/src/backend/access/nbtree/nbtutils.c index 86d2e3cf8f..55c4c32300 100644 --- a/src/backend/access/nbtree/nbtutils.c +++ b/src/backend/access/nbtree/nbtutils.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtutils.c,v 1.46 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtutils.c,v 1.47 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -221,7 +221,6 @@ _bt_orderkeys(Relation relation, BTScanOpaque so) /* We can short-circuit most of the work if there's just one key */ if (numberOfKeys == 1) { - /* * We don't use indices for 'A is null' and 'A is not null' * currently and 'A < = > <> NULL' will always fail - so qual is @@ -317,7 +316,6 @@ _bt_orderkeys(Relation relation, BTScanOpaque so) } else { - /* * No "=" for this key, so we're done with required keys */ diff --git a/src/backend/access/rtree/rtree.c b/src/backend/access/rtree/rtree.c index 42878248b0..0e8305bdfb 100644 --- a/src/backend/access/rtree/rtree.c +++ b/src/backend/access/rtree/rtree.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtree.c,v 1.65 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtree.c,v 1.66 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -58,9 +58,9 @@ typedef struct SPLITVEC /* for sorting tuples by cost, for picking split */ typedef struct SPLITCOST { - OffsetNumber offset_number; - float cost_differential; - bool choose_left; + OffsetNumber offset_number; + float cost_differential; + bool choose_left; } SPLITCOST; typedef struct RTSTATE @@ -79,11 +79,11 @@ typedef struct /* non-export function prototypes */ static void rtbuildCallback(Relation index, - HeapTuple htup, - Datum *attdata, - char *nulls, - bool tupleIsAlive, - void *state); + HeapTuple htup, + Datum *attdata, + char *nulls, + bool tupleIsAlive, + void *state); static InsertIndexResult rtdoinsert(Relation r, IndexTuple itup, RTSTATE *rtstate); static void rttighten(Relation r, RTSTACK *stk, Datum datum, int att_size, @@ -100,7 +100,7 @@ static OffsetNumber choose(Relation r, Page p, IndexTuple it, RTSTATE *rtstate); static int nospace(Page p, IndexTuple it); static void initRtstate(RTSTATE *rtstate, Relation index); -static int qsort_comp_splitcost(const void *a, const void *b); +static int qsort_comp_splitcost(const void *a, const void *b); /* @@ -178,7 +178,7 @@ rtbuildCallback(Relation index, bool tupleIsAlive, void *state) { - RTBuildState *buildstate = (RTBuildState *) state; + RTBuildState *buildstate = (RTBuildState *) state; IndexTuple itup; InsertIndexResult res; @@ -194,11 +194,11 @@ rtbuildCallback(Relation index, } /* - * Since we already have the index relation locked, we call - * rtdoinsert directly. Normal access method calls dispatch - * through rtinsert, which locks the relation for write. This is - * the right thing to do if you're inserting single tups, but not - * when you're initializing the whole index at once. + * Since we already have the index relation locked, we call rtdoinsert + * directly. Normal access method calls dispatch through rtinsert, + * which locks the relation for write. This is the right thing to do + * if you're inserting single tups, but not when you're initializing + * the whole index at once. */ res = rtdoinsert(index, itup, &buildstate->rtState); @@ -223,6 +223,7 @@ rtinsert(PG_FUNCTION_ARGS) Datum *datum = (Datum *) PG_GETARG_POINTER(1); char *nulls = (char *) PG_GETARG_POINTER(2); ItemPointer ht_ctid = (ItemPointer) PG_GETARG_POINTER(3); + #ifdef NOT_USED Relation heapRel = (Relation) PG_GETARG_POINTER(4); #endif @@ -249,7 +250,7 @@ rtinsert(PG_FUNCTION_ARGS) /* * Since rtree is not marked "amconcurrent" in pg_am, caller should - * have acquired exclusive lock on index relation. We need no locking + * have acquired exclusive lock on index relation. We need no locking * here. */ @@ -376,9 +377,8 @@ rttighten(Relation r, PointerGetDatum(&newd_size)); /* - * If newd_size == 0 we have degenerate rectangles, so we - * don't know if there was any change, so we have to - * assume there was. + * If newd_size == 0 we have degenerate rectangles, so we don't know + * if there was any change, so we have to assume there was. */ if ((newd_size == 0) || (newd_size != old_size)) { @@ -386,7 +386,6 @@ rttighten(Relation r, if (td->attrs[0]->attlen < 0) { - /* * This is an internal page, so 'oldud' had better be a union * (constant-length) key, too. (See comment below.) @@ -500,10 +499,10 @@ rtdosplit(Relation r, res = (InsertIndexResult) palloc(sizeof(InsertIndexResultData)); /* - * spl_left contains a list of the offset numbers of the - * tuples that will go to the left page. For each offset - * number, get the tuple item, then add the item to the - * left page. Similarly for the right side. + * spl_left contains a list of the offset numbers of the tuples that + * will go to the left page. For each offset number, get the tuple + * item, then add the item to the left page. Similarly for the right + * side. */ /* fill left node */ @@ -527,7 +526,7 @@ rtdosplit(Relation r, if (i == newitemoff) ItemPointerSet(&(res->pointerData), lbknum, leftoff); - spl_left++; /* advance in left split vector */ + spl_left++; /* advance in left split vector */ } /* fill right node */ @@ -551,7 +550,7 @@ rtdosplit(Relation r, if (i == newitemoff) ItemPointerSet(&(res->pointerData), rbknum, rightoff); - spl_right++; /* advance in right split vector */ + spl_right++; /* advance in right split vector */ } /* Make sure we consumed all of the split vectors, and release 'em */ @@ -764,9 +763,10 @@ rtpicksplit(Relation r, right_avail_space; int total_num_tuples, num_tuples_without_seeds, - max_after_split; /* in Guttman's lingo, (M - m) */ - float diff; /* diff between cost of putting tuple left or right */ - SPLITCOST *cost_vector; + max_after_split; /* in Guttman's lingo, (M - m) */ + float diff; /* diff between cost of putting tuple left + * or right */ + SPLITCOST *cost_vector; int n; /* @@ -852,7 +852,6 @@ rtpicksplit(Relation r, if (firsttime) { - /* * There is no possible split except to put the new item on its * own page. Since we still have to compute the union rectangles, @@ -885,25 +884,25 @@ rtpicksplit(Relation r, /* * Now split up the regions between the two seeds. * - * The cost_vector array will contain hints for determining where - * each tuple should go. Each record in the array will contain - * a boolean, choose_left, that indicates which node the tuple - * prefers to be on, and the absolute difference in cost between - * putting the tuple in its favored node and in the other node. + * The cost_vector array will contain hints for determining where each + * tuple should go. Each record in the array will contain a boolean, + * choose_left, that indicates which node the tuple prefers to be on, + * and the absolute difference in cost between putting the tuple in + * its favored node and in the other node. * * Later, we will sort the cost_vector in descending order by cost - * difference, and consider the tuples in that order for - * placement. That way, the tuples that *really* want to be in - * one node or the other get to choose first, and the tuples that - * don't really care choose last. + * difference, and consider the tuples in that order for placement. + * That way, the tuples that *really* want to be in one node or the + * other get to choose first, and the tuples that don't really care + * choose last. * - * First, build the cost_vector array. The new index tuple will - * also be handled in this loop, and represented in the array, - * with i==newitemoff. + * First, build the cost_vector array. The new index tuple will also be + * handled in this loop, and represented in the array, with + * i==newitemoff. * - * In the case of variable size tuples it is possible that we only - * have the two seeds and no other tuples, in which case we don't - * do any of this cost_vector stuff. + * In the case of variable size tuples it is possible that we only have + * the two seeds and no other tuples, in which case we don't do any of + * this cost_vector stuff. */ /* to keep compiler quiet */ @@ -943,21 +942,21 @@ rtpicksplit(Relation r, } /* - * Sort the array. The function qsort_comp_splitcost is - * set up "backwards", to provided descending order. + * Sort the array. The function qsort_comp_splitcost is set up + * "backwards", to provided descending order. */ qsort(cost_vector, num_tuples_without_seeds, sizeof(SPLITCOST), &qsort_comp_splitcost); } /* - * Now make the final decisions about where each tuple will go, - * and build the vectors to return in the SPLITVEC record. + * Now make the final decisions about where each tuple will go, and + * build the vectors to return in the SPLITVEC record. * - * The cost_vector array contains (descriptions of) all the - * tuples, in the order that we want to consider them, so we - * we just iterate through it and place each tuple in left - * or right nodes, according to the criteria described below. + * The cost_vector array contains (descriptions of) all the tuples, in + * the order that we want to consider them, so we we just iterate + * through it and place each tuple in left or right nodes, according + * to the criteria described below. */ left = v->spl_left; @@ -965,9 +964,9 @@ rtpicksplit(Relation r, right = v->spl_right; v->spl_nright = 0; - /* Place the seeds first. - * left avail space, left union, right avail space, and right - * union have already been adjusted for the seeds. + /* + * Place the seeds first. left avail space, left union, right avail + * space, and right union have already been adjusted for the seeds. */ *left++ = seed_1; @@ -983,8 +982,8 @@ rtpicksplit(Relation r, choose_left; /* - * We need to figure out which page needs the least - * enlargement in order to store the item. + * We need to figure out which page needs the least enlargement in + * order to store the item. */ i = cost_vector[n].offset_number; @@ -1019,22 +1018,22 @@ rtpicksplit(Relation r, * the new item.) * * Guttman's algorithm actually has two factors to consider (in - * order): 1. if one node has so many tuples already assigned to + * order): 1. if one node has so many tuples already assigned to * it that the other needs all the rest in order to satisfy the - * condition that neither node has fewer than m tuples, then - * that is decisive; 2. otherwise, choose the page that shows - * the smaller enlargement of its union area. + * condition that neither node has fewer than m tuples, then that + * is decisive; 2. otherwise, choose the page that shows the + * smaller enlargement of its union area. * - * I have chosen m = M/2, where M is the maximum number of - * tuples on a page. (Actually, this is only strictly - * true for fixed size tuples. For variable size tuples, - * there still might have to be only one tuple on a page, - * if it is really big. But even with variable size - * tuples we still try to get m as close as possible to M/2.) + * I have chosen m = M/2, where M is the maximum number of tuples on + * a page. (Actually, this is only strictly true for fixed size + * tuples. For variable size tuples, there still might have to be + * only one tuple on a page, if it is really big. But even with + * variable size tuples we still try to get m as close as possible + * to M/2.) * - * The question of which page shows the smaller enlargement of - * its union area has already been answered, and the answer - * stored in the choose_left field of the SPLITCOST record. + * The question of which page shows the smaller enlargement of its + * union area has already been answered, and the answer stored in + * the choose_left field of the SPLITCOST record. */ left_feasible = (left_avail_space >= item_1_sz && ((left_avail_space - item_1_sz) >= newitemsz || @@ -1045,10 +1044,10 @@ rtpicksplit(Relation r, if (left_feasible && right_feasible) { /* - * Both feasible, use Guttman's algorithm. - * First check the m condition described above, and if - * that doesn't apply, choose the page with the smaller - * enlargement of its union area. + * Both feasible, use Guttman's algorithm. First check the m + * condition described above, and if that doesn't apply, + * choose the page with the smaller enlargement of its union + * area. */ if (v->spl_nleft > max_after_split) choose_left = false; @@ -1064,7 +1063,7 @@ rtpicksplit(Relation r, else { elog(ERROR, "rtpicksplit: failed to find a workable page split"); - choose_left = false;/* keep compiler quiet */ + choose_left = false; /* keep compiler quiet */ } if (choose_left) @@ -1090,9 +1089,7 @@ rtpicksplit(Relation r, } if (num_tuples_without_seeds > 0) - { pfree(cost_vector); - } *left = *right = InvalidOffsetNumber; /* add ending sentinels */ @@ -1189,7 +1186,7 @@ rtbulkdelete(PG_FUNCTION_ARGS) IndexBulkDeleteCallback callback = (IndexBulkDeleteCallback) PG_GETARG_POINTER(1); void *callback_state = (void *) PG_GETARG_POINTER(2); IndexBulkDeleteResult *result; - BlockNumber num_pages; + BlockNumber num_pages; double tuples_removed; double num_index_tuples; RetrieveIndexResult res; @@ -1200,7 +1197,7 @@ rtbulkdelete(PG_FUNCTION_ARGS) /* * Since rtree is not marked "amconcurrent" in pg_am, caller should - * have acquired exclusive lock on index relation. We need no locking + * have acquired exclusive lock on index relation. We need no locking * here. */ @@ -1279,9 +1276,10 @@ initRtstate(RTSTATE *rtstate, Relation index) static int qsort_comp_splitcost(const void *a, const void *b) { - float diff = - ((SPLITCOST *)a)->cost_differential - - ((SPLITCOST *)b)->cost_differential; + float diff = + ((SPLITCOST *) a)->cost_differential - + ((SPLITCOST *) b)->cost_differential; + if (diff < 0) return 1; else if (diff > 0) @@ -1342,7 +1340,6 @@ _rtdump(Relation r) ReleaseBuffer(buf); } } - #endif /* defined RTDEBUG */ void diff --git a/src/backend/access/rtree/rtscan.c b/src/backend/access/rtree/rtscan.c index 1311cfdc29..c6883fd041 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.38 2001/07/15 22:48:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtscan.c,v 1.39 2001/10/25 05:49:21 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -380,7 +380,6 @@ adjustiptr(IndexScanDesc s, } else { - /* * remember that we're before the current * tuple diff --git a/src/backend/access/rtree/rtstrat.c b/src/backend/access/rtree/rtstrat.c index 74ee6a39a4..41de4a4e3e 100644 --- a/src/backend/access/rtree/rtstrat.c +++ b/src/backend/access/rtree/rtstrat.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtstrat.c,v 1.17 2001/05/30 19:53:40 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/rtree/Attic/rtstrat.c,v 1.18 2001/10/25 05:49:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -163,7 +163,7 @@ static StrategyExpression RTEvaluationExpressions[RTNStrategies] = { NULL, /* express overlap */ NULL, /* express overright */ NULL, /* express right */ - (StrategyExpression) RTEqualExpressionData, /* express same */ + (StrategyExpression) RTEqualExpressionData, /* express same */ NULL, /* express contains */ NULL /* express contained-by */ }; @@ -221,7 +221,6 @@ RelationInvokeRTStrategy(Relation r, return (RelationInvokeStrategy(r, &RTEvaluationData, attnum, s, left, right)); } - #endif RegProcedure diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index cd83da93ea..1436b32aa1 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -13,7 +13,7 @@ * Portions Copyright (c) 1996-2001, 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.4 2001/09/29 04:02:21 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/clog.c,v 1.5 2001/10/25 05:49:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -33,7 +33,7 @@ /* * Defines for CLOG page and segment sizes. A page is the same BLCKSZ - * as is used everywhere else in Postgres. The CLOG segment size can be + * as is used everywhere else in Postgres. The CLOG segment size can be * chosen somewhat arbitrarily; we make it 1 million transactions by default, * or 256Kb. * @@ -48,15 +48,15 @@ /* We need two bits per xact, so four xacts fit in a byte */ #define CLOG_BITS_PER_XACT 2 -#define CLOG_XACTS_PER_BYTE 4 -#define CLOG_XACTS_PER_PAGE (CLOG_BLCKSZ * CLOG_XACTS_PER_BYTE) +#define CLOG_XACTS_PER_BYTE 4 +#define CLOG_XACTS_PER_PAGE (CLOG_BLCKSZ * CLOG_XACTS_PER_BYTE) #define CLOG_XACT_BITMASK ((1 << CLOG_BITS_PER_XACT) - 1) #define CLOG_XACTS_PER_SEGMENT 0x100000 #define CLOG_PAGES_PER_SEGMENT (CLOG_XACTS_PER_SEGMENT / CLOG_XACTS_PER_PAGE) #define TransactionIdToPage(xid) ((xid) / (TransactionId) CLOG_XACTS_PER_PAGE) -#define TransactionIdToPgIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) +#define TransactionIdToPgIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_PAGE) #define TransactionIdToByte(xid) (TransactionIdToPgIndex(xid) / CLOG_XACTS_PER_BYTE) #define TransactionIdToBIndex(xid) ((xid) % (TransactionId) CLOG_XACTS_PER_BYTE) @@ -101,15 +101,15 @@ * the control lock. * * As with the regular buffer manager, it is possible for another process - * to re-dirty a page that is currently being written out. This is handled + * to re-dirty a page that is currently being written out. This is handled * by setting the page's state from WRITE_IN_PROGRESS to DIRTY. The writing * process must notice this and not mark the page CLEAN when it's done. * * XLOG interactions: this module generates an XLOG record whenever a new - * CLOG page is initialized to zeroes. Other writes of CLOG come from + * CLOG page is initialized to zeroes. Other writes of CLOG come from * recording of transaction commit or abort in xact.c, which generates its * own XLOG records for these events and will re-perform the status update - * on redo; so we need make no additional XLOG entry here. Also, the XLOG + * on redo; so we need make no additional XLOG entry here. Also, the XLOG * is guaranteed flushed through the XLOG commit record before we are called * to log a commit, so the WAL rule "write xlog before data" is satisfied * automatically for commits, and we don't really care for aborts. Therefore, @@ -120,11 +120,13 @@ typedef enum { - CLOG_PAGE_EMPTY, /* CLOG buffer is not in use */ - CLOG_PAGE_READ_IN_PROGRESS, /* CLOG page is being read in */ - CLOG_PAGE_CLEAN, /* CLOG page is valid and not dirty */ - CLOG_PAGE_DIRTY, /* CLOG page is valid but needs write */ - CLOG_PAGE_WRITE_IN_PROGRESS /* CLOG page is being written out in */ + CLOG_PAGE_EMPTY,/* CLOG buffer is not in use */ + CLOG_PAGE_READ_IN_PROGRESS, /* CLOG page is being read + * in */ + CLOG_PAGE_CLEAN,/* CLOG page is valid and not dirty */ + CLOG_PAGE_DIRTY,/* CLOG page is valid but needs write */ + CLOG_PAGE_WRITE_IN_PROGRESS /* CLOG page is being + * written out in */ } ClogPageStatus; /* @@ -134,14 +136,15 @@ typedef struct ClogCtlData { /* * Info for each buffer slot. Page number is undefined when status is - * EMPTY. lru_count is essentially the number of operations since last - * use of this page; the page with highest lru_count is the best candidate - * to replace. + * EMPTY. lru_count is essentially the number of operations since + * last use of this page; the page with highest lru_count is the best + * candidate to replace. */ char *page_buffer[NUM_CLOG_BUFFERS]; - ClogPageStatus page_status[NUM_CLOG_BUFFERS]; + ClogPageStatus page_status[NUM_CLOG_BUFFERS]; int page_number[NUM_CLOG_BUFFERS]; - unsigned int page_lru_count[NUM_CLOG_BUFFERS]; + unsigned int page_lru_count[NUM_CLOG_BUFFERS]; + /* * latest_page_number is the page number of the current end of the * CLOG; this is not critical data, since we use it only to avoid @@ -157,7 +160,7 @@ static ClogCtlData *ClogCtl = NULL; * The value is automatically inherited by backends via fork, and * doesn't need to be in shared memory. */ -static LWLockId ClogBufferLocks[NUM_CLOG_BUFFERS]; /* Per-buffer I/O locks */ +static LWLockId ClogBufferLocks[NUM_CLOG_BUFFERS]; /* Per-buffer I/O locks */ /* * ClogDir is set during CLOGShmemInit and does not change thereafter. @@ -166,7 +169,7 @@ static LWLockId ClogBufferLocks[NUM_CLOG_BUFFERS]; /* Per-buffer I/O locks */ */ static char ClogDir[MAXPGPATH]; -#define ClogFileName(path, seg) \ +#define ClogFileName(path, seg) \ snprintf(path, MAXPGPATH, "%s/%04X", ClogDir, seg) /* @@ -430,7 +433,7 @@ ReadCLOGPage(int pageno) LWLockAcquire(CLogControlLock, LW_EXCLUSIVE); Assert(ClogCtl->page_number[slotno] == pageno && - ClogCtl->page_status[slotno] == CLOG_PAGE_READ_IN_PROGRESS); + ClogCtl->page_status[slotno] == CLOG_PAGE_READ_IN_PROGRESS); ClogCtl->page_status[slotno] = CLOG_PAGE_CLEAN; @@ -447,7 +450,7 @@ ReadCLOGPage(int pageno) * * NOTE: only one write attempt is made here. Hence, it is possible that * the page is still dirty at exit (if someone else re-dirtied it during - * the write). However, we *do* attempt a fresh write even if the page + * the write). However, we *do* attempt a fresh write even if the page * is already being written; this is for checkpoints. * * Control lock must be held at entry, and will be held at exit. @@ -455,7 +458,7 @@ ReadCLOGPage(int pageno) static void WriteCLOGPage(int slotno) { - int pageno; + int pageno; /* Do nothing if page does not need writing */ if (ClogCtl->page_status[slotno] != CLOG_PAGE_DIRTY && @@ -489,11 +492,12 @@ WriteCLOGPage(int slotno) * update on this page will mark it dirty again. NB: we are assuming * that read/write of the page status field is atomic, since we change * the state while not holding control lock. However, we cannot set - * this state any sooner, or we'd possibly fool a previous writer - * into thinking he's successfully dumped the page when he hasn't. - * (Scenario: other writer starts, page is redirtied, we come along and - * set WRITE_IN_PROGRESS again, other writer completes and sets CLEAN - * because redirty info has been lost, then we think it's clean too.) + * this state any sooner, or we'd possibly fool a previous writer into + * thinking he's successfully dumped the page when he hasn't. + * (Scenario: other writer starts, page is redirtied, we come along + * and set WRITE_IN_PROGRESS again, other writer completes and sets + * CLEAN because redirty info has been lost, then we think it's clean + * too.) */ ClogCtl->page_status[slotno] = CLOG_PAGE_WRITE_IN_PROGRESS; @@ -523,7 +527,7 @@ WriteCLOGPage(int slotno) static void CLOGPhysicalReadPage(int pageno, int slotno) { - int segno = pageno / CLOG_PAGES_PER_SEGMENT; + int segno = pageno / CLOG_PAGES_PER_SEGMENT; int rpageno = pageno % CLOG_PAGES_PER_SEGMENT; int offset = rpageno * CLOG_BLCKSZ; char path[MAXPGPATH]; @@ -533,9 +537,9 @@ CLOGPhysicalReadPage(int pageno, int slotno) /* * In a crash-and-restart situation, it's possible for us to receive - * commands to set the commit status of transactions whose bits are - * in already-truncated segments of the commit log (see notes in - * CLOGPhysicalWritePage). Hence, if we are InRecovery, allow the + * commands to set the commit status of transactions whose bits are in + * already-truncated segments of the commit log (see notes in + * CLOGPhysicalWritePage). Hence, if we are InRecovery, allow the * case where the file doesn't exist, and return zeroes instead. */ fd = BasicOpenFile(path, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR); @@ -569,7 +573,7 @@ CLOGPhysicalReadPage(int pageno, int slotno) static void CLOGPhysicalWritePage(int pageno, int slotno) { - int segno = pageno / CLOG_PAGES_PER_SEGMENT; + int segno = pageno / CLOG_PAGES_PER_SEGMENT; int rpageno = pageno % CLOG_PAGES_PER_SEGMENT; int offset = rpageno * CLOG_BLCKSZ; char path[MAXPGPATH]; @@ -578,16 +582,17 @@ CLOGPhysicalWritePage(int pageno, int slotno) ClogFileName(path, segno); /* - * If the file doesn't already exist, we should create it. It is 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 ZeroCLOGPage 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 CLOGPhysicalReadPage.) + * If the file doesn't already exist, we should create it. It is + * 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 + * ZeroCLOGPage 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 CLOGPhysicalReadPage.) */ fd = BasicOpenFile(path, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR); if (fd < 0) @@ -649,16 +654,15 @@ SelectLRUCLOGPage(int pageno) } /* - * If we find any EMPTY slot, just select that one. - * Else locate the least-recently-used slot that isn't the - * latest CLOG page. + * If we find any EMPTY slot, just select that one. Else locate + * the least-recently-used slot that isn't the latest CLOG page. */ for (slotno = 0; slotno < NUM_CLOG_BUFFERS; slotno++) { if (ClogCtl->page_status[slotno] == CLOG_PAGE_EMPTY) return slotno; if (ClogCtl->page_lru_count[slotno] > bestcount && - ClogCtl->page_number[slotno] != ClogCtl->latest_page_number) + ClogCtl->page_number[slotno] != ClogCtl->latest_page_number) { bestslot = slotno; bestcount = ClogCtl->page_lru_count[slotno]; @@ -672,10 +676,10 @@ SelectLRUCLOGPage(int pageno) return bestslot; /* - * 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 ReadCLOGPage to wait for the read to - * complete. + * 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 ReadCLOGPage to wait for + * the read to complete. */ if (ClogCtl->page_status[bestslot] == CLOG_PAGE_READ_IN_PROGRESS) (void) ReadCLOGPage(ClogCtl->page_number[bestslot]); @@ -683,9 +687,9 @@ SelectLRUCLOGPage(int pageno) WriteCLOGPage(bestslot); /* - * Now loop back and try again. This is the easiest way of dealing - * with corner cases such as the victim page being re-dirtied while - * we wrote it. + * Now loop back and try again. This is the easiest way of + * dealing with corner cases such as the victim page being + * re-dirtied while we wrote it. */ } } @@ -736,6 +740,7 @@ CheckPointCLOG(void) for (slotno = 0; slotno < NUM_CLOG_BUFFERS; slotno++) { WriteCLOGPage(slotno); + /* * We cannot assert that the slot is clean now, since another * process might have re-dirtied it already. That's okay. @@ -782,13 +787,13 @@ ExtendCLOG(TransactionId newestXact) * Remove all CLOG segments before the one holding the passed transaction ID * * When this is called, we know that the database logically contains no - * reference to transaction IDs older than oldestXact. However, we must + * reference to transaction IDs older than oldestXact. However, we must * not truncate the CLOG until we have performed a checkpoint, to ensure * that no such references remain on disk either; else a crash just after * the truncation might leave us with a problem. Since CLOG segments hold * a large number of transactions, the opportunity to actually remove a * segment is fairly rare, and so it seems best not to do the checkpoint - * unless we have confirmed that there is a removable segment. Therefore + * unless we have confirmed that there is a removable segment. Therefore * we issue the checkpoint command here, not in higher-level code as might * seem cleaner. */ @@ -813,15 +818,16 @@ TruncateCLOG(TransactionId oldestXact) /* * Scan CLOG 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.) + * should have been flushed already during the checkpoint, we're just + * being extra careful here.) */ LWLockAcquire(CLogControlLock, LW_EXCLUSIVE); restart:; + /* - * While we are holding the lock, make an important safety check: - * the planned cutoff point must be <= the current CLOG endpoint page. + * While we are holding the lock, make an important safety check: the + * planned cutoff point must be <= the current CLOG endpoint page. * Otherwise we have already wrapped around, and proceeding with the * truncation would risk removing the current CLOG segment. */ @@ -838,6 +844,7 @@ restart:; continue; if (!CLOGPagePrecedes(ClogCtl->page_number[slotno], cutoffPage)) continue; + /* * If page is CLEAN, just change state to EMPTY (expected case). */ @@ -846,6 +853,7 @@ restart:; ClogCtl->page_status[slotno] = CLOG_PAGE_EMPTY; continue; } + /* * Hmm, we have (or may have) I/O operations acting on the page, * so we've got to wait for them to finish and then start again. @@ -928,9 +936,11 @@ CLOGPagePrecedes(int page1, int page2) TransactionId xid1; TransactionId xid2; - xid1 = (TransactionId) page1 * CLOG_XACTS_PER_PAGE; + xid1 = (TransactionId) page1 *CLOG_XACTS_PER_PAGE; + xid1 += FirstNormalTransactionId; - xid2 = (TransactionId) page2 * CLOG_XACTS_PER_PAGE; + xid2 = (TransactionId) page2 *CLOG_XACTS_PER_PAGE; + xid2 += FirstNormalTransactionId; return TransactionIdPrecedes(xid1, xid2); @@ -966,8 +976,8 @@ clog_redo(XLogRecPtr lsn, XLogRecord *record) if (info == CLOG_ZEROPAGE) { - int pageno; - int slotno; + int pageno; + int slotno; memcpy(&pageno, XLogRecGetData(record), sizeof(int)); @@ -993,7 +1003,7 @@ clog_desc(char *buf, uint8 xl_info, char *rec) if (info == CLOG_ZEROPAGE) { - int pageno; + int pageno; memcpy(&pageno, rec, sizeof(int)); sprintf(buf + strlen(buf), "zeropage: %d", pageno); diff --git a/src/backend/access/transam/transam.c b/src/backend/access/transam/transam.c index 2a73c045b7..bb94fc27a1 100644 --- a/src/backend/access/transam/transam.c +++ b/src/backend/access/transam/transam.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/transam/transam.c,v 1.48 2001/08/26 16:55:59 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/transam.c,v 1.49 2001/10/25 05:49:22 momjian Exp $ * * NOTES * This file contains the high level access-method interface to the @@ -32,7 +32,7 @@ static void TransactionLogUpdate(TransactionId transactionId, * ---------------- */ static TransactionId cachedTestXid = InvalidTransactionId; -static XidStatus cachedTestXidStatus; +static XidStatus cachedTestXidStatus; /* ---------------------------------------------------------------- @@ -56,8 +56,8 @@ TransactionLogTest(TransactionId transactionId, /* transaction id to test */ XidStatus xidstatus; /* recorded status of xid */ /* - * Before going to the commit log manager, check our single item cache to - * see if we didn't just check the transaction status a moment ago. + * Before going to the commit log manager, check our single item cache + * to see if we didn't just check the transaction status a moment ago. */ if (TransactionIdEquals(transactionId, cachedTestXid)) return (status == cachedTestXidStatus); @@ -65,7 +65,7 @@ TransactionLogTest(TransactionId transactionId, /* transaction id to test */ /* * Also, check to see if the transaction ID is a permanent one. */ - if (! TransactionIdIsNormal(transactionId)) + if (!TransactionIdIsNormal(transactionId)) { if (TransactionIdEquals(transactionId, BootstrapTransactionId)) return (status == TRANSACTION_STATUS_COMMITTED); @@ -77,18 +77,18 @@ TransactionLogTest(TransactionId transactionId, /* transaction id to test */ /* * Get the status. */ - xidstatus = TransactionIdGetStatus(transactionId); - - /* - * DO NOT cache status for unfinished transactions! - */ - if (xidstatus != TRANSACTION_STATUS_IN_PROGRESS) - { - TransactionIdStore(transactionId, &cachedTestXid); - cachedTestXidStatus = xidstatus; - } - - return (status == xidstatus); + xidstatus = TransactionIdGetStatus(transactionId); + + /* + * DO NOT cache status for unfinished transactions! + */ + if (xidstatus != TRANSACTION_STATUS_IN_PROGRESS) + { + TransactionIdStore(transactionId, &cachedTestXid); + cachedTestXidStatus = xidstatus; + } + + return (status == xidstatus); } /* -------------------------------- @@ -197,7 +197,7 @@ TransactionIdIsInProgress(TransactionId transactionId) return TransactionLogTest(transactionId, TRANSACTION_STATUS_IN_PROGRESS); } -#endif /* NOT_USED */ +#endif /* NOT_USED */ /* -------------------------------- * TransactionId Commit @@ -246,7 +246,7 @@ TransactionIdPrecedes(TransactionId id1, TransactionId id2) { /* * If either ID is a permanent XID then we can just do unsigned - * comparison. If both are normal, do a modulo-2^31 comparison. + * comparison. If both are normal, do a modulo-2^31 comparison. */ int32 diff; diff --git a/src/backend/access/transam/varsup.c b/src/backend/access/transam/varsup.c index 048080a180..5a56f47e06 100644 --- a/src/backend/access/transam/varsup.c +++ b/src/backend/access/transam/varsup.c @@ -6,7 +6,7 @@ * Copyright (c) 2000, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/access/transam/varsup.c,v 1.46 2001/09/29 04:02:21 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/varsup.c,v 1.47 2001/10/25 05:49:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -32,7 +32,7 @@ VariableCache ShmemVariableCache = NULL; TransactionId GetNewTransactionId(void) { - TransactionId xid; + TransactionId xid; /* * During bootstrap initialization, we return the special bootstrap @@ -48,32 +48,32 @@ GetNewTransactionId(void) TransactionIdAdvance(ShmemVariableCache->nextXid); /* - * If we have just allocated the first XID of a new page of the - * commit log, zero out that commit-log page before returning. - * We must do this while holding XidGenLock, else another xact could - * acquire and commit a later XID before we zero the page. Fortunately, - * a page of the commit log holds 32K or more transactions, so we don't - * have to do this very often. + * If we have just allocated the first XID of a new page of the commit + * log, zero out that commit-log page before returning. We must do + * this while holding XidGenLock, else another xact could acquire and + * commit a later XID before we zero the page. Fortunately, a page of + * the commit log holds 32K or more transactions, so we don't have to + * do this very often. */ ExtendCLOG(xid); /* - * Must set MyProc->xid before releasing XidGenLock. This ensures that - * when GetSnapshotData calls ReadNewTransactionId, all active XIDs - * before the returned value of nextXid are already present in the shared - * PROC array. Else we have a race condition. + * Must set MyProc->xid before releasing XidGenLock. This ensures + * that when GetSnapshotData calls ReadNewTransactionId, all active + * XIDs before the returned value of nextXid are already present in + * the shared PROC array. Else we have a race condition. * * XXX by storing xid into MyProc without acquiring SInvalLock, we are * relying on fetch/store of an xid to be atomic, else other backends - * might see a partially-set xid here. But holding both locks at once - * would be a nasty concurrency hit (and in fact could cause a deadlock - * against GetSnapshotData). So for now, assume atomicity. Note that - * readers of PROC xid field should be careful to fetch the value only - * once, rather than assume they can read it multiple times and get the - * same answer each time. + * might see a partially-set xid here. But holding both locks at once + * would be a nasty concurrency hit (and in fact could cause a + * deadlock against GetSnapshotData). So for now, assume atomicity. + * Note that readers of PROC xid field should be careful to fetch the + * value only once, rather than assume they can read it multiple times + * and get the same answer each time. * - * A solution to the atomic-store problem would be to give each PROC - * its own spinlock used only for fetching/storing that PROC's xid. + * A solution to the atomic-store problem would be to give each PROC its + * own spinlock used only for fetching/storing that PROC's xid. * (SInvalLock would then mean primarily that PROCs couldn't be added/ * removed while holding the lock.) */ @@ -91,7 +91,7 @@ GetNewTransactionId(void) TransactionId ReadNewTransactionId(void) { - TransactionId xid; + TransactionId xid; /* * During bootstrap initialization, we return the special bootstrap @@ -117,16 +117,16 @@ static Oid lastSeenOid = InvalidOid; Oid GetNewObjectId(void) { - Oid result; + Oid result; LWLockAcquire(OidGenLock, LW_EXCLUSIVE); /* * Check for wraparound of the OID counter. We *must* not return 0 * (InvalidOid); and as long as we have to check that, it seems a good - * idea to skip over everything below BootstrapObjectIdData too. (This - * basically just reduces the odds of OID collision right after a wrap - * occurs.) Note we are relying on unsigned comparison here. + * idea to skip over everything below BootstrapObjectIdData too. + * (This basically just reduces the odds of OID collision right after + * a wrap occurs.) Note we are relying on unsigned comparison here. */ if (ShmemVariableCache->nextOid < ((Oid) BootstrapObjectIdData)) { diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c index cf9791a8e8..f4dc01adfd 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.112 2001/10/18 17:30:03 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/xact.c,v 1.113 2001/10/25 05:49:22 momjian Exp $ * * NOTES * Transaction aborts can now occur two ways: @@ -300,7 +300,6 @@ IsTransactionState(void) */ return false; } - #endif /* -------------------------------- @@ -476,7 +475,6 @@ AtStart_Cache(void) static void AtStart_Locks(void) { - /* * at present, it is unknown to me what belongs here -cim 3/18/90 * @@ -492,7 +490,6 @@ AtStart_Locks(void) static void AtStart_Memory(void) { - /* * We shouldn't have any transaction contexts already. */ @@ -717,8 +714,8 @@ RecordTransactionAbort(void) recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata); /* - * There's no need for XLogFlush here, since the default assumption - * would be that we aborted, anyway. + * There's no need for XLogFlush here, since the default + * assumption would be that we aborted, anyway. */ /* Mark the transaction aborted in clog */ @@ -756,7 +753,6 @@ AtAbort_Cache(void) static void AtAbort_Locks(void) { - /* * XXX What if ProcReleaseLocks() fails? (race condition?) * @@ -773,7 +769,6 @@ AtAbort_Locks(void) static void AtAbort_Memory(void) { - /* * Make sure we are in a valid context (not a child of * TransactionCommandContext...). Note that it is possible for this @@ -807,7 +802,6 @@ AtAbort_Memory(void) static void AtCleanup_Memory(void) { - /* * Now that we're "out" of a transaction, have the system allocate * things in the top memory context instead of per-transaction @@ -909,7 +903,6 @@ CurrentXactInProgress(void) { return CurrentTransactionState->state == TRANS_INPROGRESS; } - #endif /* -------------------------------- @@ -965,12 +958,11 @@ CommitTransaction(void) * this must be done _before_ releasing locks we hold and _after_ * RecordTransactionCommit. * - * LWLockAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked - * by xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot - - * if xid 2' GetSnapshotData sees xid 1 as running then it must see - * xid 0 as running as well or it will see two tuple versions - one - * deleted by xid 1 and one inserted by xid 0. See notes in - * GetSnapshotData. + * LWLockAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked by + * xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot - if + * xid 2' GetSnapshotData sees xid 1 as running then it must see xid 0 + * as running as well or it will see two tuple versions - one deleted + * by xid 1 and one inserted by xid 0. See notes in GetSnapshotData. */ if (MyProc != (PROC *) NULL) { @@ -1002,7 +994,7 @@ CommitTransaction(void) AtCommit_Memory(); AtEOXact_Files(); - SharedBufferChanged = false;/* safest place to do it */ + SharedBufferChanged = false; /* safest place to do it */ /* Count transaction commit in statistics collector */ pgstat_count_xact_commit(); @@ -1032,8 +1024,8 @@ AbortTransaction(void) /* * Release any LW locks we might be holding as quickly as possible. * (Regular locks, however, must be held till we finish aborting.) - * Releasing LW locks is critical since we might try to grab them again - * while cleaning up! + * Releasing LW locks is critical since we might try to grab them + * again while cleaning up! */ LWLockReleaseAll(); @@ -1105,7 +1097,7 @@ AbortTransaction(void) AtEOXact_Files(); AtAbort_Locks(); - SharedBufferChanged = false;/* safest place to do it */ + SharedBufferChanged = false; /* safest place to do it */ /* Count transaction abort in statistics collector */ pgstat_count_xact_rollback(); @@ -1155,7 +1147,6 @@ StartTransactionCommand(void) switch (s->blockState) { - /* * if we aren't in a transaction block, we just do our usual * start transaction. @@ -1238,7 +1229,6 @@ CommitTransactionCommand(void) switch (s->blockState) { - /* * if we aren't in a transaction block, we just do our usual * transaction commit @@ -1313,7 +1303,6 @@ AbortCurrentTransaction(void) switch (s->blockState) { - /* * if we aren't in a transaction block, we just do the basic * abort & cleanup transaction. @@ -1429,7 +1418,6 @@ EndTransactionBlock(void) */ if (s->blockState == TBLOCK_INPROGRESS) { - /* * here we are in a transaction block which should commit when we * get to the upcoming CommitTransactionCommand() so we set the @@ -1442,7 +1430,6 @@ EndTransactionBlock(void) if (s->blockState == TBLOCK_ABORT) { - /* * here, we are in a transaction block which aborted and since the * AbortTransaction() was already done, we do whatever is needed @@ -1480,7 +1467,6 @@ AbortTransactionBlock(void) */ if (s->blockState == TBLOCK_INPROGRESS) { - /* * here we were inside a transaction block something screwed up * inside the system so we enter the abort state, do the abort @@ -1502,7 +1488,6 @@ AbortTransactionBlock(void) AbortTransaction(); s->blockState = TBLOCK_ENDABORT; } - #endif /* -------------------------------- @@ -1527,7 +1512,6 @@ UserAbortTransactionBlock(void) if (s->blockState == TBLOCK_INPROGRESS) { - /* * here we were inside a transaction block and we got an abort * command from the user, so we move to the abort state, do the diff --git a/src/backend/access/transam/xid.c b/src/backend/access/transam/xid.c index babe7c9a48..cde2713b0f 100644 --- a/src/backend/access/transam/xid.c +++ b/src/backend/access/transam/xid.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: xid.c,v 1.33 2001/08/26 16:55:59 tgl Exp $ + * $Id: xid.c,v 1.34 2001/10/25 05:49:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -34,6 +34,7 @@ Datum xidout(PG_FUNCTION_ARGS) { TransactionId transactionId = PG_GETARG_TRANSACTIONID(0); + /* maximum 32 bit unsigned integer representation takes 10 chars */ char *str = palloc(11); @@ -64,7 +65,7 @@ xid_age(PG_FUNCTION_ARGS) TransactionId now = GetCurrentTransactionId(); /* Permanent XIDs are always infinitely old */ - if (! TransactionIdIsNormal(xid)) + if (!TransactionIdIsNormal(xid)) PG_RETURN_INT32(INT_MAX); PG_RETURN_INT32((int32) (now - xid)); diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index 057ee72d55..8c162ab3f6 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, 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.78 2001/09/29 04:02:21 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/xlog.c,v 1.79 2001/10/25 05:49:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -97,7 +97,7 @@ char XLOG_archive_dir[MAXPGPATH]; /* null string means * delete 'em */ /* - * XLOGfileslop is used in the code as the allowed "fuzz" in the number of + * XLOGfileslop is used in the code as the allowed "fuzz" in the number of * preallocated XLOG segments --- we try to have at least XLOGfiles advance * segments but no more than XLOGfiles+XLOGfileslop segments. This could * be made a separate GUC variable, but at present I think it's sufficient @@ -215,13 +215,13 @@ typedef struct XLogwrtRqst { XLogRecPtr Write; /* last byte + 1 to write out */ XLogRecPtr Flush; /* last byte + 1 to flush */ -} XLogwrtRqst; +} XLogwrtRqst; typedef struct XLogwrtResult { XLogRecPtr Write; /* last byte + 1 written out */ XLogRecPtr Flush; /* last byte + 1 flushed */ -} XLogwrtResult; +} XLogwrtResult; /* * Shared state data for XLogInsert. @@ -260,8 +260,9 @@ typedef struct XLogCtlData /* * These values do not change after startup, although the pointed-to - * pages and xlblocks values certainly do. Permission to read/write the - * pages and xlblocks values depends on WALInsertLock and WALWriteLock. + * pages and xlblocks values certainly do. Permission to read/write + * the pages and xlblocks values depends on WALInsertLock and + * WALWriteLock. */ char *pages; /* buffers for unwritten XLOG pages */ XLogRecPtr *xlblocks; /* 1st byte ptr-s + BLCKSZ */ @@ -428,8 +429,8 @@ static void XLogWrite(XLogwrtRqst WriteRqst); static int XLogFileInit(uint32 log, uint32 seg, bool *use_existent, bool use_lock); static bool InstallXLogFileSegment(uint32 log, uint32 seg, char *tmppath, - bool find_free, int max_advance, - bool use_lock); + bool find_free, int max_advance, + bool use_lock); static int XLogFileOpen(uint32 log, uint32 seg, bool econt); static void PreallocXlogFiles(XLogRecPtr endptr); static void MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr); @@ -621,8 +622,8 @@ begin:; SpinLockRelease_NoHoldoff(&XLogCtl->info_lck); /* - * If cache is half filled then try to acquire write lock and - * do XLogWrite. Ignore any fractional blocks in performing this check. + * If cache is half filled then try to acquire write lock and do + * XLogWrite. Ignore any fractional blocks in performing this check. */ LogwrtRqst.Write.xrecoff -= LogwrtRqst.Write.xrecoff % BLCKSZ; if (LogwrtRqst.Write.xlogid != LogwrtResult.Write.xlogid || @@ -939,9 +940,7 @@ AdvanceXLInsertBuffer(void) NewPageEndPtr.xrecoff = BLCKSZ; } else - { NewPageEndPtr.xrecoff += BLCKSZ; - } XLogCtl->xlblocks[nextidx] = NewPageEndPtr; NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * BLCKSZ); Insert->curridx = nextidx; @@ -956,7 +955,7 @@ AdvanceXLInsertBuffer(void) /* And fill the new page's header */ NewPage->xlp_magic = XLOG_PAGE_MAGIC; - /* NewPage->xlp_info = 0; */ /* done by memset */ + /* NewPage->xlp_info = 0; *//* done by memset */ NewPage->xlp_sui = ThisStartUpID; NewPage->xlp_pageaddr.xlogid = NewPageEndPtr.xlogid; NewPage->xlp_pageaddr.xrecoff = NewPageEndPtr.xrecoff - BLCKSZ; @@ -985,7 +984,6 @@ XLogWrite(XLogwrtRqst WriteRqst) while (XLByteLT(LogwrtResult.Write, WriteRqst.Write)) { - /* * Make sure we're not ahead of the insert process. This could * happen if we're passed a bogus WriteRqst.Write that is past the @@ -1004,7 +1002,6 @@ XLogWrite(XLogwrtRqst WriteRqst) if (!XLByteInPrevSeg(LogwrtResult.Write, openLogId, openLogSeg)) { - /* * Switch to new logfile segment. */ @@ -1114,7 +1111,6 @@ XLogWrite(XLogwrtRqst WriteRqst) if (XLByteLT(LogwrtResult.Flush, WriteRqst.Flush) && XLByteLT(LogwrtResult.Flush, LogwrtResult.Write)) { - /* * Could get here without iterating above loop, in which case we * might have no open file or the wrong one. However, we do not @@ -1174,11 +1170,11 @@ XLogFlush(XLogRecPtr record) if (XLOG_DEBUG) { elog(DEBUG, "XLogFlush%s%s: request %X/%X; write %X/%X; flush %X/%X\n", - (IsBootstrapProcessingMode()) ? "(bootstrap)" : "", - (InRedo) ? "(redo)" : "", - record.xlogid, record.xrecoff, - LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff, - LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff); + (IsBootstrapProcessingMode()) ? "(bootstrap)" : "", + (InRedo) ? "(redo)" : "", + record.xlogid, record.xrecoff, + LogwrtResult.Write.xlogid, LogwrtResult.Write.xrecoff, + LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff); fflush(stderr); } @@ -1240,7 +1236,7 @@ XLogFlush(XLogRecPtr record) if (XLByteLT(LogwrtResult.Flush, record)) elog(STOP, "XLogFlush: request %X/%X is not satisfied --- flushed only to %X/%X", record.xlogid, record.xrecoff, - LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff); + LogwrtResult.Flush.xlogid, LogwrtResult.Flush.xrecoff); } LWLockRelease(WALWriteLock); } @@ -1565,8 +1561,8 @@ MoveOfflineLogs(uint32 log, uint32 seg, XLogRecPtr endptr) { /* * Before deleting the file, see if it can be recycled as - * a future log segment. We allow recycling segments up to - * XLOGfiles + XLOGfileslop segments beyond the current + * a future log segment. We allow recycling segments up + * to XLOGfiles + XLOGfileslop segments beyond the current * XLOG location. */ if (InstallXLogFileSegment(endlogId, endlogSeg, path, @@ -1719,7 +1715,6 @@ ReadRecord(XLogRecPtr *RecPtr, int emode, char *buffer) if (readBuf == NULL) { - /* * First time through, permanently allocate readBuf. We do it * this way, rather than just making a static array, for two @@ -1767,7 +1762,7 @@ ReadRecord(XLogRecPtr *RecPtr, int emode, char *buffer) readFile = XLogFileOpen(readId, readSeg, (emode == LOG)); if (readFile < 0) goto next_record_is_invalid; - readOff = (uint32) (-1);/* force read to occur below */ + readOff = (uint32) (-1); /* force read to occur below */ } targetPageOff = ((RecPtr->xrecoff % XLogSegSize) / BLCKSZ) * BLCKSZ; @@ -2022,7 +2017,6 @@ WriteControlFile(void) #ifdef USE_LOCALE char *localeptr; - #endif /* @@ -2054,10 +2048,10 @@ WriteControlFile(void) "\n\tsuch queries, you may wish to set LC_COLLATE to \"C\" and" "\n\tre-initdb. For more information see the Administrator's Guide.", ControlFile->lc_collate); -#else /* not USE_LOCALE */ +#else /* not USE_LOCALE */ strcpy(ControlFile->lc_collate, "C"); strcpy(ControlFile->lc_ctype, "C"); -#endif /* not USE_LOCALE */ +#endif /* not USE_LOCALE */ /* Contents are protected with a CRC */ INIT_CRC64(ControlFile->crc); @@ -2156,7 +2150,7 @@ ReadControlFile(void) if (ControlFile->catalog_version_no != CATALOG_VERSION_NO) elog(STOP, "The database cluster was initialized with CATALOG_VERSION_NO %d,\n" - "\tbut the backend was compiled with CATALOG_VERSION_NO %d.\n" + "\tbut the backend was compiled with CATALOG_VERSION_NO %d.\n" "\tIt looks like you need to initdb.", ControlFile->catalog_version_no, CATALOG_VERSION_NO); if (ControlFile->blcksz != BLCKSZ) @@ -2174,7 +2168,7 @@ ReadControlFile(void) #ifdef USE_LOCALE if (setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL) elog(STOP, - "The database cluster was initialized with LC_COLLATE '%s',\n" + "The database cluster was initialized with LC_COLLATE '%s',\n" "\twhich is not recognized by setlocale().\n" "\tIt looks like you need to initdb.", ControlFile->lc_collate); @@ -2184,15 +2178,15 @@ ReadControlFile(void) "\twhich is not recognized by setlocale().\n" "\tIt looks like you need to initdb.", ControlFile->lc_ctype); -#else /* not USE_LOCALE */ +#else /* not USE_LOCALE */ if (strcmp(ControlFile->lc_collate, "C") != 0 || strcmp(ControlFile->lc_ctype, "C") != 0) elog(STOP, - "The database cluster was initialized with LC_COLLATE '%s' and\n" + "The database cluster was initialized with LC_COLLATE '%s' and\n" "\tLC_CTYPE '%s', but the server was compiled without locale support.\n" "\tIt looks like you need to initdb or recompile.", ControlFile->lc_collate, ControlFile->lc_ctype); -#endif /* not USE_LOCALE */ +#endif /* not USE_LOCALE */ } void @@ -2536,7 +2530,7 @@ StartupXLOG(void) { /* nextXid must be beyond record's xid */ if (TransactionIdFollowsOrEquals(record->xl_xid, - ShmemVariableCache->nextXid)) + ShmemVariableCache->nextXid)) { ShmemVariableCache->nextXid = record->xl_xid; TransactionIdAdvance(ShmemVariableCache->nextXid); @@ -2585,8 +2579,8 @@ StartupXLOG(void) Insert->PrevRecord = LastRec; /* - * If the next record will go to the new page - * then initialize for that one. + * If the next record will go to the new page then initialize for that + * one. */ if ((BLCKSZ - EndOfLog.xrecoff % BLCKSZ) < SizeOfXLogRecord) EndOfLog.xrecoff += (BLCKSZ - EndOfLog.xrecoff % BLCKSZ); @@ -2602,9 +2596,7 @@ StartupXLOG(void) NewPageEndPtr.xrecoff = BLCKSZ; } else - { NewPageEndPtr.xrecoff += BLCKSZ; - } XLogCtl->xlblocks[0] = NewPageEndPtr; Insert->currpage->xlp_magic = XLOG_PAGE_MAGIC; if (InRecovery) @@ -2621,9 +2613,10 @@ StartupXLOG(void) XLogCtl->xlblocks[0].xlogid = openLogId; XLogCtl->xlblocks[0].xrecoff = ((EndOfLog.xrecoff - 1) / BLCKSZ + 1) * BLCKSZ; + /* * Tricky point here: readBuf contains the *last* block that the - * LastRec record spans, not the one it starts in. The last block + * 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); @@ -2670,7 +2663,6 @@ StartupXLOG(void) if (InRecovery) { - /* * In case we had to use the secondary checkpoint, make sure that * it will still be shown as the secondary checkpoint after this @@ -2748,8 +2740,8 @@ ReadCheckpointRecord(XLogRecPtr RecPtr, if (record->xl_rmid != RM_XLOG_ID) { elog(LOG, (whichChkpt == 1 ? - "invalid resource manager id in primary checkpoint record" : - "invalid resource manager id in secondary checkpoint record")); + "invalid resource manager id in primary checkpoint record" : + "invalid resource manager id in secondary checkpoint record")); return NULL; } if (record->xl_info != XLOG_CHECKPOINT_SHUTDOWN && @@ -2845,11 +2837,11 @@ CreateCheckPoint(bool shutdown) /* * 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 an - * LWLock. (But the alternative of using a regular lock won't work for - * background checkpoint processes, which are not regular backends.) - * So, rather than use a plain LWLockAcquire, use this kluge to allow - * an interrupt to be accepted while we are waiting: + * because we won't respond to a cancel/die request while waiting for + * an LWLock. (But the alternative of using a regular lock won't work + * for background checkpoint processes, which are not regular + * backends.) So, rather than use a plain LWLockAcquire, use this + * kluge to allow an interrupt to be accepted while we are waiting: */ while (!LWLockConditionalAcquire(CheckpointLock, LW_EXCLUSIVE)) { @@ -2996,7 +2988,8 @@ CreateCheckPoint(bool shutdown) * but watch out for case that undo = 0. * * Without UNDO support: just use the redo pointer. This allows xlog - * space to be freed much faster when there are long-running transactions. + * space to be freed much faster when there are long-running + * transactions. */ #ifdef NOT_USED if (ControlFile->checkPointCopy.undo.xrecoff != 0 && @@ -3230,7 +3223,6 @@ assign_xlog_sync_method(const char *method) if (sync_method != new_sync_method || open_sync_bit != new_sync_bit) { - /* * To ensure that no blocks escape unsynced, force an fsync on the * currently open log segment (if any). Also, if the open flag is @@ -3264,7 +3256,7 @@ issue_xlog_fsync(void) { switch (sync_method) { - case SYNC_METHOD_FSYNC: + case SYNC_METHOD_FSYNC: if (pg_fsync(openLogFile) != 0) elog(STOP, "fsync of log file %u, segment %u failed: %m", openLogId, openLogSeg); diff --git a/src/backend/access/transam/xlogutils.c b/src/backend/access/transam/xlogutils.c index 2394060a67..e49d543ac8 100644 --- a/src/backend/access/transam/xlogutils.c +++ b/src/backend/access/transam/xlogutils.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/access/transam/xlogutils.c,v 1.20 2001/10/05 17:28:11 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/access/transam/xlogutils.c,v 1.21 2001/10/25 05:49:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -247,7 +247,7 @@ _xl_remove_hash_entry(XLogRelDesc *rdesc) rdesc->moreRecently->lessRecently = rdesc->lessRecently; hentry = (XLogRelCacheEntry *) hash_search(_xlrelcache, - (void *) &(rdesc->reldata.rd_node), HASH_REMOVE, NULL); + (void *) &(rdesc->reldata.rd_node), HASH_REMOVE, NULL); if (hentry == NULL) elog(STOP, "_xl_remove_hash_entry: file was not found in cache"); @@ -304,9 +304,7 @@ XLogCloseRelationCache(void) hash_seq_init(&status, _xlrelcache); while ((hentry = (XLogRelCacheEntry *) hash_seq_search(&status)) != NULL) - { _xl_remove_hash_entry(hentry->rdesc); - } hash_destroy(_xlrelcache); diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c index 817ed4c8c8..076b31fb17 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.118 2001/10/19 17:03:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.119 2001/10/25 05:49:22 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -188,7 +188,7 @@ usage(void) { fprintf(stderr, gettext("Usage:\n" - " postgres -boot [-d] [-D datadir] [-F] [-o file] [-x num] dbname\n" + " postgres -boot [-d] [-D datadir] [-F] [-o file] [-x num] dbname\n" " -d debug mode\n" " -D datadir data directory\n" " -F turn off fsync\n" @@ -293,7 +293,7 @@ BootstrapMain(int argc, char *argv[]) { if (!potential_DataDir) { - fprintf(stderr, + fprintf(stderr, gettext("%s does not know where to find the database system data.\n" "You must specify the directory that contains the database system\n" "either by specifying the -D invocation option or by setting the\n" @@ -377,7 +377,7 @@ BootstrapMain(int argc, char *argv[]) case BS_XLOG_CHECKPOINT: if (IsUnderPostmaster) - InitDummyProcess(); /* needed to get LWLocks */ + InitDummyProcess(); /* needed to get LWLocks */ CreateDummyCaches(); CreateCheckPoint(false); SetRedoRecPtr(); @@ -996,7 +996,6 @@ FindStr(char *str, int length, hashnode *mderef) node = hashtable[CompHash(str, length)]; while (node != NULL) { - /* * We must differentiate between string constants that might have * the same value as a identifier and the identifier itself. diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c index 35352be16b..123dbdd247 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.51 2001/06/18 16:13:21 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/aclchk.c,v 1.52 2001/10/25 05:49:22 momjian Exp $ * * NOTES * See acl.h. @@ -61,8 +61,7 @@ dumpacl(Acl *acl) DatumGetCString(DirectFunctionCall1(aclitemout, PointerGetDatum(aip + i)))); } - -#endif /* ACLDEBUG */ +#endif /* ACLDEBUG */ /* @@ -115,8 +114,8 @@ ExecuteGrantStmt(GrantStmt *stmt) relname); /* - * If there's no ACL, create a default using the - * pg_class.relowner field. + * If there's no ACL, create a default using the pg_class.relowner + * field. */ aclDatum = SysCacheGetAttr(RELNAME, tuple, Anum_pg_class_relacl, &isNull); @@ -133,10 +132,10 @@ ExecuteGrantStmt(GrantStmt *stmt) foreach(j, stmt->grantees) { - PrivGrantee *grantee = (PrivGrantee *)lfirst(j); + PrivGrantee *grantee = (PrivGrantee *) lfirst(j); char *granteeString; char *aclString; - AclItem aclitem; + AclItem aclitem; unsigned modechg; if (grantee->username) @@ -162,7 +161,8 @@ ExecuteGrantStmt(GrantStmt *stmt) { replaces[i] = ' '; nulls[i] = ' '; /* ignored if replaces[i]==' ' anyway */ - values[i] = (Datum) NULL; /* ignored if replaces[i]==' ' anyway */ + values[i] = (Datum) NULL; /* ignored if replaces[i]==' ' + * anyway */ } replaces[Anum_pg_class_relacl - 1] = 'r'; values[Anum_pg_class_relacl - 1] = PointerGetDatum(new_acl); @@ -175,6 +175,7 @@ ExecuteGrantStmt(GrantStmt *stmt) { /* keep the catalog indexes up to date */ Relation idescs[Num_pg_class_indices]; + CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, idescs); CatalogIndexInsert(idescs, Num_pg_class_indices, relation, newtuple); @@ -322,8 +323,8 @@ aclcheck(Acl *acl, AclId id, AclIdType idtype, AclMode mode) } /* - * "World" rights are applicable regardless of the passed-in ID, - * and since they're much the cheapest to check, check 'em first. + * "World" rights are applicable regardless of the passed-in ID, and + * since they're much the cheapest to check, check 'em first. */ if (aidat->ai_idtype != ACL_IDTYPE_WORLD) elog(ERROR, "aclcheck: first entry in ACL is not 'world' entry"); @@ -376,7 +377,7 @@ aclcheck(Acl *acl, AclId id, AclIdType idtype, AclMode mode) for (i = 1, aip = aidat + 1; /* skip world entry */ i < num && aip->ai_idtype == ACL_IDTYPE_UID; ++i, ++aip) - /* skip UID entry */; + /* skip UID entry */ ; for (; i < num && aip->ai_idtype == ACL_IDTYPE_GID; ++i, ++aip) diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c index 89d3072f7b..f78ac28693 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.178 2001/10/22 22:47:57 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.179 2001/10/25 05:49:22 momjian Exp $ * * * INTERFACE ROUTINES @@ -64,10 +64,10 @@ static void AddNewRelationTuple(Relation pg_class_desc, - Relation new_rel_desc, - Oid new_rel_oid, Oid new_type_oid, - char relkind, bool relhasoids, - char *temp_relname); + Relation new_rel_desc, + Oid new_rel_oid, Oid new_type_oid, + char relkind, bool relhasoids, + char *temp_relname); static void DeleteAttributeTuples(Relation rel); static void DeleteRelationTuple(Relation rel); static void DeleteTypeTuple(Relation rel); @@ -156,7 +156,7 @@ static Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7}; Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids) { - if (attno >= 0 || attno < - (int) lengthof(SysAtt)) + if (attno >= 0 || attno < -(int) lengthof(SysAtt)) elog(ERROR, "SystemAttributeDefinition: invalid attribute number %d", attno); if (attno == ObjectIdAttributeNumber && !relhasoids) @@ -167,12 +167,12 @@ SystemAttributeDefinition(AttrNumber attno, bool relhasoids) /* * If the given name is a system attribute name, return a Form_pg_attribute - * pointer for a prototype definition. If not, return NULL. + * pointer for a prototype definition. If not, return NULL. */ Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids) { - int j; + int j; for (j = 0; j < (int) lengthof(SysAtt); j++) { @@ -237,8 +237,8 @@ heap_create(char *relname, /* * Real ugly stuff to assign the proper relid in the relation - * descriptor follows. Note that only "bootstrapped" relations - * whose OIDs are hard-coded in pg_class.h need be listed here. + * descriptor follows. Note that only "bootstrapped" relations whose + * OIDs are hard-coded in pg_class.h need be listed here. */ if (relname && IsSystemRelationName(relname)) { @@ -541,7 +541,11 @@ AddNewAttributeTuples(Oid new_rel_oid, /* Fill in the correct relation OID in the copied tuple */ attStruct = (Form_pg_attribute) GETSTRUCT(tup); attStruct->attrelid = new_rel_oid; - /* Unneeded since they should be OK in the constant data anyway */ + + /* + * Unneeded since they should be OK in the constant data + * anyway + */ /* attStruct->attstattarget = 0; */ /* attStruct->attcacheoff = -1; */ @@ -613,7 +617,7 @@ AddNewRelationTuple(Relation pg_class_desc, case RELKIND_RELATION: case RELKIND_INDEX: case RELKIND_TOASTVALUE: - new_rel_reltup->relpages = 10; /* bogus estimates */ + new_rel_reltup->relpages = 10; /* bogus estimates */ new_rel_reltup->reltuples = 1000; break; case RELKIND_SEQUENCE: @@ -653,7 +657,6 @@ AddNewRelationTuple(Relation pg_class_desc, if (!IsIgnoringSystemIndexes()) { - /* * First, open the catalog indices and insert index tuples for the * new relation. @@ -1735,27 +1738,35 @@ AddRelationRawConstraints(Relation rel, { int i; int j; - bool success; + bool success; List *listptr2; + ccname = (char *) palloc(NAMEDATALEN); /* Loop until we find a non-conflicting constraint name */ /* What happens if this loops forever? */ j = numchecks + 1; - do { + do + { success = true; snprintf(ccname, NAMEDATALEN, "$%d", j); /* Check against old constraints */ for (i = 0; i < numoldchecks; i++) { - if (strcmp(oldchecks[i].ccname, ccname) == 0) { + if (strcmp(oldchecks[i].ccname, ccname) == 0) + { success = false; break; } } - /* Check against other new constraints, if the check hasn't already failed */ - if (success) { + + /* + * Check against other new constraints, if the check + * hasn't already failed + */ + if (success) + { foreach(listptr2, rawConstraints) { Constraint *cdef2 = (Constraint *) lfirst(listptr2); @@ -1765,7 +1776,8 @@ AddRelationRawConstraints(Relation rel, cdef2->raw_expr == NULL || cdef2->name == NULL) continue; - if (strcmp(cdef2->name, ccname) == 0) { + if (strcmp(cdef2->name, ccname) == 0) + { success = false; break; } @@ -1914,59 +1926,60 @@ RemoveRelCheck(Relation rel) int RemoveCheckConstraint(Relation rel, const char *constrName, bool inh) { - Oid relid; - Relation rcrel; - Relation relrel; - Relation inhrel; - Relation relidescs[Num_pg_class_indices]; - TupleDesc tupleDesc; - TupleConstr *oldconstr; - int numoldchecks; - int numchecks; - HeapScanDesc rcscan; - ScanKeyData key[2]; - HeapTuple rctup; - HeapTuple reltup; - Form_pg_class relStruct; - int rel_deleted = 0; - int all_deleted = 0; - - /* Find id of the relation */ - relid = RelationGetRelid(rel); - - /* Process child tables and remove constraints of the - same name. */ - if (inh) - { - List *child, - *children; - - /* This routine is actually in the planner */ - children = find_all_inheritors(relid); - - /* - * find_all_inheritors does the recursive search of the - * inheritance hierarchy, so all we have to do is process all - * of the relids in the list that it returns. - */ - foreach(child, children) - { - Oid childrelid = lfirsti(child); - - if (childrelid == relid) - continue; - inhrel = heap_open(childrelid, AccessExclusiveLock); - all_deleted += RemoveCheckConstraint(inhrel, constrName, false); - heap_close(inhrel, NoLock); - } - } + Oid relid; + Relation rcrel; + Relation relrel; + Relation inhrel; + Relation relidescs[Num_pg_class_indices]; + TupleDesc tupleDesc; + TupleConstr *oldconstr; + int numoldchecks; + int numchecks; + HeapScanDesc rcscan; + ScanKeyData key[2]; + HeapTuple rctup; + HeapTuple reltup; + Form_pg_class relStruct; + int rel_deleted = 0; + int all_deleted = 0; + + /* Find id of the relation */ + relid = RelationGetRelid(rel); + + /* + * Process child tables and remove constraints of the same name. + */ + if (inh) + { + List *child, + *children; + + /* This routine is actually in the planner */ + children = find_all_inheritors(relid); + + /* + * find_all_inheritors does the recursive search of the + * inheritance hierarchy, so all we have to do is process all of + * the relids in the list that it returns. + */ + foreach(child, children) + { + Oid childrelid = lfirsti(child); + + if (childrelid == relid) + continue; + inhrel = heap_open(childrelid, AccessExclusiveLock); + all_deleted += RemoveCheckConstraint(inhrel, constrName, false); + heap_close(inhrel, NoLock); + } + } /* Grab an exclusive lock on the pg_relcheck relation */ rcrel = heap_openr(RelCheckRelationName, RowExclusiveLock); /* - * Create two scan keys. We need to match on the oid of the table - * the CHECK is in and also we need to match the name of the CHECK + * Create two scan keys. We need to match on the oid of the table the + * CHECK is in and also we need to match the name of the CHECK * constraint. */ ScanKeyEntryInitialize(&key[0], 0, Anum_pg_relcheck_rcrelid, @@ -1979,14 +1992,15 @@ RemoveCheckConstraint(Relation rel, const char *constrName, bool inh) rcscan = heap_beginscan(rcrel, 0, SnapshotNow, 2, key); /* - * Scan over the result set, removing any matching entries. Note - * that this has the side-effect of removing ALL CHECK constraints - * that share the specified constraint name. + * Scan over the result set, removing any matching entries. Note that + * this has the side-effect of removing ALL CHECK constraints that + * share the specified constraint name. */ - while (HeapTupleIsValid(rctup = heap_getnext(rcscan, 0))) { + while (HeapTupleIsValid(rctup = heap_getnext(rcscan, 0))) + { simple_heap_delete(rcrel, &rctup->t_self); ++rel_deleted; - ++all_deleted; + ++all_deleted; } /* Clean up after the scan */ @@ -2001,7 +2015,7 @@ RemoveCheckConstraint(Relation rel, const char *constrName, bool inh) * message, but for ALTER TABLE ADD ATTRIBUTE this'd be important.) */ - /* + /* * Get number of existing constraints. */ @@ -2020,7 +2034,7 @@ RemoveCheckConstraint(Relation rel, const char *constrName, bool inh) relrel = heap_openr(RelationRelationName, RowExclusiveLock); reltup = SearchSysCacheCopy(RELOID, - ObjectIdGetDatum(RelationGetRelid(rel)), 0, 0, 0); + ObjectIdGetDatum(RelationGetRelid(rel)), 0, 0, 0); if (!HeapTupleIsValid(reltup)) elog(ERROR, "cache lookup of relation %u failed", diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index b53eab8652..0afb9cf7e4 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.165 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/index.c,v 1.166 2001/10/25 05:49:22 momjian Exp $ * * * INTERFACE ROUTINES @@ -64,19 +64,19 @@ static Oid GetHeapRelationOid(char *heapRelationName, char *indexRelationName, bool istemp); static TupleDesc BuildFuncTupleDesc(Oid funcOid, - Oid *classObjectId); + Oid *classObjectId); static TupleDesc ConstructTupleDescriptor(Relation heapRelation, - int numatts, AttrNumber *attNums, - Oid *classObjectId); + int numatts, AttrNumber *attNums, + Oid *classObjectId); static void ConstructIndexReldesc(Relation indexRelation, Oid amoid); static Oid UpdateRelationRelation(Relation indexRelation, char *temp_relname); static void InitializeAttributeOids(Relation indexRelation, int numatts, Oid indexoid); static void AppendAttributeTuples(Relation indexRelation, int numatts); static void UpdateIndexRelation(Oid indexoid, Oid heapoid, - IndexInfo *indexInfo, - Oid *classOids, - bool primary); + IndexInfo *indexInfo, + Oid *classOids, + bool primary); static Oid IndexGetRelation(Oid indexId); static bool activate_index(Oid indexId, bool activate, bool inplace); @@ -255,7 +255,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 { @@ -319,11 +319,11 @@ ConstructTupleDescriptor(Relation heapRelation, elog(ERROR, "Type %u does not exist", keyType); typeTup = (Form_pg_type) GETSTRUCT(tuple); - to->atttypid = keyType; - to->atttypmod = -1; - to->attlen = typeTup->typlen; - to->attbyval = typeTup->typbyval; - to->attalign = typeTup->typalign; + to->atttypid = keyType; + to->atttypmod = -1; + to->attlen = typeTup->typlen; + to->attbyval = typeTup->typbyval; + to->attalign = typeTup->typalign; to->attstorage = typeTup->typstorage; ReleaseSysCache(tuple); @@ -405,14 +405,15 @@ ConstructIndexReldesc(Relation indexRelation, Oid amoid) * Fill in a copy of relevant pg_am entry */ indexRelation->rd_am = AccessMethodObjectIdGetForm(amoid, - CacheMemoryContext); + CacheMemoryContext); + /* - * Set up some additional fields of the index' pg_class entry. - * In particular, initialize knowledge of whether the index is shared. + * Set up some additional fields of the index' pg_class entry. In + * particular, initialize knowledge of whether the index is shared. */ indexRelation->rd_rel->relowner = GetUserId(); indexRelation->rd_rel->relam = amoid; - indexRelation->rd_rel->relisshared = + indexRelation->rd_rel->relisshared = IsSharedSystemRelationName(RelationGetPhysicalRelationName(indexRelation)); indexRelation->rd_rel->relkind = RELKIND_INDEX; indexRelation->rd_rel->relhasoids = false; @@ -521,10 +522,10 @@ AppendAttributeTuples(Relation indexRelation, int numatts) for (i = 0; i < numatts; i++) { /* - * There used to be very grotty code here to set these fields, - * but I think it's unnecessary. They should be set already. + * There used to be very grotty code here to set these fields, but + * I think it's unnecessary. They should be set already. */ - Assert(indexTupDesc->attrs[i]->attnum == i+1); + Assert(indexTupDesc->attrs[i]->attnum == i + 1); Assert(indexTupDesc->attrs[i]->attcacheoff == -1); new_tuple = heap_addheader(Natts_pg_attribute, @@ -592,7 +593,7 @@ UpdateIndexRelation(Oid indexoid, indexForm->indexrelid = indexoid; indexForm->indrelid = heapoid; indexForm->indproc = indexInfo->ii_FuncOid; - indexForm->indisclustered = false; /* not used */ + indexForm->indisclustered = false; /* not used */ indexForm->indisunique = indexInfo->ii_Unique; indexForm->indisprimary = primary; memcpy((char *) &indexForm->indpred, (char *) predText, predLen); @@ -678,7 +679,7 @@ index_create(char *heapRelationName, elog(ERROR, "must index at least one column"); if (heapRelationName && !allow_system_table_mods && - IsSystemRelationName(heapRelationName) && IsNormalProcessingMode()) + IsSystemRelationName(heapRelationName) && IsNormalProcessingMode()) elog(ERROR, "User-defined indexes on system catalogs are not supported"); /* @@ -700,7 +701,7 @@ index_create(char *heapRelationName, else indexTupDesc = ConstructTupleDescriptor(heapRelation, indexInfo->ii_NumKeyAttrs, - indexInfo->ii_KeyAttrNumbers, + indexInfo->ii_KeyAttrNumbers, classObjectId); if (istemp) @@ -825,12 +826,13 @@ index_drop(Oid indexId) * To drop an index safely, we must grab exclusive lock on its parent * table; otherwise there could be other backends using the index! * Exclusive lock on the index alone is insufficient because another - * backend might be in the midst of devising a query plan that will use - * the index. The parser and planner take care to hold an appropriate - * lock on the parent table while working, but having them hold locks on - * all the indexes too seems overly complex. We do grab exclusive lock - * on the index too, just to be safe. Both locks must be held till end of - * transaction, else other backends will still see this index in pg_index. + * backend might be in the midst of devising a query plan that will + * use the index. The parser and planner take care to hold an + * appropriate lock on the parent table while working, but having them + * hold locks on all the indexes too seems overly complex. We do grab + * exclusive lock on the index too, just to be safe. Both locks must + * be held till end of transaction, else other backends will still see + * this index in pg_index. */ heapId = IndexGetRelation(indexId); userHeapRelation = heap_open(heapId, AccessExclusiveLock); @@ -873,8 +875,8 @@ index_drop(Oid indexId) * ensure other backends update their relcache lists of indexes. So, * unconditionally do setRelhasindex(true). * - * Possible future improvement: skip the physical tuple update and - * just send out an invalidation message. + * Possible future improvement: skip the physical tuple update and just + * send out an invalidation message. */ setRelhasindex(heapId, true, false, InvalidOid); @@ -950,7 +952,7 @@ index_drop(Oid indexId) * just once per command, and then use it for (potentially) many tuples. * ---------------- */ -IndexInfo * +IndexInfo * BuildIndexInfo(HeapTuple indexTuple) { Form_pg_index indexStruct = (Form_pg_index) GETSTRUCT(indexTuple); @@ -974,8 +976,8 @@ BuildIndexInfo(HeapTuple indexTuple) * Handle functional index. * * If we have a functional index then the number of attributes defined in - * the index must be 1 (the function's single return value). - * Otherwise it's same as number of keys. + * the index must be 1 (the function's single return value). Otherwise + * it's same as number of keys. */ ii->ii_FuncOid = indexStruct->indproc; @@ -1041,7 +1043,6 @@ FormIndexDatum(IndexInfo *indexInfo, if (OidIsValid(indexInfo->ii_FuncOid)) { - /* * Functional index --- compute the single index attribute */ @@ -1076,7 +1077,6 @@ FormIndexDatum(IndexInfo *indexInfo, } else { - /* * Plain index --- for each attribute we need from the heap tuple, * get the attribute and stick it into the datum and nullv arrays. @@ -1198,7 +1198,7 @@ IndexesAreActive(Oid relid, bool confirmCommitted) * set relhasindex of relation's pg_class entry * * If isprimary is TRUE, we are defining a primary index, so also set - * relhaspkey to TRUE. Otherwise, leave relhaspkey alone. + * relhaspkey to TRUE. Otherwise, leave relhaspkey alone. * * If reltoastidxid is not InvalidOid, also set reltoastidxid to that value. * This is only used for TOAST relations. @@ -1390,7 +1390,7 @@ UpdateStats(Oid relid, double reltuples) Relation pg_class; HeapTuple tuple; HeapTuple newtup; - BlockNumber relpages; + BlockNumber relpages; int i; Form_pg_class rd_rel; Relation idescs[Num_pg_class_indices]; @@ -1473,8 +1473,8 @@ UpdateStats(Oid relid, double reltuples) * when it is actually sizable. See also CREATE TABLE in heap.c. * * Note: this path is also taken during bootstrap, because bootstrap.c - * passes reltuples = 0 after loading a table. We have to estimate some - * number for reltuples based on the actual number of pages. + * passes reltuples = 0 after loading a table. We have to estimate + * some number for reltuples based on the actual number of pages. */ relpages = RelationGetNumberOfBlocks(whichRel); @@ -1492,7 +1492,7 @@ UpdateStats(Oid relid, double reltuples) reltuples = 1000; } else - reltuples = (double) relpages * NTUPLES_PER_PAGE(whichRel->rd_rel->relnatts); + reltuples = (double) relpages *NTUPLES_PER_PAGE(whichRel->rd_rel->relnatts); } /* @@ -1508,7 +1508,6 @@ 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. @@ -1599,8 +1598,8 @@ index_build(Relation heapRelation, * build procedure does whatever cleanup is needed; in particular, it should * close the heap and index relations. * - * The total count of heap tuples is returned. This is for updating pg_class - * statistics. (It's annoying not to be able to do that here, but we can't + * The total count of heap tuples is returned. This is for updating pg_class + * statistics. (It's annoying not to be able to do that here, but we can't * do it until after the relation is closed.) Note that the index AM itself * must keep track of the number of index tuples; we don't do so here because * the AM might reject some of the tuples for its own reasons, such as being @@ -1658,7 +1657,8 @@ IndexBuildHeapScan(Relation heapRelation, /* * Ok, begin our scan of the base relation. We use SnapshotAny - * because we must retrieve all tuples and do our own time qual checks. + * because we must retrieve all tuples and do our own time qual + * checks. */ if (IsBootstrapProcessingMode()) { @@ -1673,7 +1673,7 @@ IndexBuildHeapScan(Relation heapRelation, scan = heap_beginscan(heapRelation, /* relation */ 0, /* start at end */ - snapshot, /* seeself */ + snapshot, /* seeself */ 0, /* number of keys */ (ScanKey) NULL); /* scan key */ @@ -1689,14 +1689,14 @@ IndexBuildHeapScan(Relation heapRelation, if (snapshot == SnapshotAny) { /* do our own time qual check */ - bool indexIt; - uint16 sv_infomask; + bool indexIt; + uint16 sv_infomask; /* - * HeapTupleSatisfiesVacuum may update tuple's hint status bits. - * We could possibly get away with not locking the buffer here, - * since caller should hold ShareLock on the relation, but let's - * be conservative about it. + * HeapTupleSatisfiesVacuum may update tuple's hint status + * bits. We could possibly get away with not locking the + * buffer here, since caller should hold ShareLock on the + * relation, but let's be conservative about it. */ LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE); sv_infomask = heapTuple->t_data->t_infomask; @@ -1712,6 +1712,7 @@ IndexBuildHeapScan(Relation heapRelation, tupleIsAlive = true; break; case HEAPTUPLE_RECENTLY_DEAD: + /* * If tuple is recently deleted then we must index it * anyway to keep VACUUM from complaining. @@ -1720,32 +1721,36 @@ IndexBuildHeapScan(Relation heapRelation, tupleIsAlive = false; break; case HEAPTUPLE_INSERT_IN_PROGRESS: + /* - * Since caller should hold ShareLock or better, we should - * not see any tuples inserted by open transactions --- - * unless it's our own transaction. (Consider INSERT - * followed by CREATE INDEX within a transaction.) + * Since caller should hold ShareLock or better, we + * should not see any tuples inserted by open + * transactions --- unless it's our own transaction. + * (Consider INSERT followed by CREATE INDEX within a + * transaction.) */ - if (! TransactionIdIsCurrentTransactionId(heapTuple->t_data->t_xmin)) + if (!TransactionIdIsCurrentTransactionId(heapTuple->t_data->t_xmin)) elog(ERROR, "IndexBuildHeapScan: concurrent insert in progress"); indexIt = true; tupleIsAlive = true; break; case HEAPTUPLE_DELETE_IN_PROGRESS: + /* - * Since caller should hold ShareLock or better, we should - * not see any tuples deleted by open transactions --- - * unless it's our own transaction. (Consider DELETE - * followed by CREATE INDEX within a transaction.) + * Since caller should hold ShareLock or better, we + * should not see any tuples deleted by open + * transactions --- unless it's our own transaction. + * (Consider DELETE followed by CREATE INDEX within a + * transaction.) */ - if (! TransactionIdIsCurrentTransactionId(heapTuple->t_data->t_xmax)) + if (!TransactionIdIsCurrentTransactionId(heapTuple->t_data->t_xmax)) elog(ERROR, "IndexBuildHeapScan: concurrent delete in progress"); indexIt = true; tupleIsAlive = false; break; default: elog(ERROR, "Unexpected HeapTupleSatisfiesVacuum result"); - indexIt = tupleIsAlive = false; /* keep compiler quiet */ + indexIt = tupleIsAlive = false; /* keep compiler quiet */ break; } @@ -1755,7 +1760,7 @@ IndexBuildHeapScan(Relation heapRelation, LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK); - if (! indexIt) + if (!indexIt) continue; } else @@ -1776,7 +1781,7 @@ IndexBuildHeapScan(Relation heapRelation, */ if (predicate != NIL) { - if (! tupleIsAlive) + if (!tupleIsAlive) continue; ExecStoreTuple(heapTuple, slot, InvalidBuffer, false); if (!ExecQual(predicate, econtext, false)) @@ -1785,7 +1790,7 @@ IndexBuildHeapScan(Relation heapRelation, /* * For the current heap tuple, extract all the attributes we use - * in this index, and note which are null. This also performs + * in this index, and note which are null. This also performs * evaluation of the function, if this is a functional index. */ FormIndexDatum(indexInfo, @@ -1797,8 +1802,8 @@ IndexBuildHeapScan(Relation heapRelation, /* * You'd think we should go ahead and build the index tuple here, - * but some index AMs want to do further processing on the - * data first. So pass the attdata and nulls arrays, instead. + * but some index AMs want to do further processing on the data + * first. So pass the attdata and nulls arrays, instead. */ /* Call the AM's callback routine to process the tuple */ @@ -1919,7 +1924,6 @@ reindex_index(Oid indexId, bool force, bool inplace) if (inplace) { - /* * Release any buffers associated with this index. If they're * dirty, they're just dropped without bothering to flush to disk. @@ -2002,11 +2006,12 @@ reindex_relation(Oid relid, bool force) upd_pg_class_inplace = true; /* - * Ensure to hold an exclusive lock throughout the - * transaction. The lock could be less intensive - * but now it's AccessExclusiveLock for simplicity. + * Ensure to hold an exclusive lock throughout the transaction. The + * lock could be less intensive but now it's AccessExclusiveLock for + * simplicity. */ rel = heap_open(relid, AccessExclusiveLock); + /* * ignore the indexes of the target system relation while processing * reindex. @@ -2045,8 +2050,9 @@ reindex_relation(Oid relid, bool force) else elog(ERROR, "the target relation %u is shared", relid); } + /* - * Continue to hold the lock. + * Continue to hold the lock. */ heap_close(rel, NoLock); @@ -2087,7 +2093,6 @@ reindex_relation(Oid relid, bool force) heap_close(indexRelation, AccessShareLock); if (reindexed) { - /* * Ok,we could use the reindexed indexes of the target system * relation now. @@ -2096,7 +2101,6 @@ reindex_relation(Oid relid, bool force) { if (!overwrite && relid == RelOid_pg_class) { - /* * For pg_class, relhasindex should be set to true here in * place. diff --git a/src/backend/catalog/pg_aggregate.c b/src/backend/catalog/pg_aggregate.c index 119e125402..f037852bb5 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.39 2001/08/10 15:49:39 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_aggregate.c,v 1.40 2001/10/25 05:49:23 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -167,7 +167,6 @@ AggregateCreate(char *aggName, } else { - /* * If no finalfn, aggregate result type is type of the state value */ diff --git a/src/backend/catalog/pg_operator.c b/src/backend/catalog/pg_operator.c index 97e0b87b9c..efd98b546f 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.62 2001/10/22 19:34:13 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_operator.c,v 1.63 2001/10/25 05:49:23 momjian Exp $ * * NOTES * these routines moved here from commands/define.c and somewhat cleaned up. @@ -74,7 +74,7 @@ static void OperatorUpd(Oid baseId, Oid commId, Oid negId); static bool validOperatorName(const char *name) { - size_t len = strlen(name); + size_t len = strlen(name); /* Can't be empty or too long */ if (len == 0 || len >= NAMEDATALEN) @@ -90,20 +90,19 @@ validOperatorName(const char *name) return false; /* - * For SQL92 compatibility, '+' and '-' cannot be the - * last char of a multi-char operator unless the operator - * contains chars that are not in SQL92 operators. - * The idea is to lex '=-' as two operators, but not - * to forbid operator names like '?-' that could not be - * sequences of SQL92 operators. + * For SQL92 compatibility, '+' and '-' cannot be the last char of a + * multi-char operator unless the operator contains chars that are not + * in SQL92 operators. The idea is to lex '=-' as two operators, but + * not to forbid operator names like '?-' that could not be sequences + * of SQL92 operators. */ if (len > 1 && - (name[len-1] == '+' || - name[len-1] == '-')) + (name[len - 1] == '+' || + name[len - 1] == '-')) { - int ic; + int ic; - for (ic = len-2; ic >= 0; ic--) + for (ic = len - 2; ic >= 0; ic--) { if (strchr("~!@#^&|`?$%", name[ic])) break; @@ -143,7 +142,7 @@ OperatorGetWithOpenRelation(Relation pg_operator_desc, HeapScanDesc pg_operator_scan; Oid operatorObjectId; HeapTuple tup; - ScanKeyData opKey[3]; + ScanKeyData opKey[3]; /* * form scan key @@ -495,7 +494,7 @@ OperatorDef(char *operatorName, int nargs; NameData oname; TupleDesc tupDesc; - ScanKeyData opKey[3]; + ScanKeyData opKey[3]; operatorObjectId = OperatorGet(operatorName, leftTypeName, @@ -743,7 +742,6 @@ OperatorDef(char *operatorName, } else { - /* * self-linkage to this operator; will fix below. Note * that only self-linkage for commutation makes sense. @@ -867,7 +865,7 @@ OperatorUpd(Oid baseId, Oid commId, Oid negId) char nulls[Natts_pg_operator]; char replaces[Natts_pg_operator]; Datum values[Natts_pg_operator]; - ScanKeyData opKey[1]; + ScanKeyData opKey[1]; for (i = 0; i < Natts_pg_operator; ++i) { diff --git a/src/backend/catalog/pg_proc.c b/src/backend/catalog/pg_proc.c index e83d35edbf..016b9c1d98 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.61 2001/10/06 23:21:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_proc.c,v 1.62 2001/10/25 05:49:23 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -125,7 +125,6 @@ ProcedureCreate(char *procedureName, if (languageObjectId == SQLlanguageId) { - /* * If this call is defining a set, check if the set is already * defined by looking to see whether this call's function text @@ -230,7 +229,7 @@ ProcedureCreate(char *procedureName, prosrc = procedureName; if (fmgr_internal_function(prosrc) == InvalidOid) elog(ERROR, - "there is no built-in function named \"%s\"", + "there is no built-in function named \"%s\"", prosrc); } @@ -246,7 +245,7 @@ ProcedureCreate(char *procedureName, if (languageObjectId == ClanguageId) { - void *libraryhandle; + void *libraryhandle; /* If link symbol is specified as "-", substitute procedure name */ if (strcmp(prosrc, "-") == 0) @@ -303,7 +302,7 @@ ProcedureCreate(char *procedureName, if (HeapTupleIsValid(oldtup)) { /* There is one; okay to replace it? */ - Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup); + Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup); if (!replace) elog(ERROR, "function %s already exists with same argument types", @@ -311,6 +310,7 @@ ProcedureCreate(char *procedureName, if (GetUserId() != oldproc->proowner && !superuser()) elog(ERROR, "ProcedureCreate: you do not have permission to replace function %s", procedureName); + /* * Not okay to change the return type of the existing proc, since * existing rules, views, etc may depend on the return type. @@ -321,8 +321,8 @@ ProcedureCreate(char *procedureName, "\n\tUse DROP FUNCTION first."); /* Okay, do it... */ - tup = heap_modifytuple(oldtup, rel, values, nulls, replaces); - simple_heap_update(rel, &tup->t_self, tup); + tup = heap_modifytuple(oldtup, rel, values, nulls, replaces); + simple_heap_update(rel, &tup->t_self, tup); ReleaseSysCache(oldtup); } @@ -412,8 +412,8 @@ checkretval(Oid rettype, List *queryTreeList) /* * For base-type returns, the target list should have exactly one - * entry, and its type should agree with what the user declared. - * (As of Postgres 7.2, we accept binary-compatible types too.) + * entry, and its type should agree with what the user declared. (As + * of Postgres 7.2, we accept binary-compatible types too.) */ typerelid = typeidTypeRelid(rettype); if (typerelid == InvalidOid) @@ -433,9 +433,9 @@ checkretval(Oid rettype, List *queryTreeList) /* * If the target list is of length 1, and the type of the varnode in * the target list matches the declared return type, this is okay. - * This can happen, for example, where the body of the function - * is 'SELECT func2()', where func2 has the same return type as - * the function that's calling it. + * This can happen, for example, where the body of the function is + * 'SELECT func2()', where func2 has the same return type as the + * function that's calling it. */ if (tlistlen == 1) { diff --git a/src/backend/catalog/pg_type.c b/src/backend/catalog/pg_type.c index b79bd7068f..f14d06e0e2 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.64 2001/10/12 00:07:14 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/catalog/pg_type.c,v 1.65 2001/10/25 05:49:23 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -318,13 +318,13 @@ TypeCreate(char *typeName, } /* - * validate size specifications: either positive (fixed-length) or - * -1 (variable-length). + * validate size specifications: either positive (fixed-length) or -1 + * (variable-length). */ - if (! (internalSize > 0 || internalSize == -1)) + if (!(internalSize > 0 || internalSize == -1)) elog(ERROR, "TypeCreate: invalid type internal size %d", internalSize); - if (! (externalSize > 0 || externalSize == -1)) + if (!(externalSize > 0 || externalSize == -1)) elog(ERROR, "TypeCreate: invalid type external size %d", externalSize); @@ -382,7 +382,6 @@ TypeCreate(char *typeName, if (!OidIsValid(procOid)) { - /* * For array types, the input procedures may take 3 args (data * value, element OID, atttypmod); the pg_proc argtype @@ -434,7 +433,7 @@ TypeCreate(char *typeName, */ if (defaultTypeValue) values[i] = DirectFunctionCall1(textin, - CStringGetDatum(defaultTypeValue)); + CStringGetDatum(defaultTypeValue)); else nulls[i] = 'n'; i++; /* 17 */ diff --git a/src/backend/commands/_deadcode/recipe.c b/src/backend/commands/_deadcode/recipe.c index 15a1d0a564..3cc26fa51c 100644 --- a/src/backend/commands/_deadcode/recipe.c +++ b/src/backend/commands/_deadcode/recipe.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/_deadcode/Attic/recipe.c,v 1.13 2001/03/22 06:16:12 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/_deadcode/Attic/recipe.c,v 1.14 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -431,7 +431,6 @@ tg_replaceNumberedParam(Node *expression, { case T_Param: { - /* * the node is a parameter, substitute the entry from the * target list of the child that corresponds to the @@ -445,7 +444,6 @@ tg_replaceNumberedParam(Node *expression, if (p->param_tlist) { - /* * we have a parameter with an attribute like * $N.foo so replace it with a new var node @@ -506,7 +504,6 @@ tg_replaceNumberedParam(Node *expression, break; case T_Expr: { - /* * the node is an expression, we need to recursively call * ourselves until we find parameter nodes @@ -578,7 +575,6 @@ tg_rewriteParamsInExpr(Node *expression, QueryTreeList * inputQlist) { case T_Param: { - /* * the node is a parameter, substitute the entry from the * target list of the child that corresponds to the @@ -594,7 +590,6 @@ tg_rewriteParamsInExpr(Node *expression, QueryTreeList * inputQlist) if (p->param_tlist) { - /* * we have a parameter with an attribute like * $N.foo so match the resname "foo" against the @@ -634,7 +629,6 @@ tg_rewriteParamsInExpr(Node *expression, QueryTreeList * inputQlist) break; case T_Expr: { - /* * the node is an expression, we need to recursively call * ourselves until we find parameter nodes @@ -834,7 +828,6 @@ tg_parseSubQuery(TgRecipe * r, TgNode * n, TeeInfo * teeInfo) { case TG_SQL: { - /* * for SQL ingredients, the SQL query is contained in * the 'src' field @@ -940,7 +933,6 @@ tg_parseSubQuery(TgRecipe * r, TgNode * n, TeeInfo * teeInfo) } else if (n->nodeType == TG_EYE_NODE) { - /* * if we hit an eye, we need to stop and make what we have into a * subrecipe query block @@ -949,7 +941,6 @@ tg_parseSubQuery(TgRecipe * r, TgNode * n, TeeInfo * teeInfo) } else if (n->nodeType == TG_TEE_NODE) { - /* * if we hit a tee, check to see if the parsing has been done for * this tee already by the other parent @@ -958,7 +949,6 @@ tg_parseSubQuery(TgRecipe * r, TgNode * n, TeeInfo * teeInfo) rel = RelationNameGetRelation(n->nodeName); if (RelationIsValid(rel)) { - /* * this tee has already been visited, no need to do any * further processing @@ -1014,7 +1004,6 @@ tg_parseSubQuery(TgRecipe * r, TgNode * n, TeeInfo * teeInfo) if (RelationIsValid(rel)) { - /* * for complex types, create new relation with the same * tuple descriptor as the output table type @@ -1028,7 +1017,6 @@ tg_parseSubQuery(TgRecipe * r, TgNode * n, TeeInfo * teeInfo) } else { - /* * we have to create a relation with one attribute of the * simple base type. That attribute will have an attr @@ -1197,7 +1185,6 @@ replaceSeqScan(Plan *plan, Plan *parent, snode = (Scan *) plan; if (snode->scanrelid == rt_ind) { - /* * found the sequential scan that should be replaced with the * tplan. @@ -1328,5 +1315,4 @@ replaceTeeScans(Plan *plan, Query *parsetree, TeeInfo * teeInfo) } - #endif /* TIOGA */ diff --git a/src/backend/commands/_deadcode/recipe.h b/src/backend/commands/_deadcode/recipe.h index 7ac908fa7c..11dafaefa7 100644 --- a/src/backend/commands/_deadcode/recipe.h +++ b/src/backend/commands/_deadcode/recipe.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: recipe.h,v 1.3 2001/01/24 19:42:53 momjian Exp $ + * $Id: recipe.h,v 1.4 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -16,5 +16,4 @@ #include "nodes/parsenodes.h" extern void beginRecipe(RecipeStmt *stmt); - #endif /* RECIPE_H */ diff --git a/src/backend/commands/_deadcode/version.c b/src/backend/commands/_deadcode/version.c index 2b8b3b6345..3a5170e86a 100644 --- a/src/backend/commands/_deadcode/version.c +++ b/src/backend/commands/_deadcode/version.c @@ -10,7 +10,7 @@ * doesn't work! - jolly 8/19/95 * * - * $Id: version.c,v 1.26 2001/03/23 04:49:52 momjian Exp $ + * $Id: version.c,v 1.27 2001/10/25 05:49:27 momjian Exp $ * * NOTES * At the point the version is defined, 2 physical relations are created @@ -87,7 +87,6 @@ eval_as_new_xact(char *query) CommandCounterIncrement(); pg_exec_query(query); } - #endif /* * Define a version. @@ -129,7 +128,6 @@ DefineVersion(char *name, char *fromRelname, char *date) VersionReplace(name, saved_basename, saved_snapshot); VersionRetrieve(name, saved_basename, saved_snapshot); } - #endif /* @@ -162,7 +160,6 @@ VersionCreate(char *vname, char *bname) sprintf(query_buf, "CREATE TABLE %s_del (DOID oid)", vname); eval_as_new_xact(query_buf); } - #endif @@ -210,7 +207,6 @@ setAttrList(char *bname) return; } - #endif /* @@ -228,7 +224,6 @@ VersionAppend(char *vname, char *bname) eval_as_new_xact(rule_buf); } - #endif /* @@ -257,7 +252,6 @@ where _%s.oid !!= '%s_del.DOID'", /* printf("%s\n",rule_buf); */ } - #endif /* @@ -295,7 +289,6 @@ VersionDelete(char *vname, char *bname, char *snapshot) eval_as_new_xact(rule_buf); #endif /* OLD_REWRITE */ } - #endif /* @@ -349,5 +342,4 @@ VersionReplace(char *vname, char *bname, char *snapshot) /* printf("%s\n",rule_buf); */ } - #endif diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index e7a7d5c066..41c863a5ba 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.22 2001/07/05 19:33:35 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/analyze.c,v 1.23 2001/10/25 05:49:23 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,9 +37,11 @@ /* * Analysis algorithms supported */ -typedef enum { +typedef enum +{ ALG_MINIMAL = 1, /* Compute only most-common-values */ - ALG_SCALAR /* Compute MCV, histogram, sort correlation */ + ALG_SCALAR /* Compute MCV, histogram, sort + * correlation */ } AlgCode; /* @@ -70,7 +72,10 @@ typedef struct Oid eqfunc; /* and associated function */ Oid ltopr; /* '<' operator for datatype, if any */ - /* These fields are filled in by the actual statistics-gathering routine */ + /* + * These fields are filled in by the actual statistics-gathering + * routine + */ bool stats_valid; float4 stanullfrac; /* fraction of entries that are NULL */ int4 stawidth; /* average width */ @@ -101,7 +106,7 @@ typedef struct #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0) -static int MESSAGE_LEVEL; +static int MESSAGE_LEVEL; /* context information for compare_scalars() */ static FmgrInfo *datumCmpFn; @@ -111,19 +116,19 @@ static int *datumCmpTupnoLink; static VacAttrStats *examine_attribute(Relation onerel, int attnum); static int acquire_sample_rows(Relation onerel, HeapTuple *rows, - int targrows, double *totalrows); + int targrows, double *totalrows); static double random_fract(void); static double init_selection_state(int n); static double select_next_random_record(double t, int n, double *stateptr); -static int compare_rows(const void *a, const void *b); -static int compare_scalars(const void *a, const void *b); -static int compare_mcvs(const void *a, const void *b); +static int compare_rows(const void *a, const void *b); +static int compare_scalars(const void *a, const void *b); +static int compare_mcvs(const void *a, const void *b); static void compute_minimal_stats(VacAttrStats *stats, - TupleDesc tupDesc, double totalrows, - HeapTuple *rows, int numrows); + TupleDesc tupDesc, double totalrows, + HeapTuple *rows, int numrows); static void compute_scalar_stats(VacAttrStats *stats, - TupleDesc tupDesc, double totalrows, - HeapTuple *rows, int numrows); + TupleDesc tupDesc, double totalrows, + HeapTuple *rows, int numrows); static void update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats); @@ -154,8 +159,8 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) * Begin a transaction for analyzing this relation. * * Note: All memory allocated during ANALYZE will live in - * TransactionCommandContext or a subcontext thereof, so it will - * all be released by transaction commit at the end of this routine. + * TransactionCommandContext or a subcontext thereof, so it will all + * be released by transaction commit at the end of this routine. */ StartTransactionCommand(); @@ -191,14 +196,14 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) ReleaseSysCache(tuple); /* - * Open the class, getting only a read lock on it, and check permissions. - * Permissions check should match vacuum's check! + * Open the class, getting only a read lock on it, and check + * permissions. Permissions check should match vacuum's check! */ onerel = heap_open(relid, AccessShareLock); - if (! (pg_ownercheck(GetUserId(), RelationGetRelationName(onerel), - RELNAME) || - (is_dbadmin(MyDatabaseId) && !onerel->rd_rel->relisshared))) + if (!(pg_ownercheck(GetUserId(), RelationGetRelationName(onerel), + RELNAME) || + (is_dbadmin(MyDatabaseId) && !onerel->rd_rel->relisshared))) { /* No need for a notice if we already complained during VACUUM */ if (!vacstmt->vacuum) @@ -238,7 +243,7 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) if (i >= attr_cnt) elog(ERROR, "ANALYZE: there is no attribute %s in %s", col, RelationGetRelationName(onerel)); - vacattrstats[tcnt] = examine_attribute(onerel, i+1); + vacattrstats[tcnt] = examine_attribute(onerel, i + 1); if (vacattrstats[tcnt] != NULL) tcnt++; } @@ -251,7 +256,7 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) tcnt = 0; for (i = 0; i < attr_cnt; i++) { - vacattrstats[tcnt] = examine_attribute(onerel, i+1); + vacattrstats[tcnt] = examine_attribute(onerel, i + 1); if (vacattrstats[tcnt] != NULL) tcnt++; } @@ -270,8 +275,8 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) /* * Determine how many rows we need to sample, using the worst case - * from all analyzable columns. We use a lower bound of 100 rows - * to avoid possible overflow in Vitter's algorithm. + * from all analyzable columns. We use a lower bound of 100 rows to + * avoid possible overflow in Vitter's algorithm. */ targrows = 100; for (i = 0; i < attr_cnt; i++) @@ -289,8 +294,8 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) /* * If we are running a standalone ANALYZE, update pages/tuples stats * in pg_class. We have the accurate page count from heap_beginscan, - * but only an approximate number of tuples; therefore, if we are - * part of VACUUM ANALYZE do *not* overwrite the accurate count already + * but only an approximate number of tuples; therefore, if we are part + * of VACUUM ANALYZE do *not* overwrite the accurate count already * inserted by VACUUM. */ if (!vacstmt->vacuum) @@ -300,7 +305,7 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) RelationGetForm(onerel)->relhasindex); /* - * Compute the statistics. Temporary results during the calculations + * Compute the statistics. Temporary results during the calculations * for each column are stored in a child context. The calc routines * are responsible to make sure that whatever they store into the * VacAttrStats structure is allocated in TransactionCommandContext. @@ -338,8 +343,9 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) /* * Emit the completed stats rows into pg_statistic, replacing any - * previous statistics for the target columns. (If there are stats - * in pg_statistic for columns we didn't process, we leave them alone.) + * previous statistics for the target columns. (If there are + * stats in pg_statistic for columns we didn't process, we leave + * them alone.) */ update_attstats(relid, attr_cnt, vacattrstats); } @@ -364,7 +370,7 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt) static VacAttrStats * examine_attribute(Relation onerel, int attnum) { - Form_pg_attribute attr = onerel->rd_att->attrs[attnum-1]; + Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1]; Operator func_operator; Oid oprrest; HeapTuple typtuple; @@ -396,8 +402,8 @@ examine_attribute(Relation onerel, int attnum) return NULL; /* - * If we have "=" then we're at least able to do the minimal algorithm, - * so start filling in a VacAttrStats struct. + * If we have "=" then we're at least able to do the minimal + * algorithm, so start filling in a VacAttrStats struct. */ stats = (VacAttrStats *) palloc(sizeof(VacAttrStats)); MemSet(stats, 0, sizeof(VacAttrStats)); @@ -424,15 +430,14 @@ examine_attribute(Relation onerel, int attnum) { oprrest = ((Form_pg_operator) GETSTRUCT(func_operator))->oprrest; if (oprrest == F_SCALARLTSEL) - { ltopr = oprid(func_operator); - } ReleaseSysCache(func_operator); } stats->ltopr = ltopr; /* - * Determine the algorithm to use (this will get more complicated later) + * Determine the algorithm to use (this will get more complicated + * later) */ if (OidIsValid(ltopr)) { @@ -474,7 +479,7 @@ examine_attribute(Relation onerel, int attnum) * acquire_sample_rows -- acquire a random sample of rows from the table * * Up to targrows rows are collected (if there are fewer than that many - * rows in the table, all rows are collected). When the table is larger + * rows in the table, all rows are collected). When the table is larger * than targrows, a truly random sample is collected: every row has an * equal chance of ending up in the final sample. * @@ -491,8 +496,8 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, int numrows = 0; HeapScanDesc scan; HeapTuple tuple; - ItemPointer lasttuple; - BlockNumber lastblock, + ItemPointer lasttuple; + BlockNumber lastblock, estblock; OffsetNumber lastoffset; int numest; @@ -501,6 +506,7 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, double rstate; Assert(targrows > 1); + /* * Do a simple linear scan until we reach the target number of rows. */ @@ -512,8 +518,9 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, break; } heap_endscan(scan); + /* - * If we ran out of tuples then we're done, no matter how few we + * If we ran out of tuples then we're done, no matter how few we * collected. No sort is needed, since they're already in order. */ if (!HeapTupleIsValid(tuple)) @@ -521,35 +528,40 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, *totalrows = (double) numrows; return numrows; } + /* * Otherwise, start replacing tuples in the sample until we reach the * end of the relation. This algorithm is from Jeff Vitter's paper - * (see full citation below). It works by repeatedly computing the number - * of the next tuple we want to fetch, which will replace a randomly - * chosen element of the reservoir (current set of tuples). At all times - * the reservoir is a true random sample of the tuples we've passed over - * so far, so when we fall off the end of the relation we're done. + * (see full citation below). It works by repeatedly computing the + * number of the next tuple we want to fetch, which will replace a + * randomly chosen element of the reservoir (current set of tuples). + * At all times the reservoir is a true random sample of the tuples + * we've passed over so far, so when we fall off the end of the + * relation we're done. * - * A slight difficulty is that since we don't want to fetch tuples or even - * pages that we skip over, it's not possible to fetch *exactly* the N'th - * tuple at each step --- we don't know how many valid tuples are on - * the skipped pages. We handle this by assuming that the average number - * of valid tuples/page on the pages already scanned over holds good for - * the rest of the relation as well; this lets us estimate which page - * the next tuple should be on and its position in the page. Then we - * fetch the first valid tuple at or after that position, being careful - * not to use the same tuple twice. This approach should still give a - * good random sample, although it's not perfect. + * A slight difficulty is that since we don't want to fetch tuples or + * even pages that we skip over, it's not possible to fetch *exactly* + * the N'th tuple at each step --- we don't know how many valid tuples + * are on the skipped pages. We handle this by assuming that the + * average number of valid tuples/page on the pages already scanned + * over holds good for the rest of the relation as well; this lets us + * estimate which page the next tuple should be on and its position in + * the page. Then we fetch the first valid tuple at or after that + * position, being careful not to use the same tuple twice. This + * approach should still give a good random sample, although it's not + * perfect. */ - lasttuple = &(rows[numrows-1]->t_self); + lasttuple = &(rows[numrows - 1]->t_self); lastblock = ItemPointerGetBlockNumber(lasttuple); lastoffset = ItemPointerGetOffsetNumber(lasttuple); + /* - * If possible, estimate tuples/page using only completely-scanned pages. + * If possible, estimate tuples/page using only completely-scanned + * pages. */ for (numest = numrows; numest > 0; numest--) { - if (ItemPointerGetBlockNumber(&(rows[numest-1]->t_self)) != lastblock) + if (ItemPointerGetBlockNumber(&(rows[numest - 1]->t_self)) != lastblock) break; } if (numest == 0) @@ -558,27 +570,25 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, estblock = lastblock + 1; } else - { estblock = lastblock; - } tuplesperpage = (double) numest / (double) estblock; t = (double) numrows; /* t is the # of records processed so far */ rstate = init_selection_state(targrows); for (;;) { - double targpos; - BlockNumber targblock; - Buffer targbuffer; - Page targpage; - OffsetNumber targoffset, - maxoffset; + double targpos; + BlockNumber targblock; + Buffer targbuffer; + Page targpage; + OffsetNumber targoffset, + maxoffset; t = select_next_random_record(t, targrows, &rstate); /* Try to read the t'th record in the table */ targpos = t / tuplesperpage; targblock = (BlockNumber) targpos; - targoffset = ((int) ((targpos - targblock) * tuplesperpage)) + + targoffset = ((int) ((targpos - targblock) * tuplesperpage)) + FirstOffsetNumber; /* Make sure we are past the last selected record */ if (targblock <= lastblock) @@ -588,19 +598,22 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, targoffset = lastoffset + 1; } /* Loop to find first valid record at or after given position */ - pageloop:; +pageloop:; + /* - * Have we fallen off the end of the relation? (We rely on + * Have we fallen off the end of the relation? (We rely on * heap_beginscan to have updated rd_nblocks.) */ if (targblock >= onerel->rd_nblocks) break; + /* - * We must maintain a pin on the target page's buffer to ensure that - * the maxoffset value stays good (else concurrent VACUUM might - * delete tuples out from under us). Hence, pin the page until we - * are done looking at it. We don't maintain a lock on the page, - * so tuples could get added to it, but we ignore such tuples. + * We must maintain a pin on the target page's buffer to ensure + * that the maxoffset value stays good (else concurrent VACUUM + * might delete tuples out from under us). Hence, pin the page + * until we are done looking at it. We don't maintain a lock on + * the page, so tuples could get added to it, but we ignore such + * tuples. */ targbuffer = ReadBuffer(onerel, targblock); if (!BufferIsValid(targbuffer)) @@ -632,7 +645,7 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, * Found a suitable tuple, so save it, replacing one old * tuple at random */ - int k = (int) (targrows * random_fract()); + int k = (int) (targrows * random_fract()); Assert(k >= 0 && k < targrows); heap_freetuple(rows[k]); @@ -667,13 +680,13 @@ acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows, static double random_fract(void) { - long z; + long z; /* random() can produce endpoint values, try again if so */ do { z = random(); - } while (! (z > 0 && z < MAX_RANDOM_VALUE)); + } while (!(z > 0 && z < MAX_RANDOM_VALUE)); return (double) z / (double) MAX_RANDOM_VALUE; } @@ -702,7 +715,7 @@ static double init_selection_state(int n) { /* Initial value of W (for use when Algorithm Z is first applied) */ - return exp(- log(random_fract())/n); + return exp(-log(random_fract()) / n); } static double @@ -712,8 +725,8 @@ select_next_random_record(double t, int n, double *stateptr) if (t <= (22.0 * n)) { /* Process records using Algorithm X until t is large enough */ - double V, - quot; + double V, + quot; V = random_fract(); /* Generate V */ t += 1; @@ -728,21 +741,21 @@ select_next_random_record(double t, int n, double *stateptr) else { /* Now apply Algorithm Z */ - double W = *stateptr; - double term = t - (double) n + 1; - double S; + double W = *stateptr; + double term = t - (double) n + 1; + double S; for (;;) { - double numer, - numer_lim, - denom; - double U, - X, - lhs, - rhs, - y, - tmp; + double numer, + numer_lim, + denom; + double U, + X, + lhs, + rhs, + y, + tmp; /* Generate U and X */ U = random_fract(); @@ -750,15 +763,15 @@ select_next_random_record(double t, int n, double *stateptr) S = floor(X); /* S is tentatively set to floor(X) */ /* Test if U <= h(S)/cg(X) in the manner of (6.3) */ tmp = (t + 1) / term; - lhs = exp(log(((U * tmp * tmp) * (term + S))/(t + X))/n); - rhs = (((t + X)/(term + S)) * term)/t; + lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n); + rhs = (((t + X) / (term + S)) * term) / t; if (lhs <= rhs) { - W = rhs/lhs; + W = rhs / lhs; break; } /* Test if U <= f(S)/cg(X) */ - y = (((U * (t + 1))/term) * (t + S + 1))/(t + X); + y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X); if ((double) n < S) { denom = t; @@ -774,8 +787,8 @@ select_next_random_record(double t, int n, double *stateptr) y *= numer / denom; denom -= 1; } - W = exp(- log(random_fract())/n); /* Generate W in advance */ - if (exp(log(y)/n) <= (t + X)/t) + W = exp(-log(random_fract()) / n); /* Generate W in advance */ + if (exp(log(y) / n) <= (t + X) / t) break; } t += S + 1; @@ -790,11 +803,11 @@ select_next_random_record(double t, int n, double *stateptr) static int compare_rows(const void *a, const void *b) { - HeapTuple ha = * (HeapTuple *) a; - HeapTuple hb = * (HeapTuple *) b; - BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self); + HeapTuple ha = *(HeapTuple *) a; + HeapTuple hb = *(HeapTuple *) b; + BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self); OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self); - BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self); + BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self); OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self); if (ba < bb) @@ -839,15 +852,18 @@ compute_minimal_stats(VacAttrStats *stats, FmgrInfo f_cmpeq; typedef struct { - Datum value; - int count; + Datum value; + int count; } TrackItem; TrackItem *track; int track_cnt, track_max; int num_mcv = stats->attr->attstattarget; - /* We track up to 2*n values for an n-element MCV list; but at least 10 */ + /* + * We track up to 2*n values for an n-element MCV list; but at least + * 10 + */ track_max = 2 * num_mcv; if (track_max < 10) track_max = 10; @@ -877,19 +893,20 @@ compute_minimal_stats(VacAttrStats *stats, /* * If it's a varlena field, add up widths for average width - * calculation. Note that if the value is toasted, we - * use the toasted width. We don't bother with this calculation - * if it's a fixed-width type. + * calculation. Note that if the value is toasted, we use the + * toasted width. We don't bother with this calculation if it's a + * fixed-width type. */ if (is_varlena) { total_width += VARSIZE(DatumGetPointer(value)); + /* * If the value is toasted, we want to detoast it just once to - * avoid repeated detoastings and resultant excess memory usage - * during the comparisons. Also, check to see if the value is - * excessively wide, and if so don't detoast at all --- just - * ignore the value. + * avoid repeated detoastings and resultant excess memory + * usage during the comparisons. Also, check to see if the + * value is excessively wide, and if so don't detoast at all + * --- just ignore the value. */ if (toast_raw_datum_size(value) > WIDTH_THRESHOLD) { @@ -920,10 +937,10 @@ compute_minimal_stats(VacAttrStats *stats, /* Found a match */ track[j].count++; /* This value may now need to "bubble up" in the track list */ - while (j > 0 && track[j].count > track[j-1].count) + while (j > 0 && track[j].count > track[j - 1].count) { - swapDatum(track[j].value, track[j-1].value); - swapInt(track[j].count, track[j-1].count); + swapDatum(track[j].value, track[j - 1].value); + swapInt(track[j].count, track[j - 1].count); j--; } } @@ -932,10 +949,10 @@ compute_minimal_stats(VacAttrStats *stats, /* No match. Insert at head of count-1 list */ if (track_cnt < track_max) track_cnt++; - for (j = track_cnt-1; j > firstcount1; j--) + for (j = track_cnt - 1; j > firstcount1; j--) { - track[j].value = track[j-1].value; - track[j].count = track[j-1].count; + track[j].value = track[j - 1].value; + track[j].count = track[j - 1].count; } if (firstcount1 < track_cnt) { @@ -948,8 +965,8 @@ compute_minimal_stats(VacAttrStats *stats, /* We can only compute valid stats if we found some non-null values. */ if (nonnull_cnt > 0) { - int nmultiple, - summultiple; + int nmultiple, + summultiple; stats->stats_valid = true; /* Do the simple null-frac and width stats */ @@ -977,9 +994,9 @@ compute_minimal_stats(VacAttrStats *stats, nmultiple == track_cnt) { /* - * Our track list includes every value in the sample, and every - * value appeared more than once. Assume the column has just - * these values. + * Our track list includes every value in the sample, and + * every value appeared more than once. Assume the column has + * just these values. */ stats->stadistinct = track_cnt; } @@ -994,12 +1011,12 @@ compute_minimal_stats(VacAttrStats *stats, * We assume (not very reliably!) that all the multiply-occurring * values are reflected in the final track[] list, and the other * nonnull values all appeared but once. (XXX this usually - * results in a drastic overestimate of ndistinct. Can we do + * results in a drastic overestimate of ndistinct. Can we do * any better?) *---------- */ - int f1 = nonnull_cnt - summultiple; - double term1; + int f1 = nonnull_cnt - summultiple; + double term1; if (f1 < 1) f1 = 1; @@ -1014,16 +1031,16 @@ compute_minimal_stats(VacAttrStats *stats, * a fixed value. */ if (stats->stadistinct > 0.1 * totalrows) - stats->stadistinct = - (stats->stadistinct / totalrows); + stats->stadistinct = -(stats->stadistinct / totalrows); /* * Decide how many values are worth storing as most-common values. * If we are able to generate a complete MCV list (all the values * in the sample will fit, and we think these are all the ones in - * the table), then do so. Otherwise, store only those values - * that are significantly more common than the (estimated) average. - * We set the threshold rather arbitrarily at 25% more than average, - * with at least 2 instances in the sample. + * the table), then do so. Otherwise, store only those values + * that are significantly more common than the (estimated) + * average. We set the threshold rather arbitrarily at 25% more + * than average, with at least 2 instances in the sample. */ if (track_cnt < track_max && toowide_cnt == 0 && stats->stadistinct > 0 && @@ -1034,12 +1051,12 @@ compute_minimal_stats(VacAttrStats *stats, } else { - double ndistinct = stats->stadistinct; - double avgcount, - mincount; + double ndistinct = stats->stadistinct; + double avgcount, + mincount; if (ndistinct < 0) - ndistinct = - ndistinct * totalrows; + ndistinct = -ndistinct * totalrows; /* estimate # of occurrences in sample of a typical value */ avgcount = (double) numrows / ndistinct; /* set minimum threshold count to store a value */ @@ -1062,8 +1079,8 @@ compute_minimal_stats(VacAttrStats *stats, if (num_mcv > 0) { MemoryContext old_context; - Datum *mcv_values; - float4 *mcv_freqs; + Datum *mcv_values; + float4 *mcv_freqs; /* Must copy the target values into TransactionCommandContext */ old_context = MemoryContextSwitchTo(TransactionCommandContext); @@ -1153,19 +1170,20 @@ compute_scalar_stats(VacAttrStats *stats, /* * If it's a varlena field, add up widths for average width - * calculation. Note that if the value is toasted, we - * use the toasted width. We don't bother with this calculation - * if it's a fixed-width type. + * calculation. Note that if the value is toasted, we use the + * toasted width. We don't bother with this calculation if it's a + * fixed-width type. */ if (is_varlena) { total_width += VARSIZE(DatumGetPointer(value)); + /* * If the value is toasted, we want to detoast it just once to - * avoid repeated detoastings and resultant excess memory usage - * during the comparisons. Also, check to see if the value is - * excessively wide, and if so don't detoast at all --- just - * ignore the value. + * avoid repeated detoastings and resultant excess memory + * usage during the comparisons. Also, check to see if the + * value is excessively wide, and if so don't detoast at all + * --- just ignore the value. */ if (toast_raw_datum_size(value) > WIDTH_THRESHOLD) { @@ -1185,11 +1203,11 @@ compute_scalar_stats(VacAttrStats *stats, /* We can only compute valid stats if we found some sortable values. */ if (values_cnt > 0) { - int ndistinct, /* # distinct values in sample */ - nmultiple, /* # that appear multiple times */ - num_hist, - dups_cnt; - int slot_idx = 0; + int ndistinct, /* # distinct values in sample */ + nmultiple, /* # that appear multiple times */ + num_hist, + dups_cnt; + int slot_idx = 0; /* Sort the collected values */ datumCmpFn = &f_cmpfn; @@ -1199,23 +1217,24 @@ compute_scalar_stats(VacAttrStats *stats, sizeof(ScalarItem), compare_scalars); /* - * Now scan the values in order, find the most common ones, - * and also accumulate ordering-correlation statistics. + * Now scan the values in order, find the most common ones, and + * also accumulate ordering-correlation statistics. * * To determine which are most common, we first have to count the - * number of duplicates of each value. The duplicates are adjacent - * in the sorted list, so a brute-force approach is to compare - * successive datum values until we find two that are not equal. - * However, that requires N-1 invocations of the datum comparison - * routine, which are completely redundant with work that was done - * during the sort. (The sort algorithm must at some point have - * compared each pair of items that are adjacent in the sorted order; - * otherwise it could not know that it's ordered the pair correctly.) - * We exploit this by having compare_scalars remember the highest - * tupno index that each ScalarItem has been found equal to. At the - * end of the sort, a ScalarItem's tupnoLink will still point to - * itself if and only if it is the last item of its group of - * duplicates (since the group will be ordered by tupno). + * number of duplicates of each value. The duplicates are + * adjacent in the sorted list, so a brute-force approach is to + * compare successive datum values until we find two that are not + * equal. However, that requires N-1 invocations of the datum + * comparison routine, which are completely redundant with work + * that was done during the sort. (The sort algorithm must at + * some point have compared each pair of items that are adjacent + * in the sorted order; otherwise it could not know that it's + * ordered the pair correctly.) We exploit this by having + * compare_scalars remember the highest tupno index that each + * ScalarItem has been found equal to. At the end of the sort, a + * ScalarItem's tupnoLink will still point to itself if and only + * if it is the last item of its group of duplicates (since the + * group will be ordered by tupno). */ corr_xysum = 0; ndistinct = 0; @@ -1225,7 +1244,8 @@ compute_scalar_stats(VacAttrStats *stats, { int tupno = values[i].tupno; - corr_xysum += (double) i * (double) tupno; + corr_xysum += (double) i *(double) tupno; + dups_cnt++; if (tupnoLink[tupno] == tupno) { @@ -1235,7 +1255,7 @@ compute_scalar_stats(VacAttrStats *stats, { nmultiple++; if (track_cnt < num_mcv || - dups_cnt > track[track_cnt-1].count) + dups_cnt > track[track_cnt - 1].count) { /* * Found a new item for the mcv list; find its @@ -1243,16 +1263,16 @@ compute_scalar_stats(VacAttrStats *stats, * Loop invariant is that j points at an empty/ * replaceable slot. */ - int j; + int j; if (track_cnt < num_mcv) track_cnt++; - for (j = track_cnt-1; j > 0; j--) + for (j = track_cnt - 1; j > 0; j--) { - if (dups_cnt <= track[j-1].count) + if (dups_cnt <= track[j - 1].count) break; - track[j].count = track[j-1].count; - track[j].first = track[j-1].first; + track[j].count = track[j - 1].count; + track[j].first = track[j - 1].first; } track[j].count = dups_cnt; track[j].first = i + 1 - dups_cnt; @@ -1278,8 +1298,8 @@ compute_scalar_stats(VacAttrStats *stats, else if (toowide_cnt == 0 && nmultiple == ndistinct) { /* - * Every value in the sample appeared more than once. Assume the - * column has just these values. + * Every value in the sample appeared more than once. Assume + * the column has just these values. */ stats->stadistinct = ndistinct; } @@ -1294,8 +1314,8 @@ compute_scalar_stats(VacAttrStats *stats, * Overwidth values are assumed to have been distinct. *---------- */ - int f1 = ndistinct - nmultiple + toowide_cnt; - double term1; + int f1 = ndistinct - nmultiple + toowide_cnt; + double term1; if (f1 < 1) f1 = 1; @@ -1310,19 +1330,20 @@ compute_scalar_stats(VacAttrStats *stats, * a fixed value. */ if (stats->stadistinct > 0.1 * totalrows) - stats->stadistinct = - (stats->stadistinct / totalrows); + stats->stadistinct = -(stats->stadistinct / totalrows); /* * Decide how many values are worth storing as most-common values. * If we are able to generate a complete MCV list (all the values * in the sample will fit, and we think these are all the ones in - * the table), then do so. Otherwise, store only those values - * that are significantly more common than the (estimated) average. - * We set the threshold rather arbitrarily at 25% more than average, - * with at least 2 instances in the sample. Also, we won't suppress - * values that have a frequency of at least 1/K where K is the - * intended number of histogram bins; such values might otherwise - * cause us to emit duplicate histogram bin boundaries. + * the table), then do so. Otherwise, store only those values + * that are significantly more common than the (estimated) + * average. We set the threshold rather arbitrarily at 25% more + * than average, with at least 2 instances in the sample. Also, + * we won't suppress values that have a frequency of at least 1/K + * where K is the intended number of histogram bins; such values + * might otherwise cause us to emit duplicate histogram bin + * boundaries. */ if (track_cnt == ndistinct && toowide_cnt == 0 && stats->stadistinct > 0 && @@ -1333,13 +1354,13 @@ compute_scalar_stats(VacAttrStats *stats, } else { - double ndistinct = stats->stadistinct; - double avgcount, - mincount, - maxmincount; + double ndistinct = stats->stadistinct; + double avgcount, + mincount, + maxmincount; if (ndistinct < 0) - ndistinct = - ndistinct * totalrows; + ndistinct = -ndistinct * totalrows; /* estimate # of occurrences in sample of a typical value */ avgcount = (double) numrows / ndistinct; /* set minimum threshold count to store a value */ @@ -1366,8 +1387,8 @@ compute_scalar_stats(VacAttrStats *stats, if (num_mcv > 0) { MemoryContext old_context; - Datum *mcv_values; - float4 *mcv_freqs; + Datum *mcv_values; + float4 *mcv_freqs; /* Must copy the target values into TransactionCommandContext */ old_context = MemoryContextSwitchTo(TransactionCommandContext); @@ -1402,8 +1423,8 @@ compute_scalar_stats(VacAttrStats *stats, if (num_hist >= 2) { MemoryContext old_context; - Datum *hist_values; - int nvals; + Datum *hist_values; + int nvals; /* Sort the MCV items into position order to speed next loop */ qsort((void *) track, num_mcv, @@ -1413,24 +1434,25 @@ compute_scalar_stats(VacAttrStats *stats, * Collapse out the MCV items from the values[] array. * * Note we destroy the values[] array here... but we don't need - * it for anything more. We do, however, still need values_cnt. - * nvals will be the number of remaining entries in values[]. + * it for anything more. We do, however, still need + * values_cnt. nvals will be the number of remaining entries + * in values[]. */ if (num_mcv > 0) { - int src, - dest; - int j; + int src, + dest; + int j; src = dest = 0; j = 0; /* index of next interesting MCV item */ while (src < values_cnt) { - int ncopy; + int ncopy; if (j < num_mcv) { - int first = track[j].first; + int first = track[j].first; if (src >= first) { @@ -1442,9 +1464,7 @@ compute_scalar_stats(VacAttrStats *stats, ncopy = first - src; } else - { ncopy = values_cnt - src; - } memmove(&values[dest], &values[src], ncopy * sizeof(ScalarItem)); src += ncopy; @@ -1461,7 +1481,7 @@ compute_scalar_stats(VacAttrStats *stats, hist_values = (Datum *) palloc(num_hist * sizeof(Datum)); for (i = 0; i < num_hist; i++) { - int pos; + int pos; pos = (i * (nvals - 1)) / (num_hist - 1); hist_values[i] = datumCopy(values[pos].value, @@ -1481,9 +1501,9 @@ compute_scalar_stats(VacAttrStats *stats, if (values_cnt > 1) { MemoryContext old_context; - float4 *corrs; - double corr_xsum, - corr_x2sum; + float4 *corrs; + double corr_xsum, + corr_x2sum; /* Must copy the target values into TransactionCommandContext */ old_context = MemoryContextSwitchTo(TransactionCommandContext); @@ -1499,9 +1519,10 @@ compute_scalar_stats(VacAttrStats *stats, * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6. *---------- */ - corr_xsum = (double) (values_cnt-1) * (double) values_cnt / 2.0; - corr_x2sum = (double) (values_cnt-1) * (double) values_cnt * - (double) (2*values_cnt-1) / 6.0; + corr_xsum = (double) (values_cnt - 1) * (double) values_cnt / 2.0; + corr_x2sum = (double) (values_cnt - 1) * (double) values_cnt * + (double) (2 * values_cnt - 1) / 6.0; + /* And the correlation coefficient reduces to */ corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) / (values_cnt * corr_x2sum - corr_xsum * corr_xsum); @@ -1521,7 +1542,7 @@ compute_scalar_stats(VacAttrStats *stats, * qsort comparator for sorting ScalarItems * * Aside from sorting the items, we update the datumCmpTupnoLink[] array - * whenever two ScalarItems are found to contain equal datums. The array + * whenever two ScalarItems are found to contain equal datums. The array * is indexed by tupno; for each ScalarItem, it contains the highest * tupno that that item's datum has been found to be equal to. This allows * us to avoid additional comparisons in compute_scalar_stats(). @@ -1573,7 +1594,7 @@ compare_mcvs(const void *a, const void *b) * Statistics are stored in several places: the pg_class row for the * relation has stats about the whole relation, and there is a * pg_statistic row for each (non-system) attribute that has ever - * been analyzed. The pg_class values are updated by VACUUM, not here. + * been analyzed. The pg_class values are updated by VACUUM, not here. * * pg_statistic rows are just added or updated normally. This means * that pg_statistic will probably contain some deleted rows at the @@ -1604,7 +1625,9 @@ update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats) FmgrInfo out_function; HeapTuple stup, oldtup; - int i, k, n; + int i, + k, + n; Datum values[Natts_pg_statistic]; char nulls[Natts_pg_statistic]; char replaces[Natts_pg_statistic]; @@ -1626,22 +1649,22 @@ update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats) } i = 0; - values[i++] = ObjectIdGetDatum(relid); /* starelid */ - values[i++] = Int16GetDatum(stats->attnum); /* staattnum */ - values[i++] = Float4GetDatum(stats->stanullfrac); /* stanullfrac */ - values[i++] = Int32GetDatum(stats->stawidth); /* stawidth */ - values[i++] = Float4GetDatum(stats->stadistinct); /* stadistinct */ + values[i++] = ObjectIdGetDatum(relid); /* starelid */ + values[i++] = Int16GetDatum(stats->attnum); /* staattnum */ + values[i++] = Float4GetDatum(stats->stanullfrac); /* stanullfrac */ + values[i++] = Int32GetDatum(stats->stawidth); /* stawidth */ + values[i++] = Float4GetDatum(stats->stadistinct); /* stadistinct */ for (k = 0; k < STATISTIC_NUM_SLOTS; k++) { - values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */ + values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */ } for (k = 0; k < STATISTIC_NUM_SLOTS; k++) { - values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */ + values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */ } for (k = 0; k < STATISTIC_NUM_SLOTS; k++) { - int nnum = stats->numnumbers[k]; + int nnum = stats->numnumbers[k]; if (nnum > 0) { @@ -1653,7 +1676,7 @@ update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats) /* XXX knows more than it should about type float4: */ arry = construct_array(numdatums, nnum, false, sizeof(float4), 'i'); - values[i++] = PointerGetDatum(arry); /* stanumbersN */ + values[i++] = PointerGetDatum(arry); /* stanumbersN */ } else { @@ -1663,7 +1686,7 @@ update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats) } for (k = 0; k < STATISTIC_NUM_SLOTS; k++) { - int ntxt = stats->numvalues[k]; + int ntxt = stats->numvalues[k]; if (ntxt > 0) { @@ -1676,20 +1699,20 @@ update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats) * Convert data values to a text string to be inserted * into the text array. */ - Datum stringdatum; + Datum stringdatum; stringdatum = FunctionCall3(&out_function, stats->stavalues[k][n], - ObjectIdGetDatum(stats->attrtype->typelem), - Int32GetDatum(stats->attr->atttypmod)); + ObjectIdGetDatum(stats->attrtype->typelem), + Int32GetDatum(stats->attr->atttypmod)); txtdatums[n] = DirectFunctionCall1(textin, stringdatum); pfree(DatumGetPointer(stringdatum)); } /* XXX knows more than it should about type text: */ arry = construct_array(txtdatums, ntxt, false, -1, 'i'); - values[i++] = PointerGetDatum(arry); /* stavaluesN */ + values[i++] = PointerGetDatum(arry); /* stavaluesN */ } else { diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c index 6333efafc6..3195f5fc0b 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.80 2001/09/08 01:10:20 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.81 2001/10/25 05:49:23 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -120,7 +120,7 @@ static volatile int notifyInterruptOccurred = 0; /* True if we've registered an on_shmem_exit cleanup */ static bool unlistenExitRegistered = false; -bool Trace_notify = false; +bool Trace_notify = false; static void Async_UnlistenAll(void); @@ -153,13 +153,13 @@ Async_Notify(char *relname) elog(DEBUG, "Async_Notify: %s", relname); /* no point in making duplicate entries in the list ... */ - if (! AsyncExistsPendingNotify(relname)) + if (!AsyncExistsPendingNotify(relname)) { /* - * The name list needs to live until end of transaction, so - * store it in the top transaction context. + * The name list needs to live until end of transaction, so store + * it in the top transaction context. */ - MemoryContext oldcontext; + MemoryContext oldcontext; oldcontext = MemoryContextSwitchTo(TopTransactionContext); @@ -209,7 +209,7 @@ Async_Listen(char *relname, int pid) Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(tuple); if (listener->listenerpid == pid && - strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0) + strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0) { alreadyListener = true; /* No need to scan the rest of the table */ @@ -310,13 +310,14 @@ Async_Unlisten(char *relname, int pid) Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(tuple); if (listener->listenerpid == pid && - strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0) + strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0) { /* Found the matching tuple, delete it */ simple_heap_delete(lRel, &tuple->t_self); + /* - * We assume there can be only one match, so no need - * to scan the rest of the table + * We assume there can be only one match, so no need to scan + * the rest of the table */ break; } @@ -478,16 +479,16 @@ AtCommit_Notify(void) char *relname = NameStr(listener->relname); int32 listenerPID = listener->listenerpid; - if (! AsyncExistsPendingNotify(relname)) + if (!AsyncExistsPendingNotify(relname)) continue; if (listenerPID == MyProcPid) { /* - * Self-notify: no need to bother with table update. - * Indeed, we *must not* clear the notification field in - * this path, or we could lose an outside notify, which'd - * be bad for applications that ignore self-notify messages. + * Self-notify: no need to bother with table update. Indeed, + * we *must not* clear the notification field in this path, or + * we could lose an outside notify, which'd be bad for + * applications that ignore self-notify messages. */ if (Trace_notify) @@ -503,22 +504,20 @@ AtCommit_Notify(void) /* * If someone has already notified this listener, we don't - * bother modifying the table, but we do still send a - * SIGUSR2 signal, just in case that backend missed the - * earlier signal for some reason. It's OK to send the - * signal first, because the other guy can't read - * pg_listener until we unlock it. + * bother modifying the table, but we do still send a SIGUSR2 + * signal, just in case that backend missed the earlier signal + * for some reason. It's OK to send the signal first, because + * the other guy can't read pg_listener until we unlock it. */ if (kill(listenerPID, SIGUSR2) < 0) { /* - * Get rid of pg_listener entry if it refers to a PID - * that no longer exists. Presumably, that backend - * crashed without deleting its pg_listener entries. - * This code used to only delete the entry if - * errno==ESRCH, but as far as I can see we should - * just do it for any failure (certainly at least for - * EPERM too...) + * Get rid of pg_listener entry if it refers to a PID that + * no longer exists. Presumably, that backend crashed + * without deleting its pg_listener entries. This code + * used to only delete the entry if errno==ESRCH, but as + * far as I can see we should just do it for any failure + * (certainly at least for EPERM too...) */ simple_heap_delete(lRel, &lTuple->t_self); } @@ -610,7 +609,6 @@ Async_NotifyHandler(SIGNAL_ARGS) if (notifyInterruptEnabled) { - /* * I'm not sure whether some flavors of Unix might allow another * SIGUSR2 occurrence to recursively interrupt this routine. To @@ -641,7 +639,6 @@ Async_NotifyHandler(SIGNAL_ARGS) } else { - /* * In this path it is NOT SAFE to do much of anything, except * this: @@ -888,11 +885,11 @@ static void ClearPendingNotifies(void) { /* - * We used to have to explicitly deallocate the list members and nodes, - * because they were malloc'd. Now, since we know they are palloc'd - * in TopTransactionContext, we need not do that --- they'll go away - * automatically at transaction exit. We need only reset the list head - * pointer. + * We used to have to explicitly deallocate the list members and + * nodes, because they were malloc'd. Now, since we know they are + * palloc'd in TopTransactionContext, we need not do that --- they'll + * go away automatically at transaction exit. We need only reset the + * list head pointer. */ pendingNotifies = NIL; } diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c index 7d5d3e6cbd..469b4cd1ce 100644 --- a/src/backend/commands/cluster.c +++ b/src/backend/commands/cluster.c @@ -15,7 +15,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.69 2001/08/21 16:36:01 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/cluster.c,v 1.70 2001/10/25 05:49:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -267,10 +267,9 @@ rebuildheap(Oid OIDNewHeap, Oid OIDOldHeap, Oid OIDOldIndex) LocalHeapTuple.t_datamcxt = NULL; LocalHeapTuple.t_data = NULL; heap_fetch(LocalOldHeap, SnapshotNow, &LocalHeapTuple, &LocalBuffer, - ScanDesc); + ScanDesc); if (LocalHeapTuple.t_data != NULL) { - /* * We must copy the tuple because heap_insert() will overwrite * the commit-status fields of the tuple it's handed, and the diff --git a/src/backend/commands/command.c b/src/backend/commands/command.c index 5297f7481d..4d1792a1d3 100644 --- a/src/backend/commands/command.c +++ b/src/backend/commands/command.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/Attic/command.c,v 1.145 2001/10/23 17:39:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/Attic/command.c,v 1.146 2001/10/25 05:49:24 momjian Exp $ * * NOTES * The PerformAddAttribute() code, like most of the relation @@ -32,7 +32,7 @@ #include "catalog/pg_type.h" #include "commands/command.h" #include "commands/trigger.h" -#include "commands/defrem.h" /* For add constraint unique, primary */ +#include "commands/defrem.h" /* For add constraint unique, primary */ #include "executor/execdefs.h" #include "executor/executor.h" #include "miscadmin.h" @@ -43,7 +43,7 @@ #include "parser/parse_expr.h" #include "parser/parse_oper.h" #include "parser/parse_relation.h" -#include "parser/analyze.h" /* For add constraint unique, primary */ +#include "parser/analyze.h" /* For add constraint unique, primary */ #include "utils/acl.h" #include "utils/builtins.h" #include "utils/fmgroids.h" @@ -137,8 +137,8 @@ PerformPortalFetch(char *name, * destination. This supports MOVE, for example, which will pass in * dest = None. * - * EXCEPTION: if the query's original dest is RemoteInternal (ie, it's - * a binary cursor) and the request is Remote, we do NOT override the + * EXCEPTION: if the query's original dest is RemoteInternal (ie, it's a + * binary cursor) and the request is Remote, we do NOT override the * original dest. This is necessary since a FETCH command will pass * dest = Remote, not knowing whether the cursor is binary or not. */ @@ -183,10 +183,11 @@ PerformPortalFetch(char *name, if (!portal->atEnd) { ExecutorRun(queryDesc, estate, EXEC_FOR, (long) count); + /* - * I use CMD_UPDATE, because no CMD_MOVE or the like - * exists, and I would like to provide the same - * kind of info as CMD_UPDATE + * I use CMD_UPDATE, because no CMD_MOVE or the like exists, + * and I would like to provide the same kind of info as + * CMD_UPDATE */ UpdateCommandInfo(CMD_UPDATE, 0, estate->es_processed); if (estate->es_processed > 0) @@ -200,10 +201,11 @@ PerformPortalFetch(char *name, if (!portal->atStart) { ExecutorRun(queryDesc, estate, EXEC_BACK, (long) count); + /* - * I use CMD_UPDATE, because no CMD_MOVE or the like - * exists, and I would like to provide the same - * kind of info as CMD_UPDATE + * I use CMD_UPDATE, because no CMD_MOVE or the like exists, + * and I would like to provide the same kind of info as + * CMD_UPDATE */ UpdateCommandInfo(CMD_UPDATE, 0, estate->es_processed); if (estate->es_processed > 0) @@ -356,8 +358,8 @@ AlterTableAddColumn(const char *relationName, /* * find_all_inheritors does the recursive search of the - * inheritance hierarchy, so all we have to do is process all - * of the relids in the list that it returns. + * inheritance hierarchy, so all we have to do is process all of + * the relids in the list that it returns. */ foreach(child, children) { @@ -382,12 +384,12 @@ AlterTableAddColumn(const char *relationName, * Implementation restrictions: because we don't touch the table rows, * the new column values will initially appear to be NULLs. (This * happens because the heap tuple access routines always check for - * attnum > # of attributes in tuple, and return NULL if so.) Therefore - * we can't support a DEFAULT value in SQL92-compliant fashion, and - * we also can't allow a NOT NULL constraint. + * attnum > # of attributes in tuple, and return NULL if so.) + * Therefore we can't support a DEFAULT value in SQL92-compliant + * fashion, and we also can't allow a NOT NULL constraint. * - * We do allow CHECK constraints, even though these theoretically - * could fail for NULL rows (eg, CHECK (newcol IS NOT NULL)). + * We do allow CHECK constraints, even though these theoretically could + * fail for NULL rows (eg, CHECK (newcol IS NOT NULL)). */ if (colDef->raw_default || colDef->cooked_default) elog(ERROR, "Adding columns with defaults is not implemented." @@ -512,8 +514,8 @@ AlterTableAddColumn(const char *relationName, /* * Add any CHECK constraints attached to the new column. * - * To do this we must re-open the rel so that its new attr list - * gets loaded into the relcache. + * To do this we must re-open the rel so that its new attr list gets + * loaded into the relcache. */ if (colDef->constraints != NIL) { @@ -1012,7 +1014,6 @@ RemoveColumnReferences(Oid reloid, int attnum, bool checkonly, HeapTuple reltup) return checkok; } - #endif /* _DROP_COLUMN_HACK__ */ /* @@ -1169,7 +1170,7 @@ AlterTableDropColumn(const char *relationName, heap_freetuple(reltup); heap_close(rel, NoLock); #else - elog(ERROR, "ALTER TABLE / DROP COLUMN is not implemented"); + elog(ERROR, "ALTER TABLE / DROP COLUMN is not implemented"); #endif /* _DROP_COLUMN_HACK__ */ } @@ -1183,8 +1184,8 @@ AlterTableAddConstraint(char *relationName, bool inh, List *newConstraints) { Relation rel; - Oid myrelid; - List *listptr; + Oid myrelid; + List *listptr; #ifndef NO_SECURITY if (!pg_ownercheck(GetUserId(), relationName, RELNAME)) @@ -1199,7 +1200,8 @@ AlterTableAddConstraint(char *relationName, rel = heap_openr(relationName, AccessExclusiveLock); myrelid = RelationGetRelid(rel); - if (inh) { + if (inh) + { List *child, *children; @@ -1208,8 +1210,8 @@ AlterTableAddConstraint(char *relationName, /* * find_all_inheritors does the recursive search of the - * inheritance hierarchy, so all we have to do is process all - * of the relids in the list that it returns. + * inheritance hierarchy, so all we have to do is process all of + * the relids in the list that it returns. */ foreach(child, children) { @@ -1229,372 +1231,418 @@ AlterTableAddConstraint(char *relationName, foreach(listptr, newConstraints) { - Node *newConstraint = lfirst(listptr); - - switch (nodeTag(newConstraint)) - { - case T_Constraint: - { - Constraint *constr = (Constraint *) newConstraint; + Node *newConstraint = lfirst(listptr); - switch (constr->contype) + switch (nodeTag(newConstraint)) + { + case T_Constraint: { - case CONSTR_CHECK: - { - ParseState *pstate; - bool successful = true; - HeapScanDesc scan; - ExprContext *econtext; - TupleTableSlot *slot; - HeapTuple tuple; - RangeTblEntry *rte; - List *qual; - Node *expr; - char *name; - - if (constr->name) - name = constr->name; - else - name = "<unnamed>"; - - /* - * We need to make a parse state and range - * table to allow us to transformExpr and - * fix_opids to get a version of the - * expression we can pass to ExecQual - */ - pstate = make_parsestate(NULL); - rte = addRangeTableEntry(pstate, relationName, NULL, - false, true); - addRTEtoQuery(pstate, rte, true, true); - - /* Convert the A_EXPR in raw_expr into an EXPR */ - expr = transformExpr(pstate, constr->raw_expr, - EXPR_COLUMN_FIRST); - - /* - * Make sure it yields a boolean result. - */ - if (exprType(expr) != BOOLOID) - elog(ERROR, "CHECK '%s' does not yield boolean result", - name); - - /* - * Make sure no outside relations are referred - * to. - */ - if (length(pstate->p_rtable) != 1) - elog(ERROR, "Only relation '%s' can be referenced in CHECK", - relationName); - - /* - * Might as well try to reduce any constant - * expressions. - */ - expr = eval_const_expressions(expr); - - /* And fix the opids */ - fix_opids(expr); - - qual = makeList1(expr); - - /* Make tuple slot to hold tuples */ - slot = MakeTupleTableSlot(); - ExecSetSlotDescriptor(slot, RelationGetDescr(rel), false); - /* Make an expression context for ExecQual */ - econtext = MakeExprContext(slot, CurrentMemoryContext); - - /* - * Scan through the rows now, checking the - * expression at each row. - */ - scan = heap_beginscan(rel, false, SnapshotNow, 0, NULL); - - while (HeapTupleIsValid(tuple = heap_getnext(scan, 0))) + Constraint *constr = (Constraint *) newConstraint; + + switch (constr->contype) + { + case CONSTR_CHECK: { - ExecStoreTuple(tuple, slot, InvalidBuffer, false); - if (!ExecQual(qual, econtext, true)) + ParseState *pstate; + bool successful = true; + HeapScanDesc scan; + ExprContext *econtext; + TupleTableSlot *slot; + HeapTuple tuple; + RangeTblEntry *rte; + List *qual; + Node *expr; + char *name; + + if (constr->name) + name = constr->name; + else + name = "<unnamed>"; + + /* + * We need to make a parse state and range + * table to allow us to transformExpr and + * fix_opids to get a version of the + * expression we can pass to ExecQual + */ + pstate = make_parsestate(NULL); + rte = addRangeTableEntry(pstate, relationName, NULL, + false, true); + addRTEtoQuery(pstate, rte, true, true); + + /* + * Convert the A_EXPR in raw_expr into an + * EXPR + */ + expr = transformExpr(pstate, constr->raw_expr, + EXPR_COLUMN_FIRST); + + /* + * Make sure it yields a boolean result. + */ + if (exprType(expr) != BOOLOID) + elog(ERROR, "CHECK '%s' does not yield boolean result", + name); + + /* + * Make sure no outside relations are + * referred to. + */ + if (length(pstate->p_rtable) != 1) + elog(ERROR, "Only relation '%s' can be referenced in CHECK", + relationName); + + /* + * Might as well try to reduce any + * constant expressions. + */ + expr = eval_const_expressions(expr); + + /* And fix the opids */ + fix_opids(expr); + + qual = makeList1(expr); + + /* Make tuple slot to hold tuples */ + slot = MakeTupleTableSlot(); + ExecSetSlotDescriptor(slot, RelationGetDescr(rel), false); + /* Make an expression context for ExecQual */ + econtext = MakeExprContext(slot, CurrentMemoryContext); + + /* + * Scan through the rows now, checking the + * expression at each row. + */ + scan = heap_beginscan(rel, false, SnapshotNow, 0, NULL); + + while (HeapTupleIsValid(tuple = heap_getnext(scan, 0))) { - successful = false; - break; + ExecStoreTuple(tuple, slot, InvalidBuffer, false); + if (!ExecQual(qual, econtext, true)) + { + successful = false; + break; + } + ResetExprContext(econtext); } - ResetExprContext(econtext); - } - heap_endscan(scan); + heap_endscan(scan); - FreeExprContext(econtext); - pfree(slot); + FreeExprContext(econtext); + pfree(slot); - if (!successful) - elog(ERROR, "AlterTableAddConstraint: rejected due to CHECK constraint %s", name); + if (!successful) + elog(ERROR, "AlterTableAddConstraint: rejected due to CHECK constraint %s", 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. - */ - AddRelationRawConstraints(rel, NIL, + /* + * 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)); - break; - } - case CONSTR_UNIQUE: - { - char *iname = constr->name; - bool istemp = is_temp_rel_name(relationName); - List *indexoidlist; - List *indexoidscan; - int num_keys; - bool index_found = false; - bool index_found_unique = false; - bool index_found_primary = false; - - /* If the constraint name is not specified, generate a name */ - if (iname == NULL) { - Oid indoid; - int pass = 0; - char *typename = palloc(NAMEDATALEN); - Ident *key; - - /* Assume that the length of the attr list is already > 0 */ - - /* Get the first attribute so we can use its name */ - key = (Ident *)lfirst(constr->keys); - - /* Initialise typename to 'key' */ - snprintf(typename, NAMEDATALEN, "key"); - - for (;;) - { - iname = makeObjectName(relationName, key->name, typename); - - /* Check for a conflict */ - indoid = RelnameFindRelid(iname); - - /* If the oid was not found, then we have a safe name */ - if ((!istemp && !OidIsValid(indoid)) || - (istemp && !is_temp_rel_name(iname))) - break; - - /* Found a conflict, so try a new name component */ - pfree(iname); - snprintf(typename, NAMEDATALEN, "key%d", ++pass); - } - } - - /* Need to check for unique key already on field(s) */ - - /* - * First we check for limited correctness of the - * constraint - */ - - /* Loop over all indices on the relation */ - indexoidlist = RelationGetIndexList(rel); - - foreach(indexoidscan, indexoidlist) - { - Oid indexoid = lfirsti(indexoidscan); - HeapTuple indexTuple; - Form_pg_index indexStruct; - List *keyl; - int i; - - indexTuple = SearchSysCache(INDEXRELID, - ObjectIdGetDatum(indexoid), - 0, 0, 0); - - if (!HeapTupleIsValid(indexTuple)) - elog(ERROR, "ALTER TABLE/ADD CONSTRAINT: Index \"%u\" not found", - indexoid); - indexStruct = (Form_pg_index) GETSTRUCT(indexTuple); - - /* - * Make sure this index has the same number of - * keys as the constraint -- It obviously won't match otherwise. - */ - for (i = 0; i < INDEX_MAX_KEYS && indexStruct->indkey[i] != 0; i++) - ; - num_keys = length(constr->keys); - - if (i == num_keys) - { - /* Loop over each key in the constraint and check that there is a - corresponding key in the index. */ - int keys_matched = 0; - - i = 0; - foreach(keyl, constr->keys) - { - Ident *key = lfirst(keyl); - int keyno = indexStruct->indkey[i]; - - /* Look at key[i] in the index and check that it is over the same column - as key[i] in the constraint. This is to differentiate between (a,b) - and (b,a) */ - if (namestrcmp(attnumAttName(rel, keyno), - key->name) == 0) - keys_matched++; - else - break; - i++; - } - if (keys_matched == num_keys) { - index_found = true; - index_found_unique = indexStruct->indisunique; - index_found_primary = indexStruct->indisprimary; - } - } - ReleaseSysCache(indexTuple); - if (index_found_unique || index_found_primary) - break; - } - - freeList(indexoidlist); - - if (index_found_primary) - elog(ERROR, "Unique primary key already defined on relation \"%s\"", relationName); - else if (index_found_unique) - elog(ERROR, "Unique constraint already defined on the specified attributes in relation \"%s\"", relationName); - - /* If everything is ok, create the new index (constraint) */ - DefineIndex( - relationName, - iname, - "btree", - constr->keys, - true, - false, - NULL, - NIL); - - /* Issue notice */ - elog(NOTICE, "ALTER TABLE/ADD UNIQUE will create implicit index '%s' for table '%s'", - iname, relationName); - if (index_found) - elog(NOTICE, "Unique constraint supercedes existing index on relation \"%s\". Drop the existing index to remove redundancy.", relationName); - pfree(iname); - - break; - } - default: - elog(ERROR, "ALTER TABLE / ADD CONSTRAINT is not implemented for that constraint type."); - } - break; - } - case T_FkConstraint: - { - FkConstraint *fkconstraint = (FkConstraint *) newConstraint; - Relation pkrel; - HeapScanDesc scan; - HeapTuple tuple; - Trigger trig; - List *list; - int count; - - if (is_temp_rel_name(fkconstraint->pktable_name) && - !is_temp_rel_name(relationName)) - elog(ERROR, "ALTER TABLE / ADD CONSTRAINT: Unable to reference temporary table from permanent table constraint."); - - /* - * Grab an exclusive lock on the pk table, so that someone - * doesn't delete rows out from under us. - */ - - pkrel = heap_openr(fkconstraint->pktable_name, AccessExclusiveLock); - if (pkrel->rd_rel->relkind != RELKIND_RELATION) - elog(ERROR, "referenced table \"%s\" not a relation", - fkconstraint->pktable_name); - heap_close(pkrel, NoLock); - - /* - * First we check for limited correctness of the constraint. - * - * NOTE: we assume parser has already checked for existence - * of an appropriate unique index on the referenced relation, - * and that the column datatypes are comparable. - * - * Scan through each tuple, calling the RI_FKey_Match_Ins - * (insert trigger) as if that tuple had just been - * inserted. If any of those fail, it should elog(ERROR) - * and that's that. - */ - - trig.tgoid = 0; - if (fkconstraint->constr_name) - trig.tgname = fkconstraint->constr_name; - else - trig.tgname = "<unknown>"; - trig.tgfoid = 0; - trig.tgtype = 0; - trig.tgenabled = TRUE; - trig.tgisconstraint = TRUE; - trig.tginitdeferred = FALSE; - trig.tgdeferrable = FALSE; - - trig.tgargs = (char **) palloc( - sizeof(char *) * (4 + length(fkconstraint->fk_attrs) - + length(fkconstraint->pk_attrs))); + break; + } + case CONSTR_UNIQUE: + { + char *iname = constr->name; + bool istemp = is_temp_rel_name(relationName); + List *indexoidlist; + List *indexoidscan; + int num_keys; + bool index_found = false; + bool index_found_unique = false; + bool index_found_primary = false; + + /* + * If the constraint name is not + * specified, generate a name + */ + if (iname == NULL) + { + Oid indoid; + int pass = 0; + char *typename = palloc(NAMEDATALEN); + Ident *key; + + /* + * Assume that the length of the attr + * list is already > 0 + */ + + /* + * Get the first attribute so we can + * use its name + */ + key = (Ident *) lfirst(constr->keys); + + /* Initialise typename to 'key' */ + snprintf(typename, NAMEDATALEN, "key"); + + for (;;) + { + iname = makeObjectName(relationName, key->name, typename); + + /* Check for a conflict */ + indoid = RelnameFindRelid(iname); + + /* + * If the oid was not found, then + * we have a safe name + */ + if ((!istemp && !OidIsValid(indoid)) || + (istemp && !is_temp_rel_name(iname))) + break; + + /* + * Found a conflict, so try a new + * name component + */ + pfree(iname); + snprintf(typename, NAMEDATALEN, "key%d", ++pass); + } + } - if (fkconstraint->constr_name) - trig.tgargs[0] = fkconstraint->constr_name; - else - trig.tgargs[0] = "<unknown>"; - trig.tgargs[1] = (char *) relationName; - trig.tgargs[2] = fkconstraint->pktable_name; - trig.tgargs[3] = fkconstraint->match_type; - count = 4; - foreach(list, fkconstraint->fk_attrs) - { - Ident *fk_at = lfirst(list); + /* + * Need to check for unique key already on + * field(s) + */ - trig.tgargs[count] = fk_at->name; - count += 2; - } - count = 5; - foreach(list, fkconstraint->pk_attrs) - { - Ident *pk_at = lfirst(list); + /* + * First we check for limited correctness + * of the constraint + */ - trig.tgargs[count] = pk_at->name; - count += 2; - } - trig.tgnargs = count - 1; + /* Loop over all indices on the relation */ + indexoidlist = RelationGetIndexList(rel); - scan = heap_beginscan(rel, false, SnapshotNow, 0, NULL); + foreach(indexoidscan, indexoidlist) + { + Oid indexoid = lfirsti(indexoidscan); + HeapTuple indexTuple; + Form_pg_index indexStruct; + List *keyl; + int i; + + indexTuple = SearchSysCache(INDEXRELID, + ObjectIdGetDatum(indexoid), + 0, 0, 0); + + if (!HeapTupleIsValid(indexTuple)) + elog(ERROR, "ALTER TABLE/ADD CONSTRAINT: Index \"%u\" not found", + indexoid); + indexStruct = (Form_pg_index) GETSTRUCT(indexTuple); + + /* + * Make sure this index has the same + * number of keys as the constraint -- + * It obviously won't match otherwise. + */ + for (i = 0; i < INDEX_MAX_KEYS && indexStruct->indkey[i] != 0; i++) + ; + num_keys = length(constr->keys); + + if (i == num_keys) + { + /* + * Loop over each key in the + * constraint and check that there + * is a corresponding key in the + * index. + */ + int keys_matched = 0; + + i = 0; + foreach(keyl, constr->keys) + { + Ident *key = lfirst(keyl); + int keyno = indexStruct->indkey[i]; + + /* + * Look at key[i] in the index + * and check that it is over + * the same column as key[i] + * in the constraint. This is + * to differentiate between + * (a,b) and (b,a) + */ + if (namestrcmp(attnumAttName(rel, keyno), + key->name) == 0) + keys_matched++; + else + break; + i++; + } + if (keys_matched == num_keys) + { + index_found = true; + index_found_unique = indexStruct->indisunique; + index_found_primary = indexStruct->indisprimary; + } + } + ReleaseSysCache(indexTuple); + if (index_found_unique || index_found_primary) + break; + } - while (HeapTupleIsValid(tuple = heap_getnext(scan, 0))) + freeList(indexoidlist); + + if (index_found_primary) + elog(ERROR, "Unique primary key already defined on relation \"%s\"", relationName); + else if (index_found_unique) + elog(ERROR, "Unique constraint already defined on the specified attributes in relation \"%s\"", relationName); + + /* + * If everything is ok, create the new + * index (constraint) + */ + DefineIndex( + relationName, + iname, + "btree", + constr->keys, + true, + false, + NULL, + NIL); + + /* Issue notice */ + elog(NOTICE, "ALTER TABLE/ADD UNIQUE will create implicit index '%s' for table '%s'", + iname, relationName); + if (index_found) + elog(NOTICE, "Unique constraint supercedes existing index on relation \"%s\". Drop the existing index to remove redundancy.", relationName); + pfree(iname); + + break; + } + default: + elog(ERROR, "ALTER TABLE / ADD CONSTRAINT is not implemented for that constraint type."); + } + break; + } + case T_FkConstraint: { - /* Make a call to the check function */ - /* No parameters are passed, but we do set a context */ - FunctionCallInfoData fcinfo; - TriggerData trigdata; - - MemSet(&fcinfo, 0, sizeof(fcinfo)); - /* We assume RI_FKey_check_ins won't look at flinfo... */ - - trigdata.type = T_TriggerData; - trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW; - trigdata.tg_relation = rel; - trigdata.tg_trigtuple = tuple; - trigdata.tg_newtuple = NULL; - trigdata.tg_trigger = &trig; - - fcinfo.context = (Node *) &trigdata; + FkConstraint *fkconstraint = (FkConstraint *) newConstraint; + Relation pkrel; + HeapScanDesc scan; + HeapTuple tuple; + Trigger trig; + List *list; + int count; + + if (is_temp_rel_name(fkconstraint->pktable_name) && + !is_temp_rel_name(relationName)) + elog(ERROR, "ALTER TABLE / ADD CONSTRAINT: Unable to reference temporary table from permanent table constraint."); + + /* + * Grab an exclusive lock on the pk table, so that + * someone doesn't delete rows out from under us. + */ + + pkrel = heap_openr(fkconstraint->pktable_name, AccessExclusiveLock); + if (pkrel->rd_rel->relkind != RELKIND_RELATION) + elog(ERROR, "referenced table \"%s\" not a relation", + fkconstraint->pktable_name); + heap_close(pkrel, NoLock); + + /* + * First we check for limited correctness of the + * constraint. + * + * NOTE: we assume parser has already checked for + * existence of an appropriate unique index on the + * referenced relation, and that the column datatypes + * are comparable. + * + * Scan through each tuple, calling the RI_FKey_Match_Ins + * (insert trigger) as if that tuple had just been + * inserted. If any of those fail, it should + * elog(ERROR) and that's that. + */ + + trig.tgoid = 0; + if (fkconstraint->constr_name) + trig.tgname = fkconstraint->constr_name; + else + trig.tgname = "<unknown>"; + trig.tgfoid = 0; + trig.tgtype = 0; + trig.tgenabled = TRUE; + trig.tgisconstraint = TRUE; + trig.tginitdeferred = FALSE; + trig.tgdeferrable = FALSE; + + trig.tgargs = (char **) palloc( + sizeof(char *) * (4 + length(fkconstraint->fk_attrs) + + length(fkconstraint->pk_attrs))); - RI_FKey_check_ins(&fcinfo); + if (fkconstraint->constr_name) + trig.tgargs[0] = fkconstraint->constr_name; + else + trig.tgargs[0] = "<unknown>"; + trig.tgargs[1] = (char *) relationName; + trig.tgargs[2] = fkconstraint->pktable_name; + trig.tgargs[3] = fkconstraint->match_type; + count = 4; + foreach(list, fkconstraint->fk_attrs) + { + Ident *fk_at = lfirst(list); + + trig.tgargs[count] = fk_at->name; + count += 2; + } + count = 5; + foreach(list, fkconstraint->pk_attrs) + { + Ident *pk_at = lfirst(list); + + trig.tgargs[count] = pk_at->name; + count += 2; + } + trig.tgnargs = count - 1; + + scan = heap_beginscan(rel, false, SnapshotNow, 0, NULL); + + while (HeapTupleIsValid(tuple = heap_getnext(scan, 0))) + { + /* Make a call to the check function */ + + /* + * No parameters are passed, but we do set a + * context + */ + FunctionCallInfoData fcinfo; + TriggerData trigdata; + + MemSet(&fcinfo, 0, sizeof(fcinfo)); + + /* + * We assume RI_FKey_check_ins won't look at + * flinfo... + */ + + trigdata.type = T_TriggerData; + trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW; + trigdata.tg_relation = rel; + trigdata.tg_trigtuple = tuple; + trigdata.tg_newtuple = NULL; + trigdata.tg_trigger = &trig; + + fcinfo.context = (Node *) &trigdata; + + RI_FKey_check_ins(&fcinfo); + } + heap_endscan(scan); + + pfree(trig.tgargs); + break; } - heap_endscan(scan); - - pfree(trig.tgargs); - break; - } - default: - elog(ERROR, "ALTER TABLE / ADD CONSTRAINT unable to determine type of constraint passed"); - } + default: + elog(ERROR, "ALTER TABLE / ADD CONSTRAINT unable to determine type of constraint passed"); + } } /* Close rel, but keep lock till commit */ @@ -1614,7 +1662,7 @@ AlterTableDropConstraint(const char *relationName, bool inh, const char *constrName, int behavior) { - Relation rel; + Relation rel; int deleted; #ifndef NO_SECURITY @@ -1622,14 +1670,16 @@ AlterTableDropConstraint(const char *relationName, elog(ERROR, "ALTER TABLE: permission denied"); #endif - /* We don't support CASCADE yet - in fact, RESTRICT - * doesn't work to the spec either! */ + /* + * We don't support CASCADE yet - in fact, RESTRICT doesn't work to + * the spec either! + */ if (behavior == CASCADE) elog(ERROR, "ALTER TABLE / DROP CONSTRAINT does not support the CASCADE keyword"); /* - * Acquire an exclusive lock on the target relation for - * the duration of the operation. + * Acquire an exclusive lock on the target relation for the duration + * of the operation. */ rel = heap_openr(relationName, AccessExclusiveLock); @@ -1640,9 +1690,10 @@ AlterTableDropConstraint(const char *relationName, relationName); /* - * Since all we have is the name of the constraint, we have to look through - * all catalogs that could possibly contain a constraint for this relation. - * We also keep a count of the number of constraints removed. + * Since all we have is the name of the constraint, we have to look + * through all catalogs that could possibly contain a constraint for + * this relation. We also keep a count of the number of constraints + * removed. */ deleted = 0; @@ -1654,7 +1705,8 @@ AlterTableDropConstraint(const char *relationName, deleted += RemoveCheckConstraint(rel, constrName, inh); /* - * Now we remove NULL, UNIQUE, PRIMARY KEY and FOREIGN KEY constraints. + * Now we remove NULL, UNIQUE, PRIMARY KEY and FOREIGN KEY + * constraints. * * Unimplemented. */ @@ -1887,10 +1939,11 @@ AlterTableCreateToastTable(const char *relationName, bool silent) * Create unique index on chunk_id, chunk_seq. * * NOTE: the tuple toaster could actually function with a single-column - * index on chunk_id only. However, it couldn't be unique then. We - * want it to be unique as a check against the possibility of duplicate - * TOAST chunk OIDs. Too, the index might be a little more efficient this - * way, since btree isn't all that happy with large numbers of equal keys. + * index on chunk_id only. However, it couldn't be unique then. We + * want it to be unique as a check against the possibility of + * duplicate TOAST chunk OIDs. Too, the index might be a little more + * efficient this way, since btree isn't all that happy with large + * numbers of equal keys. */ indexInfo = makeNode(IndexInfo); @@ -1910,9 +1963,9 @@ AlterTableCreateToastTable(const char *relationName, bool silent) true, true); /* - * Update toast rel's pg_class entry to show that it has an index. - * The index OID is stored into the reltoastidxid field for - * easy access by the tuple toaster. + * Update toast rel's pg_class entry to show that it has an index. The + * index OID is stored into the reltoastidxid field for easy access by + * the tuple toaster. */ setRelhasindex(toast_relid, true, true, toast_idxid); @@ -1990,7 +2043,7 @@ needs_toast_table(Relation rel) MAXALIGN(data_length); return (tuple_length > TOAST_TUPLE_THRESHOLD); } - + /* * * LOCK TABLE @@ -1999,38 +2052,39 @@ needs_toast_table(Relation rel) void LockTableCommand(LockStmt *lockstmt) { - List *p; - Relation rel; - - /* Iterate over the list and open, lock, and close the relations - one at a time + List *p; + Relation rel; + + /* + * Iterate over the list and open, lock, and close the relations one + * at a time */ - foreach(p, lockstmt->rellist) - { - char* relname = strVal(lfirst(p)); - int aclresult; - - rel = heap_openr(relname, NoLock); - - if (rel->rd_rel->relkind != RELKIND_RELATION) - elog(ERROR, "LOCK TABLE: %s is not a table", - relname); - - if (lockstmt->mode == AccessShareLock) - aclresult = pg_aclcheck(relname, GetUserId(), - ACL_SELECT); - else - aclresult = pg_aclcheck(relname, GetUserId(), - ACL_UPDATE | ACL_DELETE); + foreach(p, lockstmt->rellist) + { + char *relname = strVal(lfirst(p)); + int aclresult; - if (aclresult != ACLCHECK_OK) - elog(ERROR, "LOCK TABLE: permission denied"); + rel = heap_openr(relname, NoLock); - LockRelation(rel, lockstmt->mode); - - heap_close(rel, NoLock); /* close rel, keep lock */ - } + if (rel->rd_rel->relkind != RELKIND_RELATION) + elog(ERROR, "LOCK TABLE: %s is not a table", + relname); + + if (lockstmt->mode == AccessShareLock) + aclresult = pg_aclcheck(relname, GetUserId(), + ACL_SELECT); + else + aclresult = pg_aclcheck(relname, GetUserId(), + ACL_UPDATE | ACL_DELETE); + + if (aclresult != ACLCHECK_OK) + elog(ERROR, "LOCK TABLE: permission denied"); + + LockRelation(rel, lockstmt->mode); + + heap_close(rel, NoLock); /* close rel, keep lock */ + } } diff --git a/src/backend/commands/comment.c b/src/backend/commands/comment.c index 14e591288a..647cb55b7e 100644 --- a/src/backend/commands/comment.c +++ b/src/backend/commands/comment.c @@ -7,7 +7,7 @@ * Copyright (c) 1999-2001, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/comment.c,v 1.33 2001/10/03 20:54:20 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/comment.c,v 1.34 2001/10/25 05:49:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -332,9 +332,10 @@ CommentRelation(int reltype, char *relname, char *comment) elog(ERROR, "you are not permitted to comment on class '%s'", relname); /* - * Open the relation. We do this mainly to acquire a lock that ensures - * no one else drops the relation before we commit. (If they did, they'd - * fail to remove the entry we are about to make in pg_description.) + * Open the relation. We do this mainly to acquire a lock that + * ensures no one else drops the relation before we commit. (If they + * did, they'd fail to remove the entry we are about to make in + * pg_description.) * * heap_openr will complain if it's an index, so we must do this: */ diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c index ce7ea9fd6d..7f1e288fab 100644 --- a/src/backend/commands/copy.c +++ b/src/backend/commands/copy.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.141 2001/08/10 18:57:34 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.142 2001/10/25 05:49:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -76,7 +76,6 @@ static StringInfoData attribute_buf; #ifdef MULTIBYTE static int client_encoding; static int server_encoding; - #endif @@ -209,7 +208,6 @@ CopyDonePeek(FILE *fp, int c, int pickup) { if (pickup) { - /* * We want to pick it up - just receive again into dummy * buffer @@ -240,8 +238,8 @@ CopyDonePeek(FILE *fp, int c, int pickup) * (<from> = TRUE means we are inserting into the table.) * * If <pipe> is false, transfer is between the table and the file named - * <filename>. Otherwise, transfer is between the table and our regular - * input/output stream. The latter could be either stdin/stdout or a + * <filename>. Otherwise, transfer is between the table and our regular + * input/output stream. The latter could be either stdin/stdout or a * socket, depending on whether we're running under Postmaster control. * * Iff <binary>, unload or reload in the binary format, as opposed to the @@ -257,7 +255,7 @@ CopyDonePeek(FILE *fp, int c, int pickup) * NULL values as <null_print>. * * When loading in the text format from an input stream (as opposed to - * a file), recognize a "." on a line by itself as EOF. Also recognize + * a file), recognize a "." on a line by itself as EOF. Also recognize * a stream EOF. When unloading in the text format to an output stream, * write a "." on a line by itself at the end of the data. * @@ -534,7 +532,6 @@ CopyTo(Relation rel, bool binary, bool oids, FILE *fp, } else { - /* * If we have a toasted datum, forcibly detoast it to * avoid memory leakage inside the type's output routine @@ -1197,7 +1194,6 @@ CopyAttributeOut(FILE *fp, char *server_string, char *delim) char *string_start; int mblen; int i; - #endif #ifdef MULTIBYTE diff --git a/src/backend/commands/creatinh.c b/src/backend/commands/creatinh.c index 1c17714eb4..0c1e7268d7 100644 --- a/src/backend/commands/creatinh.c +++ b/src/backend/commands/creatinh.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/Attic/creatinh.c,v 1.80 2001/08/16 20:38:53 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/Attic/creatinh.c,v 1.81 2001/10/25 05:49:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,7 +37,7 @@ static List *MergeAttributes(List *schema, List *supers, bool istemp, List **supOids, List **supconstr, bool *supHasOids); static bool change_varattnos_of_a_node(Node *node, const AttrNumber *newattno); static void StoreCatalogInheritance(Oid relationId, List *supers); -static int findAttrByName(const char *attributeName, List *schema); +static int findAttrByName(const char *attributeName, List *schema); static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass); @@ -74,7 +74,7 @@ DefineRelation(CreateStmt *stmt, char relkind) * including inherited attributes. */ schema = MergeAttributes(schema, stmt->inhRelnames, stmt->istemp, - &inheritOids, &old_constraints, &parentHasOids); + &inheritOids, &old_constraints, &parentHasOids); numberOfAttributes = length(schema); if (numberOfAttributes <= 0) @@ -305,7 +305,8 @@ MergeAttributes(List *schema, List *supers, bool istemp, List *constraints = NIL; bool parentHasOids = false; bool have_bogus_defaults = false; - char *bogus_marker = "Bogus!"; /* marks conflicting defaults */ + char *bogus_marker = "Bogus!"; /* marks conflicting + * defaults */ int child_attno; /* @@ -329,6 +330,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, coldef->colname); } } + /* * Reject duplicate names in the list of parents, too. */ @@ -346,7 +348,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, /* * Scan the parents left-to-right, and merge their attributes to form - * a list of inherited attributes (inhSchema). Also check to see if + * a list of inherited attributes (inhSchema). Also check to see if * we need to inherit an OID column. */ child_attno = 0; @@ -387,7 +389,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, * the attributes of this parent table. (They are not the same * for parents after the first one.) */ - newattno = (AttrNumber *) palloc(tupleDesc->natts*sizeof(AttrNumber)); + newattno = (AttrNumber *) palloc(tupleDesc->natts * sizeof(AttrNumber)); for (parent_attno = 1; parent_attno <= tupleDesc->natts; parent_attno++) @@ -420,8 +422,8 @@ MergeAttributes(List *schema, List *supers, bool istemp, if (exist_attno > 0) { /* - * Yes, try to merge the two column definitions. - * They must have the same type and typmod. + * Yes, try to merge the two column definitions. They must + * have the same type and typmod. */ elog(NOTICE, "CREATE TABLE: merging multiple inherited definitions of attribute \"%s\"", attributeName); @@ -429,7 +431,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, if (strcmp(def->typename->name, attributeType) != 0 || def->typename->typmod != attribute->atttypmod) elog(ERROR, "CREATE TABLE: inherited attribute \"%s\" type conflict (%s and %s)", - attributeName, def->typename->name, attributeType); + attributeName, def->typename->name, attributeType); /* Merge of NOT NULL constraints = OR 'em together */ def->is_not_null |= attribute->attnotnull; /* Default and other constraints are handled below */ @@ -453,6 +455,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, inhSchema = lappend(inhSchema, def); newattno[parent_attno - 1] = ++child_attno; } + /* * Copy default if any */ @@ -474,15 +477,17 @@ MergeAttributes(List *schema, List *supers, bool istemp, } } 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. * - * If we already had a default from some prior parent, - * check to see if they are the same. If so, no problem; - * if not, mark the column as having a bogus default. - * Below, we will complain if the bogus default isn't - * overridden by the child schema. + * If we already had a default from some prior parent, check + * to see if they are the same. If so, no problem; if + * not, mark the column as having a bogus default. Below, + * we will complain if the bogus default isn't overridden + * by the child schema. */ Assert(def->raw_default == NULL); if (def->cooked_default == NULL) @@ -494,6 +499,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, } } } + /* * Now copy the constraints of this parent, adjusting attnos using * the completed newattno[] map @@ -555,8 +561,8 @@ MergeAttributes(List *schema, List *supers, bool istemp, ColumnDef *def; /* - * Yes, try to merge the two column definitions. - * They must have the same type and typmod. + * Yes, try to merge the two column definitions. They must + * have the same type and typmod. */ elog(NOTICE, "CREATE TABLE: merging attribute \"%s\" with inherited definition", attributeName); @@ -564,7 +570,7 @@ MergeAttributes(List *schema, List *supers, bool istemp, if (strcmp(def->typename->name, attributeType) != 0 || def->typename->typmod != newdef->typename->typmod) elog(ERROR, "CREATE TABLE: attribute \"%s\" type conflict (%s and %s)", - attributeName, def->typename->name, attributeType); + attributeName, def->typename->name, attributeType); /* Merge of NOT NULL constraints = OR 'em together */ def->is_not_null |= newdef->is_not_null; /* If new def has a default, override previous default */ @@ -630,7 +636,6 @@ change_varattnos_walker(Node *node, const AttrNumber *newattno) if (var->varlevelsup == 0 && var->varno == 1 && var->varattno > 0) { - /* * ??? the following may be a problem when the node is * multiply referenced though stringToNode() doesn't create @@ -783,7 +788,6 @@ again: } if (found) { - /* * found a later duplicate, so remove this entry. */ diff --git a/src/backend/commands/dbcommands.c b/src/backend/commands/dbcommands.c index 88b01fd91e..92baacb72d 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.80 2001/09/06 04:57:28 ishii Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/dbcommands.c,v 1.81 2001/10/25 05:49:24 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,7 +37,7 @@ #include "utils/syscache.h" #ifdef MULTIBYTE -#include "mb/pg_wchar.h" /* encoding check */ +#include "mb/pg_wchar.h" /* encoding check */ #endif @@ -148,11 +148,12 @@ createdb(const char *dbname, const char *dbpath, #ifdef MULTIBYTE /* Some encodings are client only */ - if (!PG_VALID_BE_ENCODING( encoding )) + if (!PG_VALID_BE_ENCODING(encoding)) elog(ERROR, "CREATE DATABASE: invalid backend encoding"); #else Assert(encoding == 0); /* zero is PG_SQL_ASCII */ #endif + /* * Preassign OID for pg_database tuple, so that we can compute db * path. diff --git a/src/backend/commands/define.c b/src/backend/commands/define.c index 02b7b0c04b..334094fd47 100644 --- a/src/backend/commands/define.c +++ b/src/backend/commands/define.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.62 2001/10/13 01:35:25 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.63 2001/10/25 05:49:25 momjian Exp $ * * DESCRIPTION * The "DefineFoo" routines take the parse tree and pick out the @@ -64,7 +64,7 @@ static void case_translate_language_name(const char *input, char *output) { /* - * Translate the input language name to lower case, except if it's "C", + * Translate the input language name to lower case, except if it's "C", * translate to upper case. */ int i; @@ -85,8 +85,8 @@ compute_return_type(TypeName *returnType, char **prorettype_p, bool *returnsSet_p) { /* - * Examine the "returns" clause returnType of the CREATE FUNCTION statement - * and return information about it as *prorettype_p and *returnsSet. + * Examine the "returns" clause returnType of the CREATE FUNCTION statement + * and return information about it as *prorettype_p and *returnsSet. */ *prorettype_p = TypeNameToInternalName(returnType); *returnsSet_p = returnType->setof; @@ -100,26 +100,26 @@ compute_full_attributes(List *parameters, bool *canCache_p, bool *isStrict_p) { /*------------- - * Interpret the parameters *parameters and return their contents as - * *byte_pct_p, etc. + * Interpret the parameters *parameters and return their contents as + * *byte_pct_p, etc. * - * These parameters supply optional information about a function. - * All have defaults if not specified. + * These parameters supply optional information about a function. + * All have defaults if not specified. * - * Note: currently, only two of these parameters actually do anything: + * Note: currently, only two of these parameters actually do anything: * - * * canCache means the optimizer's constant-folder is allowed to - * pre-evaluate the function when all its inputs are constants. + * * canCache means the optimizer's constant-folder is allowed to + * pre-evaluate the function when all its inputs are constants. * - * * isStrict means the function should not be called when any NULL - * inputs are present; instead a NULL result value should be assumed. + * * isStrict means the function should not be called when any NULL + * inputs are present; instead a NULL result value should be assumed. * - * The other four parameters are not used anywhere. They used to be - * used in the "expensive functions" optimizer, but that's been dead code - * for a long time. + * The other four parameters are not used anywhere. They used to be + * used in the "expensive functions" optimizer, but that's been dead code + * for a long time. * - * Since canCache and isStrict are useful for any function, we now allow - * attributes to be supplied for all functions regardless of language. + * Since canCache and isStrict are useful for any function, we now allow + * attributes to be supplied for all functions regardless of language. *------------ */ List *pl; @@ -142,7 +142,6 @@ compute_full_attributes(List *parameters, *isStrict_p = true; else if (strcasecmp(param->defname, "trusted") == 0) { - /* * we don't have untrusted functions any more. The 4.2 * implementation is lousy anyway so I took it out. -ay 10/94 @@ -183,7 +182,6 @@ interpret_AS_clause(const char *languageName, const List *as, if (strcmp(languageName, "C") == 0) { - /* * For "C" language, store the file name in probin and, when * given, the link symbol name in prosrc. @@ -358,7 +356,7 @@ DefineOperator(char *oprName, List *parameters) { uint16 precedence = 0; /* operator precedence */ - bool canHash = false;/* operator hashes */ + bool canHash = false; /* operator hashes */ bool isLeftAssociative = true; /* operator is left * associative */ char *functionName = NULL; /* function for operator */ @@ -369,7 +367,7 @@ DefineOperator(char *oprName, char *negatorName = NULL; /* optional negator operator name */ char *restrictionName = NULL; /* optional restrict. sel. * procedure */ - char *joinName = NULL;/* optional join sel. procedure name */ + char *joinName = NULL; /* optional join sel. procedure name */ char *sortName1 = NULL; /* optional first sort operator */ char *sortName2 = NULL; /* optional second sort operator */ List *pl; @@ -534,8 +532,8 @@ DefineAggregate(char *aggName, List *parameters) void DefineType(char *typeName, List *parameters) { - int16 internalLength = -1; /* int2 */ - int16 externalLength = -1; /* int2 */ + int16 internalLength = -1; /* int2 */ + int16 externalLength = -1; /* int2 */ char *elemName = NULL; char *inputName = NULL; char *outputName = NULL; @@ -546,7 +544,7 @@ DefineType(char *typeName, List *parameters) char delimiter = DEFAULT_TYPDELIM; char *shadow_type; List *pl; - char alignment = 'i'; /* default alignment */ + char alignment = 'i'; /* default alignment */ char storage = 'p'; /* default TOAST storage method */ /* @@ -591,9 +589,10 @@ DefineType(char *typeName, List *parameters) char *a = defGetString(defel); /* - * Note: if argument was an unquoted identifier, parser will have - * applied xlateSqlType() to it, so be prepared to recognize - * translated type names as well as the nominal form. + * Note: if argument was an unquoted identifier, parser will + * have applied xlateSqlType() to it, so be prepared to + * recognize translated type names as well as the nominal + * form. */ if (strcasecmp(a, "double") == 0) alignment = 'd'; diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c index 91282ffc3f..c14d4ce3e5 100644 --- a/src/backend/commands/explain.c +++ b/src/backend/commands/explain.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994-5, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.66 2001/09/18 01:59:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/explain.c,v 1.67 2001/10/25 05:49:25 momjian Exp $ * */ @@ -114,8 +114,8 @@ ExplainOneQuery(Query *query, bool verbose, bool analyze, CommandDest dest) struct timeval endtime; /* - * Set up the instrumentation for the top node. - * This will cascade during plan initialisation + * Set up the instrumentation for the top node. This will cascade + * during plan initialisation */ plan->instrument = InstrAlloc(); @@ -124,7 +124,7 @@ ExplainOneQuery(Query *query, bool verbose, bool analyze, CommandDest dest) CommandCounterIncrement(); gettimeofday(&endtime, NULL); - endtime.tv_sec -= starttime.tv_sec; + endtime.tv_sec -= starttime.tv_sec; endtime.tv_usec -= starttime.tv_usec; while (endtime.tv_usec < 0) { @@ -328,9 +328,9 @@ explain_outNode(StringInfo str, Plan *plan, int indent, ExplainState *es) plan->startup_cost, plan->total_cost, plan->plan_rows, plan->plan_width); - if ( plan->instrument && plan->instrument->nloops > 0 ) + if (plan->instrument && plan->instrument->nloops > 0) { - double nloops = plan->instrument->nloops; + double nloops = plan->instrument->nloops; appendStringInfo(str, " (actual time=%.2f..%.2f rows=%.0f loops=%.0f)", 1000.0 * plan->instrument->startup / nloops, @@ -442,7 +442,7 @@ explain_outNode(StringInfo str, Plan *plan, int indent, ExplainState *es) static StringInfo Explain_PlanToString(Plan *plan, ExplainState *es) { - StringInfo str = makeStringInfo(); + StringInfo str = makeStringInfo(); if (plan != NULL) explain_outNode(str, plan, 0, es); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index a02f399f12..f6eb6471c0 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.59 2001/10/24 09:28:31 inoue Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/indexcmds.c,v 1.60 2001/10/25 05:49:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -49,7 +49,7 @@ static void NormIndexAttrs(IndexInfo *indexInfo, Oid *classOidP, char *accessMethodName, Oid accessMethodId); static Oid GetAttrOpClass(IndexElem *attribute, Oid attrType, char *accessMethodName, Oid accessMethodId); -static Oid GetDefaultOpClass(Oid attrType, Oid accessMethodId); +static Oid GetDefaultOpClass(Oid attrType, Oid accessMethodId); /* * DefineIndex @@ -97,7 +97,8 @@ DefineIndex(char *heapRelationName, heapRelationName); /* - * look up the access method, verify it can handle the requested features + * look up the access method, verify it can handle the requested + * features */ tuple = SearchSysCache(AMNAME, PointerGetDatum(accessMethodName), @@ -108,18 +109,18 @@ DefineIndex(char *heapRelationName, accessMethodId = tuple->t_data->t_oid; accessMethodForm = (Form_pg_am) GETSTRUCT(tuple); - if (unique && ! accessMethodForm->amcanunique) + if (unique && !accessMethodForm->amcanunique) elog(ERROR, "DefineIndex: access method \"%s\" does not support UNIQUE indexes", accessMethodName); - if (numberOfAttributes > 1 && ! accessMethodForm->amcanmulticol) + if (numberOfAttributes > 1 && !accessMethodForm->amcanmulticol) elog(ERROR, "DefineIndex: access method \"%s\" does not support multi-column indexes", accessMethodName); ReleaseSysCache(tuple); /* - * Convert the partial-index predicate from parsetree form to - * an implicit-AND qual expression, for easier evaluation at runtime. + * Convert the partial-index predicate from parsetree form to an + * implicit-AND qual expression, for easier evaluation at runtime. * While we are at it, we reduce it to a canonical (CNF or DNF) form * to simplify the task of proving implications. */ @@ -196,7 +197,7 @@ DefineIndex(char *heapRelationName, * (via the given range table) only to the given base relation oid. * * This used to also constrain the form of the predicate to forms that - * indxpath.c could do something with. However, that seems overly + * indxpath.c could do something with. However, that seems overly * restrictive. One useful application of partial indexes is to apply * a UNIQUE constraint across a subset of a table, and in that scenario * any evaluatable predicate will work. So accept any predicate here @@ -208,11 +209,12 @@ CheckPredicate(List *predList, List *rangeTable, Oid baseRelOid) { if (length(rangeTable) != 1 || getrelid(1, rangeTable) != baseRelOid) elog(ERROR, - "Partial-index predicates may refer only to the base relation"); + "Partial-index predicates may refer only to the base relation"); /* * We don't currently support generation of an actual query plan for a - * predicate, only simple scalar expressions; hence these restrictions. + * predicate, only simple scalar expressions; hence these + * restrictions. */ if (contain_subplans((Node *) predList)) elog(ERROR, "Cannot use subselect in index predicate"); @@ -240,7 +242,7 @@ FuncIndexArgs(IndexInfo *indexInfo, List *arglist; int nargs = 0; int i; - FuncDetailCode fdresult; + FuncDetailCode fdresult; Oid funcid; Oid rettype; bool retset; @@ -309,9 +311,9 @@ FuncIndexArgs(IndexInfo *indexInfo, /* * Require that the function be marked cachable. Using a noncachable - * function for a functional index is highly questionable, 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. + * function for a functional index is highly questionable, 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 (!func_iscachable(funcid)) elog(ERROR, "DefineIndex: index function must be marked iscachable"); @@ -431,11 +433,11 @@ GetDefaultOpClass(Oid attrType, Oid accessMethodId) * (either exactly or binary-compatibly, but prefer an exact match). * * We could find more than one binary-compatible match, in which case we - * require the user to specify which one he wants. If we find more than - * one exact match, then someone put bogus entries in pg_opclass. + * require the user to specify which one he wants. If we find more + * than one exact match, then someone put bogus entries in pg_opclass. * - * We could use an indexscan here, but since pg_opclass is small - * and a scan on opcamid won't be very selective, the indexscan would + * We could use an indexscan here, but since pg_opclass is small and a + * scan on opcamid won't be very selective, the indexscan would * probably actually be slower than heapscan. */ ScanKeyEntryInitialize(&entry[0], 0x0, @@ -612,7 +614,7 @@ ReindexDatabase(const char *dbname, bool force, bool all) if (strcmp(dbname, DatabaseName) != 0) elog(ERROR, "REINDEX DATABASE: Can be executed only on the currently open database."); - if (! (superuser() || is_dbadmin(MyDatabaseId))) + if (!(superuser() || is_dbadmin(MyDatabaseId))) elog(ERROR, "REINDEX DATABASE: Permission denied."); /* diff --git a/src/backend/commands/remove.c b/src/backend/commands/remove.c index 4e46f7f9d2..37a338ff96 100644 --- a/src/backend/commands/remove.c +++ b/src/backend/commands/remove.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/Attic/remove.c,v 1.63 2001/10/03 20:54:20 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/Attic/remove.c,v 1.64 2001/10/25 05:49:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -227,7 +227,6 @@ AttributeAndRelationRemove(Oid typeOid) } heap_close(rel, RowExclusiveLock); } - #endif /* NOTYET */ /* diff --git a/src/backend/commands/rename.c b/src/backend/commands/rename.c index 8d4b05567f..c65cfcc551 100644 --- a/src/backend/commands/rename.c +++ b/src/backend/commands/rename.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/Attic/rename.c,v 1.58 2001/10/08 18:40:04 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/Attic/rename.c,v 1.59 2001/10/25 05:49:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -167,7 +167,8 @@ renameatt(char *relname, heap_freetuple(atttup); /* - * Update column names of indexes that refer to the column being renamed. + * Update column names of indexes that refer to the column being + * renamed. */ indexoidlist = RelationGetIndexList(targetrelation); @@ -177,9 +178,8 @@ renameatt(char *relname, HeapTuple indextup; /* - * First check to see if index is a functional index. - * If so, its column name is a function name and shouldn't - * be renamed here. + * First check to see if index is a functional index. If so, its + * column name is a function name and shouldn't be renamed here. */ indextup = SearchSysCache(INDEXRELID, ObjectIdGetDatum(indexoid), @@ -192,9 +192,10 @@ renameatt(char *relname, continue; } ReleaseSysCache(indextup); + /* - * Okay, look to see if any column name of the index matches - * the old attribute name. + * Okay, look to see if any column name of the index matches the + * old attribute name. */ atttup = SearchSysCacheCopy(ATTNAME, ObjectIdGetDatum(indexoid), @@ -206,20 +207,20 @@ renameatt(char *relname, /* * Update the (copied) attribute tuple. */ - StrNCpy(NameStr(((Form_pg_attribute) GETSTRUCT(atttup))->attname), - newattname, NAMEDATALEN); + StrNCpy(NameStr(((Form_pg_attribute) GETSTRUCT(atttup))->attname), + newattname, NAMEDATALEN); - simple_heap_update(attrelation, &atttup->t_self, atttup); + simple_heap_update(attrelation, &atttup->t_self, atttup); /* keep system catalog indices current */ - { - Relation irelations[Num_pg_attr_indices]; - - CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations); - CatalogIndexInsert(irelations, Num_pg_attr_indices, attrelation, atttup); - CatalogCloseIndices(Num_pg_attr_indices, irelations); - } - heap_freetuple(atttup); + { + Relation irelations[Num_pg_attr_indices]; + + CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations); + CatalogIndexInsert(irelations, Num_pg_attr_indices, attrelation, atttup); + CatalogCloseIndices(Num_pg_attr_indices, irelations); + } + heap_freetuple(atttup); } freeList(indexoidlist); @@ -332,8 +333,8 @@ renamerel(const char *oldrelname, const char *newrelname) */ if (relkind == RELKIND_VIEW) { - char *oldrulename, - *newrulename; + char *oldrulename, + *newrulename; oldrulename = MakeRetrieveViewRuleName(oldrelname); newrulename = MakeRetrieveViewRuleName(newrelname); diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c index 80e17caaa8..10954912e7 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.64 2001/09/19 09:48:42 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.65 2001/10/25 05:49:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -36,9 +36,9 @@ #else #define SEQ_MAXVALUE ((int64) 0x7FFFFFFFFFFFFFFF) #endif -#else /* INT64_IS_BUSTED */ +#else /* INT64_IS_BUSTED */ #define SEQ_MAXVALUE ((int64) 0x7FFFFFFF) -#endif /* INT64_IS_BUSTED */ +#endif /* INT64_IS_BUSTED */ #define SEQ_MINVALUE (-SEQ_MAXVALUE) @@ -204,17 +204,17 @@ DefineSequence(CreateSeqStmt *seq) heap_insert(rel, tuple); /* - * After crash REDO of heap_insert above would re-init page and - * our magic number would be lost. We have to log sequence creation. - * This means two log records instead of one -:( + * After crash REDO of heap_insert above would re-init page and our + * magic number would be lost. We have to log sequence creation. This + * means two log records instead of one -:( */ LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE); START_CRIT_SECTION(); { - xl_seq_rec xlrec; - XLogRecPtr recptr; - XLogRecData rdata[2]; - Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple); + xl_seq_rec xlrec; + XLogRecPtr recptr; + XLogRecData rdata[2]; + Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple); /* We do not log first nextval call, so "advance" sequence here */ newseq->is_called = true; @@ -582,12 +582,12 @@ get_seq_name(text *seqin) if (strlen(seqname) >= NAMEDATALEN) { #ifdef MULTIBYTE - int len; + int len; - len = pg_mbcliplen(seqname, rawlen, NAMEDATALEN-1); + len = pg_mbcliplen(seqname, rawlen, NAMEDATALEN - 1); seqname[len] = '\0'; #else - seqname[NAMEDATALEN-1] = '\0'; + seqname[NAMEDATALEN - 1] = '\0'; #endif } @@ -658,7 +658,6 @@ init_sequence(char *caller, char *name) if (elm != (SeqTable) NULL) { - /* * We are using a seqtable entry left over from a previous xact; * must check for relid change. @@ -674,7 +673,6 @@ init_sequence(char *caller, char *name) } else { - /* * Time to make a new seqtable entry. These entries live as long * as the backend does, so we use plain malloc for them. @@ -713,7 +711,7 @@ CloseSequences(void) for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next) { rel = elm->rel; - if (rel != (Relation) NULL) /* opened in current xact */ + if (rel != (Relation) NULL) /* opened in current xact */ { elm->rel = (Relation) NULL; heap_close(rel, AccessShareLock); @@ -737,17 +735,17 @@ init_params(CreateSeqStmt *seq, Form_pg_sequence new) { DefElem *defel = (DefElem *) lfirst(option); - if (strcmp(defel->defname, "increment")==0) + if (strcmp(defel->defname, "increment") == 0) increment_by = defel; - else if (strcmp(defel->defname, "start")==0) + else if (strcmp(defel->defname, "start") == 0) last_value = defel; - else if (strcmp(defel->defname, "maxvalue")==0) + else if (strcmp(defel->defname, "maxvalue") == 0) max_value = defel; - else if (strcmp(defel->defname, "minvalue")==0) + else if (strcmp(defel->defname, "minvalue") == 0) min_value = defel; - else if (strcmp(defel->defname, "cache")==0) + else if (strcmp(defel->defname, "cache") == 0) cache_value = defel; - else if (strcmp(defel->defname, "cycle")==0) + else if (strcmp(defel->defname, "cycle") == 0) { if (defel->arg != (Node *) NULL) elog(ERROR, "DefineSequence: CYCLE ??"); @@ -768,7 +766,7 @@ init_params(CreateSeqStmt *seq, Form_pg_sequence new) if (new->increment_by > 0) new->max_value = SEQ_MAXVALUE; /* ascending seq */ else - new->max_value = -1; /* descending seq */ + new->max_value = -1; /* descending seq */ } else new->max_value = get_param(max_value); @@ -822,12 +820,12 @@ get_param(DefElem *def) return (int64) intVal(def->arg); /* - * Values too large for int4 will be represented as Float constants - * by the lexer. Accept these if they are valid int8 strings. + * Values too large for int4 will be represented as Float constants by + * the lexer. Accept these if they are valid int8 strings. */ if (IsA(def->arg, Float)) return DatumGetInt64(DirectFunctionCall1(int8in, - CStringGetDatum(strVal(def->arg)))); + CStringGetDatum(strVal(def->arg)))); /* Shouldn't get here unless parser messed up */ elog(ERROR, "DefineSequence: \"%s\" value must be integer", def->defname); diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c index de98b33346..e108840d78 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.96 2001/08/23 23:06:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/trigger.c,v 1.97 2001/10/25 05:49:25 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -34,17 +34,17 @@ static void InsertTrigger(TriggerDesc *trigdesc, Trigger *trigger, int indx); static HeapTuple GetTupleForTrigger(EState *estate, - ResultRelInfo *relinfo, - ItemPointer tid, - TupleTableSlot **newSlot); + ResultRelInfo *relinfo, + ItemPointer tid, + TupleTableSlot **newSlot); static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, - FmgrInfo *finfo, - MemoryContext per_tuple_context); + FmgrInfo *finfo, + MemoryContext per_tuple_context); static void DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, - HeapTuple oldtup, HeapTuple newtup); + HeapTuple oldtup, HeapTuple newtup); static void DeferredTriggerExecute(DeferredTriggerEvent event, int itemno, - Relation rel, FmgrInfo *finfo, - MemoryContext per_tuple_context); + Relation rel, FmgrInfo *finfo, + MemoryContext per_tuple_context); void @@ -93,7 +93,6 @@ CreateTrigger(CreateTrigStmt *stmt) constrrelid = InvalidOid; else { - /* * NoLock is probably sufficient here, since we're only * interested in getting the relation's OID... @@ -849,8 +848,8 @@ ExecCallTriggerFunc(TriggerData *trigdata, MemoryContext oldContext; /* - * We cache fmgr lookup info, to avoid making the lookup - * again on each call. + * We cache fmgr lookup info, to avoid making the lookup again on each + * call. */ if (finfo->fn_oid == InvalidOid) fmgr_info(trigdata->tg_trigger->tgfoid, finfo); @@ -915,14 +914,14 @@ ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, LocTriggerData.tg_newtuple = NULL; for (i = 0; i < ntrigs; i++) { - Trigger *trigger = &trigdesc->triggers[tgindx[i]]; + Trigger *trigger = &trigdesc->triggers[tgindx[i]]; if (!trigger->tgenabled) continue; LocTriggerData.tg_trigtuple = oldtuple = newtuple; LocTriggerData.tg_trigger = trigger; newtuple = ExecCallTriggerFunc(&LocTriggerData, - relinfo->ri_TrigFunctions + tgindx[i], + relinfo->ri_TrigFunctions + tgindx[i], GetPerTupleMemoryContext(estate)); if (oldtuple != newtuple && oldtuple != trigtuple) heap_freetuple(oldtuple); @@ -978,14 +977,14 @@ ExecBRDeleteTriggers(EState *estate, ResultRelInfo *relinfo, LocTriggerData.tg_newtuple = NULL; for (i = 0; i < ntrigs; i++) { - Trigger *trigger = &trigdesc->triggers[tgindx[i]]; + Trigger *trigger = &trigdesc->triggers[tgindx[i]]; if (!trigger->tgenabled) continue; LocTriggerData.tg_trigtuple = trigtuple; LocTriggerData.tg_trigger = trigger; newtuple = ExecCallTriggerFunc(&LocTriggerData, - relinfo->ri_TrigFunctions + tgindx[i], + relinfo->ri_TrigFunctions + tgindx[i], GetPerTupleMemoryContext(estate)); if (newtuple == NULL) break; @@ -1055,7 +1054,7 @@ ExecBRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, LocTriggerData.tg_relation = relinfo->ri_RelationDesc; for (i = 0; i < ntrigs; i++) { - Trigger *trigger = &trigdesc->triggers[tgindx[i]]; + Trigger *trigger = &trigdesc->triggers[tgindx[i]]; if (!trigger->tgenabled) continue; @@ -1063,7 +1062,7 @@ ExecBRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, LocTriggerData.tg_newtuple = oldtuple = newtuple; LocTriggerData.tg_trigger = trigger; newtuple = ExecCallTriggerFunc(&LocTriggerData, - relinfo->ri_TrigFunctions + tgindx[i], + relinfo->ri_TrigFunctions + tgindx[i], GetPerTupleMemoryContext(estate)); if (oldtuple != newtuple && oldtuple != intuple) heap_freetuple(oldtuple); @@ -1130,8 +1129,8 @@ ltrmark:; else if (!(ItemPointerEquals(&(tuple.t_self), tid))) { TupleTableSlot *epqslot = EvalPlanQual(estate, - relinfo->ri_RangeTableIndex, - &(tuple.t_self)); + relinfo->ri_RangeTableIndex, + &(tuple.t_self)); if (!(TupIsNull(epqslot))) { @@ -1293,7 +1292,6 @@ deferredTriggerCheckState(Oid tgoid, int32 itemstate) static void deferredTriggerAddEvent(DeferredTriggerEvent event) { - /* * Since the event list could grow quite long, we keep track of the * list tail and append there, rather than just doing a stupid @@ -1359,7 +1357,7 @@ deferredTriggerGetPreviousEvent(Oid relid, ItemPointer ctid) * single trigger function. * * Frequently, this will be fired many times in a row for triggers of - * a single relation. Therefore, we cache the open relation and provide + * a single relation. Therefore, we cache the open relation and provide * fmgr lookup cache space at the caller level. * * event: event currently being fired. @@ -1535,8 +1533,8 @@ deferredTriggerInvokeEvents(bool immediate_only) } /* - * So let's fire it... but first, open the correct relation - * if this is not the same relation as before. + * So let's fire it... but first, open the correct relation if + * this is not the same relation as before. */ if (rel == NULL || rel->rd_id != event->dte_relid) { @@ -1544,11 +1542,13 @@ deferredTriggerInvokeEvents(bool immediate_only) heap_close(rel, NoLock); if (finfo) pfree(finfo); + /* * We assume that an appropriate lock is still held by the * executor, so grab no new lock here. */ rel = heap_open(event->dte_relid, NoLock); + /* * Allocate space to cache fmgr lookup info for triggers * of this relation. @@ -1667,7 +1667,6 @@ DeferredTriggerBeginXact(void) void DeferredTriggerEndQuery(void) { - /* * Ignore call if we aren't in a transaction. */ @@ -1688,7 +1687,6 @@ DeferredTriggerEndQuery(void) void DeferredTriggerEndXact(void) { - /* * Ignore call if we aren't in a transaction. */ @@ -1713,7 +1711,6 @@ DeferredTriggerEndXact(void) void DeferredTriggerAbortXact(void) { - /* * Ignore call if we aren't in a transaction. */ @@ -1751,7 +1748,6 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt) { if (!IsTransactionBlock()) { - /* * ... outside of a transaction block * @@ -1779,7 +1775,6 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt) } else { - /* * ... inside of a transaction block * @@ -2050,7 +2045,7 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, new_event->dte_n_items = ntriggers; for (i = 0; i < ntriggers; i++) { - Trigger *trigger = &trigdesc->triggers[tgindx[i]]; + Trigger *trigger = &trigdesc->triggers[tgindx[i]]; new_event->dte_item[i].dti_tgoid = trigger->tgoid; new_event->dte_item[i].dti_state = @@ -2090,7 +2085,7 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, */ for (i = 0; i < ntriggers; i++) { - Trigger *trigger = &trigdesc->triggers[tgindx[i]]; + Trigger *trigger = &trigdesc->triggers[tgindx[i]]; bool is_ri_trigger; bool key_unchanged; @@ -2125,7 +2120,6 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, if (key_unchanged) { - /* * The key hasn't changed, so no need later to invoke * the trigger at all. But remember other states from @@ -2138,7 +2132,6 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, if (prev_event->dte_event & TRIGGER_DEFERRED_ROW_INSERTED) { - /* * This is a row inserted during our * transaction. So any key value is considered @@ -2153,7 +2146,6 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, } else { - /* * This is a row, previously updated. So if * this key has been changed before, we still @@ -2172,7 +2164,6 @@ DeferredTriggerSaveEvent(ResultRelInfo *relinfo, int event, } else { - /* * Bomb out if this key has been changed before. * Otherwise remember that we do so. diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index 518b9942d1..a3103e7209 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/commands/user.c,v 1.84 2001/09/19 09:48:42 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/user.c,v 1.85 2001/10/25 05:49:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -170,7 +170,7 @@ update_pg_pwd(PG_FUNCTION_ARGS) { /* * ExclusiveLock ensures no one modifies pg_shadow while we read it, - * and that only one backend rewrites the flat file at a time. It's + * and that only one backend rewrites the flat file at a time. It's * OK to allow normal reads of pg_shadow in parallel, however. */ Relation rel = heap_openr(ShadowRelationName, ExclusiveLock); @@ -199,15 +199,17 @@ CreateUser(CreateUserStmt *stmt) sysid_exists = false, havesysid = false; int max_id; - List *item, *option; - char *password = NULL; /* PostgreSQL user password */ - bool encrypt_password = Password_encryption; /* encrypt password? */ - char encrypted_password[MD5_PASSWD_LEN+1]; - int sysid = 0; /* PgSQL system id (valid if havesysid) */ - bool createdb = false; /* Can the user create databases? */ - bool createuser = false; /* Can this user create users? */ - List *groupElts = NIL; /* The groups the user is a member of */ - char *validUntil = NULL; /* The time the login is valid until */ + List *item, + *option; + char *password = NULL; /* PostgreSQL user password */ + bool encrypt_password = Password_encryption; /* encrypt password? */ + char encrypted_password[MD5_PASSWD_LEN + 1]; + int sysid = 0; /* PgSQL system id (valid if havesysid) */ + bool createdb = false; /* Can the user create databases? */ + bool createuser = false; /* Can this user create users? */ + List *groupElts = NIL; /* The groups the user is a member of */ + char *validUntil = NULL; /* The time the login is valid + * until */ DefElem *dpassword = NULL; DefElem *dsysid = NULL; DefElem *dcreatedb = NULL; @@ -218,11 +220,12 @@ CreateUser(CreateUserStmt *stmt) /* Extract options from the statement node tree */ foreach(option, stmt->options) { - DefElem *defel = (DefElem *) lfirst(option); + DefElem *defel = (DefElem *) lfirst(option); if (strcmp(defel->defname, "password") == 0 || strcmp(defel->defname, "encryptedPassword") == 0 || - strcmp(defel->defname, "unencryptedPassword") == 0) { + strcmp(defel->defname, "unencryptedPassword") == 0) + { if (dpassword) elog(ERROR, "CREATE USER: conflicting options"); dpassword = defel; @@ -231,33 +234,38 @@ CreateUser(CreateUserStmt *stmt) else if (strcmp(defel->defname, "unencryptedPassword") == 0) encrypt_password = false; } - else if (strcmp(defel->defname, "sysid") == 0) { + else if (strcmp(defel->defname, "sysid") == 0) + { if (dsysid) elog(ERROR, "CREATE USER: conflicting options"); dsysid = defel; } - else if (strcmp(defel->defname, "createdb") == 0) { + else if (strcmp(defel->defname, "createdb") == 0) + { if (dcreatedb) elog(ERROR, "CREATE USER: conflicting options"); dcreatedb = defel; } - else if (strcmp(defel->defname, "createuser") == 0) { + else if (strcmp(defel->defname, "createuser") == 0) + { if (dcreateuser) elog(ERROR, "CREATE USER: conflicting options"); dcreateuser = defel; } - else if (strcmp(defel->defname, "groupElts") == 0) { + else if (strcmp(defel->defname, "groupElts") == 0) + { if (dgroupElts) elog(ERROR, "CREATE USER: conflicting options"); dgroupElts = defel; } - else if (strcmp(defel->defname, "validUntil") == 0) { + else if (strcmp(defel->defname, "validUntil") == 0) + { if (dvalidUntil) elog(ERROR, "CREATE USER: conflicting options"); dvalidUntil = defel; } else - elog(ERROR,"CREATE USER: option \"%s\" not recognized", + elog(ERROR, "CREATE USER: option \"%s\" not recognized", defel->defname); } @@ -329,7 +337,7 @@ CreateUser(CreateUserStmt *stmt) elog(ERROR, "CREATE USER: sysid %d is already assigned", sysid); /* If no sysid given, use max existing id + 1 */ - if (! havesysid) + if (!havesysid) sysid = max_id + 1; /* @@ -355,7 +363,7 @@ CreateUser(CreateUserStmt *stmt) else { if (!EncryptMD5(password, stmt->user, strlen(stmt->user), - encrypted_password)) + encrypted_password)) elog(ERROR, "CREATE USER: password encryption failed"); new_record[Anum_pg_shadow_passwd - 1] = DirectFunctionCall1(textin, CStringGetDatum(encrypted_password)); @@ -438,26 +446,28 @@ AlterUser(AlterUserStmt *stmt) HeapTuple tuple, new_tuple; bool null; - List *option; - char *password = NULL; /* PostgreSQL user password */ - bool encrypt_password = Password_encryption; /* encrypt password? */ - char encrypted_password[MD5_PASSWD_LEN+1]; - int createdb = -1; /* Can the user create databases? */ - int createuser = -1; /* Can this user create users? */ - char *validUntil = NULL; /* The time the login is valid until */ + List *option; + char *password = NULL; /* PostgreSQL user password */ + bool encrypt_password = Password_encryption; /* encrypt password? */ + char encrypted_password[MD5_PASSWD_LEN + 1]; + int createdb = -1; /* Can the user create databases? */ + int createuser = -1; /* Can this user create users? */ + char *validUntil = NULL; /* The time the login is valid + * until */ DefElem *dpassword = NULL; DefElem *dcreatedb = NULL; DefElem *dcreateuser = NULL; DefElem *dvalidUntil = NULL; /* Extract options from the statement node tree */ - foreach(option,stmt->options) + foreach(option, stmt->options) { - DefElem *defel = (DefElem *) lfirst(option); + DefElem *defel = (DefElem *) lfirst(option); if (strcmp(defel->defname, "password") == 0 || strcmp(defel->defname, "encryptedPassword") == 0 || - strcmp(defel->defname, "unencryptedPassword") == 0) { + strcmp(defel->defname, "unencryptedPassword") == 0) + { if (dpassword) elog(ERROR, "ALTER USER: conflicting options"); dpassword = defel; @@ -466,23 +476,26 @@ AlterUser(AlterUserStmt *stmt) else if (strcmp(defel->defname, "unencryptedPassword") == 0) encrypt_password = false; } - else if (strcmp(defel->defname, "createdb") == 0) { + else if (strcmp(defel->defname, "createdb") == 0) + { if (dcreatedb) elog(ERROR, "ALTER USER: conflicting options"); dcreatedb = defel; } - else if (strcmp(defel->defname, "createuser") == 0) { + else if (strcmp(defel->defname, "createuser") == 0) + { if (dcreateuser) elog(ERROR, "ALTER USER: conflicting options"); dcreateuser = defel; } - else if (strcmp(defel->defname, "validUntil") == 0) { + else if (strcmp(defel->defname, "validUntil") == 0) + { if (dvalidUntil) elog(ERROR, "ALTER USER: conflicting options"); dvalidUntil = defel; } else - elog(ERROR,"ALTER USER: option \"%s\" not recognized", + elog(ERROR, "ALTER USER: option \"%s\" not recognized", defel->defname); } @@ -556,10 +569,10 @@ AlterUser(AlterUserStmt *stmt) /* * createuser (superuser) and catupd * - * XXX It's rather unclear how to handle catupd. It's probably - * best to keep it equal to the superuser status, otherwise you - * could end up with a situation where no existing superuser can - * alter the catalogs, including pg_shadow! + * XXX It's rather unclear how to handle catupd. It's probably best to + * keep it equal to the superuser status, otherwise you could end up + * with a situation where no existing superuser can alter the + * catalogs, including pg_shadow! */ if (createuser < 0) { @@ -588,7 +601,7 @@ AlterUser(AlterUserStmt *stmt) else { if (!EncryptMD5(password, stmt->user, strlen(stmt->user), - encrypted_password)) + encrypted_password)) elog(ERROR, "CREATE USER: password encryption failed"); new_record[Anum_pg_shadow_passwd - 1] = DirectFunctionCall1(textin, CStringGetDatum(encrypted_password)); @@ -719,7 +732,7 @@ DropUser(DropUserStmt *stmt) if (HeapTupleIsValid(tmp_tuple = heap_getnext(scan, 0))) { - char *dbname; + char *dbname; datum = heap_getattr(tmp_tuple, Anum_pg_database_datname, pg_dsc, &null); @@ -847,20 +860,22 @@ CreateGroup(CreateGroupStmt *stmt) foreach(option, stmt->options) { - DefElem *defel = (DefElem *) lfirst(option); + DefElem *defel = (DefElem *) lfirst(option); - if (strcmp(defel->defname, "sysid") == 0) { + if (strcmp(defel->defname, "sysid") == 0) + { if (dsysid) elog(ERROR, "CREATE GROUP: conflicting options"); dsysid = defel; } - else if (strcmp(defel->defname, "userElts") == 0) { + else if (strcmp(defel->defname, "userElts") == 0) + { if (duserElts) elog(ERROR, "CREATE GROUP: conflicting options"); duserElts = defel; } else - elog(ERROR,"CREATE GROUP: option \"%s\" not recognized", + elog(ERROR, "CREATE GROUP: option \"%s\" not recognized", defel->defname); } @@ -900,7 +915,7 @@ CreateGroup(CreateGroupStmt *stmt) datum = heap_getattr(tuple, Anum_pg_group_grosysid, pg_group_dsc, &null); Assert(!null); - if (havesysid) /* customized id wanted */ + if (havesysid) /* customized id wanted */ sysid_exists = (DatumGetInt32(datum) == sysid); else { @@ -939,7 +954,7 @@ CreateGroup(CreateGroupStmt *stmt) userarray = palloc(ARR_OVERHEAD(1) + length(newlist) * sizeof(int32)); userarray->size = ARR_OVERHEAD(1) + length(newlist) * sizeof(int32); userarray->flags = 0; - ARR_NDIM(userarray) = 1;/* one dimensional array */ + ARR_NDIM(userarray) = 1; /* one dimensional array */ ARR_LBOUND(userarray)[0] = 1; /* axis starts at one */ ARR_DIMS(userarray)[0] = length(newlist); /* axis is this long */ /* fill the array */ @@ -1088,6 +1103,7 @@ AlterGroup(AlterGroupStmt *stmt, const char *tag) if (!member(v, newlist)) newlist = lappend(newlist, v); else + /* * we silently assume here that this error will only come * up in a ALTER GROUP statement diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 991af5d5f3..fa5770b0e8 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -4,7 +4,7 @@ * The postgres vacuum cleaner. * * This file includes the "full" version of VACUUM, as well as control code - * used by all three of full VACUUM, lazy VACUUM, and ANALYZE. See + * used by all three of full VACUUM, lazy VACUUM, and ANALYZE. See * vacuumlazy.c and analyze.c for the rest of the code for the latter two. * * @@ -13,7 +13,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.209 2001/09/04 19:12:05 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.210 2001/10/25 05:49:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -68,11 +68,11 @@ typedef VacPageData *VacPage; typedef struct VacPageListData { - BlockNumber empty_end_pages; /* Number of "empty" end-pages */ - int num_pages; /* Number of pages in pagedesc */ + BlockNumber empty_end_pages; /* Number of "empty" end-pages */ + int num_pages; /* Number of pages in pagedesc */ int num_allocated_pages; /* Number of allocated pages in * pagedesc */ - VacPage *pagedesc; /* Descriptions of pages */ + VacPage *pagedesc; /* Descriptions of pages */ } VacPageListData; typedef VacPageListData *VacPageList; @@ -96,7 +96,7 @@ typedef VTupleMoveData *VTupleMove; typedef struct VRelStats { - BlockNumber rel_pages; + BlockNumber rel_pages; double rel_tuples; Size min_tlen; Size max_tlen; @@ -122,32 +122,32 @@ static void vacuum_init(VacuumStmt *vacstmt); static void vacuum_shutdown(VacuumStmt *vacstmt); static VRelList getrels(Name VacRelP, const char *stmttype); static void vac_update_dbstats(Oid dbid, - TransactionId vacuumXID, - TransactionId frozenXID); + TransactionId vacuumXID, + TransactionId frozenXID); static void vac_truncate_clog(TransactionId vacuumXID, - TransactionId frozenXID); + TransactionId frozenXID); static void vacuum_rel(Oid relid, VacuumStmt *vacstmt); static void full_vacuum_rel(Relation onerel, VacuumStmt *vacstmt); static void scan_heap(VRelStats *vacrelstats, Relation onerel, - VacPageList vacuum_pages, VacPageList fraged_pages); + VacPageList vacuum_pages, VacPageList fraged_pages); static void repair_frag(VRelStats *vacrelstats, Relation onerel, - VacPageList vacuum_pages, VacPageList fraged_pages, - int nindexes, Relation *Irel); + VacPageList vacuum_pages, VacPageList fraged_pages, + int nindexes, Relation *Irel); static void vacuum_heap(VRelStats *vacrelstats, Relation onerel, - VacPageList vacpagelist); + VacPageList vacpagelist); static void vacuum_page(Relation onerel, Buffer buffer, VacPage vacpage); static void vacuum_index(VacPageList vacpagelist, Relation indrel, - double num_tuples, int keep_tuples); + double num_tuples, int keep_tuples); static void scan_index(Relation indrel, double num_tuples); static bool tid_reaped(ItemPointer itemptr, void *state); static bool dummy_tid_reaped(ItemPointer itemptr, void *state); static void vac_update_fsm(Relation onerel, VacPageList fraged_pages, - BlockNumber rel_pages); + BlockNumber rel_pages); static VacPage copy_vac_page(VacPage vacpage); static void vpage_insert(VacPageList vacpagelist, VacPage vpnew); static void *vac_bsearch(const void *key, const void *base, - size_t nelem, size_t size, - int (*compar) (const void *, const void *)); + size_t nelem, size_t size, + int (*compar) (const void *, const void *)); static int vac_cmp_blk(const void *left, const void *right); static int vac_cmp_offno(const void *left, const void *right); static int vac_cmp_vtlinks(const void *left, const void *right); @@ -227,11 +227,11 @@ vacuum(VacuumStmt *vacstmt) vacuum_init(vacstmt); /* - * Process each selected relation. We are careful to process - * each relation in a separate transaction in order to avoid holding - * too many locks at one time. Also, if we are doing VACUUM ANALYZE, - * the ANALYZE part runs as a separate transaction from the VACUUM - * to further reduce locking. + * Process each selected relation. We are careful to process each + * relation in a separate transaction in order to avoid holding too + * many locks at one time. Also, if we are doing VACUUM ANALYZE, the + * ANALYZE part runs as a separate transaction from the VACUUM to + * further reduce locking. */ for (cur = vrl; cur != (VRelList) NULL; cur = cur->vrl_next) { @@ -271,21 +271,21 @@ vacuum_init(VacuumStmt *vacstmt) if (vacstmt->vacuum && vacstmt->vacrel == NULL) { /* - * Compute the initially applicable OldestXmin and FreezeLimit XIDs, - * so that we can record these values at the end of the VACUUM. - * Note that individual tables may well be processed with newer values, - * but we can guarantee that no (non-shared) relations are processed - * with older ones. + * Compute the initially applicable OldestXmin and FreezeLimit + * XIDs, so that we can record these values at the end of the + * VACUUM. Note that individual tables may well be processed with + * newer values, but we can guarantee that no (non-shared) + * relations are processed with older ones. * * It is okay to record non-shared values in pg_database, even though * we may vacuum shared relations with older cutoffs, because only * the minimum of the values present in pg_database matters. We - * can be sure that shared relations have at some time been vacuumed - * with cutoffs no worse than the global minimum; for, if there is - * a backend in some other DB with xmin = OLDXMIN that's determining - * the cutoff with which we vacuum shared relations, it is not possible - * for that database to have a cutoff newer than OLDXMIN recorded in - * pg_database. + * can be sure that shared relations have at some time been + * vacuumed with cutoffs no worse than the global minimum; for, if + * there is a backend in some other DB with xmin = OLDXMIN that's + * determining the cutoff with which we vacuum shared relations, + * it is not possible for that database to have a cutoff newer + * than OLDXMIN recorded in pg_database. */ vacuum_set_xid_limits(vacstmt, false, &initialOldestXmin, &initialFreezeLimit); @@ -316,11 +316,12 @@ vacuum_shutdown(VacuumStmt *vacstmt) } /* - * If we did a complete vacuum or analyze, then flush the init file that - * relcache.c uses to save startup time. The next backend startup will - * rebuild the init file with up-to-date information from pg_class. - * This lets the optimizer see the stats that we've collected for certain - * critical system indexes. See relcache.c for more details. + * If we did a complete vacuum or analyze, then flush the init file + * that relcache.c uses to save startup time. The next backend startup + * will rebuild the init file with up-to-date information from + * pg_class. This lets the optimizer see the stats that we've + * collected for certain critical system indexes. See relcache.c for + * more details. * * Ignore any failure to unlink the file, since it might not be there if * no backend has been started since the last vacuum. @@ -526,9 +527,10 @@ vac_update_relstats(Oid relid, BlockNumber num_pages, double num_tuples, pgcform->relpages = (int32) num_pages; pgcform->reltuples = num_tuples; pgcform->relhasindex = hasindex; + /* - * If we have discovered that there are no indexes, then there's - * no primary key either. This could be done more thoroughly... + * If we have discovered that there are no indexes, then there's no + * primary key either. This could be done more thoroughly... */ if (!hasindex) pgcform->relhaspkey = false; @@ -606,7 +608,7 @@ vac_update_dbstats(Oid dbid, * seems to be in danger of wrapping around. * * The passed XIDs are simply the ones I just wrote into my pg_database - * entry. They're used to initialize the "min" calculations. + * entry. They're used to initialize the "min" calculations. * * This routine is shared by full and lazy VACUUM. Note that it is only * applied after a database-wide VACUUM operation. @@ -708,26 +710,27 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt) /* * Determine the type of lock we want --- hard exclusive lock for a * FULL vacuum, but just ShareUpdateExclusiveLock for concurrent - * vacuum. Either way, we can be sure that no other backend is vacuuming - * the same table. + * vacuum. Either way, we can be sure that no other backend is + * vacuuming the same table. */ lmode = vacstmt->full ? AccessExclusiveLock : ShareUpdateExclusiveLock; /* - * Open the class, get an appropriate lock on it, and check permissions. + * Open the class, get an appropriate lock on it, and check + * permissions. * * We allow the user to vacuum a table if he is superuser, the table * owner, or the database owner (but in the latter case, only if it's - * not a shared relation). pg_ownercheck includes the superuser case. + * not a shared relation). pg_ownercheck includes the superuser case. * * Note we choose to treat permissions failure as a NOTICE and keep * trying to vacuum the rest of the DB --- is this appropriate? */ onerel = heap_open(relid, lmode); - if (! (pg_ownercheck(GetUserId(), RelationGetRelationName(onerel), - RELNAME) || - (is_dbadmin(MyDatabaseId) && !onerel->rd_rel->relisshared))) + if (!(pg_ownercheck(GetUserId(), RelationGetRelationName(onerel), + RELNAME) || + (is_dbadmin(MyDatabaseId) && !onerel->rd_rel->relisshared))) { elog(NOTICE, "Skipping \"%s\" --- only table or database owner can VACUUM it", RelationGetRelationName(onerel)); @@ -773,9 +776,9 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt) /* * If the relation has a secondary toast rel, vacuum that too while we * still hold the session lock on the master table. Note however that - * "analyze" will not get done on the toast table. This is good, - * because the toaster always uses hardcoded index access and statistics - * are totally unimportant for toast relations. + * "analyze" will not get done on the toast table. This is good, + * because the toaster always uses hardcoded index access and + * statistics are totally unimportant for toast relations. */ if (toast_relid != InvalidOid) vacuum_rel(toast_relid, vacstmt); @@ -846,6 +849,7 @@ full_vacuum_rel(Relation onerel, VacuumStmt *vacstmt) vacrelstats->hasindex = true; #ifdef NOT_USED + /* * reindex in VACUUM is dangerous under WAL. ifdef out until it * becomes safe. @@ -945,7 +949,7 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, char *relname; VacPage vacpage, vacpagecopy; - BlockNumber empty_pages, + BlockNumber empty_pages, new_pages, changed_pages, empty_end_pages; @@ -1057,12 +1061,13 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin)) { case HEAPTUPLE_DEAD: - tupgone = true; /* we can delete the tuple */ + tupgone = true; /* we can delete the tuple */ break; case HEAPTUPLE_LIVE: + /* - * Tuple is good. Consider whether to replace its xmin - * value with FrozenTransactionId. + * Tuple is good. Consider whether to replace its + * xmin value with FrozenTransactionId. */ if (TransactionIdIsNormal(tuple.t_data->t_xmin) && TransactionIdPrecedes(tuple.t_data->t_xmin, @@ -1075,11 +1080,13 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, } break; case HEAPTUPLE_RECENTLY_DEAD: + /* - * If tuple is recently deleted then we must not remove - * it from relation. + * If tuple is recently deleted then we must not + * remove it from relation. */ nkeep += 1; + /* * If we do shrinking and this tuple is updated one * then remember it to construct updated tuple @@ -1103,18 +1110,20 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, } break; case HEAPTUPLE_INSERT_IN_PROGRESS: + /* - * This should not happen, since we hold exclusive lock - * on the relation; shouldn't we raise an error? + * This should not happen, since we hold exclusive + * lock on the relation; shouldn't we raise an error? */ elog(NOTICE, "Rel %s: TID %u/%u: InsertTransactionInProgress %u - can't shrink relation", relname, blkno, offnum, tuple.t_data->t_xmin); do_shrinking = false; break; case HEAPTUPLE_DELETE_IN_PROGRESS: + /* - * This should not happen, since we hold exclusive lock - * on the relation; shouldn't we raise an error? + * This should not happen, since we hold exclusive + * lock on the relation; shouldn't we raise an error? */ elog(NOTICE, "Rel %s: TID %u/%u: DeleteTransactionInProgress %u - can't shrink relation", relname, blkno, offnum, tuple.t_data->t_xmax); @@ -1174,7 +1183,7 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, if (tuple.t_len > max_tlen) max_tlen = tuple.t_len; } - } /* scan along page */ + } /* scan along page */ if (tempPage != (Page) NULL) { @@ -1193,13 +1202,14 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, } free_size += vacpage->free; + /* * Add the page to fraged_pages if it has a useful amount of free - * space. "Useful" means enough for a minimal-sized tuple. - * But we don't know that accurately near the start of the relation, - * so add pages unconditionally if they have >= BLCKSZ/10 free space. + * space. "Useful" means enough for a minimal-sized tuple. But we + * don't know that accurately near the start of the relation, so + * add pages unconditionally if they have >= BLCKSZ/10 free space. */ - do_frag = (vacpage->free >= min_tlen || vacpage->free >= BLCKSZ/10); + do_frag = (vacpage->free >= min_tlen || vacpage->free >= BLCKSZ / 10); if (do_reap || do_frag) { @@ -1238,9 +1248,9 @@ scan_heap(VRelStats *vacrelstats, Relation onerel, fraged_pages->empty_end_pages = empty_end_pages; /* - * Clear the fraged_pages list if we found we couldn't shrink. - * Else, remove any "empty" end-pages from the list, and compute - * usable free space = free space in remaining pages. + * Clear the fraged_pages list if we found we couldn't shrink. Else, + * remove any "empty" end-pages from the list, and compute usable free + * space = free space in remaining pages. */ if (do_shrinking) { @@ -1303,9 +1313,9 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, CommandId myCID; Buffer buf, cur_buffer; - BlockNumber nblocks, + BlockNumber nblocks, blkno; - BlockNumber last_move_dest_block = 0, + BlockNumber last_move_dest_block = 0, last_vacuum_block; Page page, ToPage = NULL; @@ -1355,7 +1365,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, resultRelInfo = makeNode(ResultRelInfo); resultRelInfo->ri_RangeTableIndex = 1; /* dummy */ resultRelInfo->ri_RelationDesc = onerel; - resultRelInfo->ri_TrigDesc = NULL; /* we don't fire triggers */ + resultRelInfo->ri_TrigDesc = NULL; /* we don't fire triggers */ ExecOpenIndices(resultRelInfo); @@ -1393,9 +1403,9 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, /* * Scan pages backwards from the last nonempty page, trying to move * tuples down to lower pages. Quit when we reach a page that we have - * moved any tuples onto, or the first page if we haven't moved anything, - * or when we find a page we cannot completely empty (this last condition - * is handled by "break" statements within the loop). + * moved any tuples onto, or the first page if we haven't moved + * anything, or when we find a page we cannot completely empty (this + * last condition is handled by "break" statements within the loop). * * NB: this code depends on the vacuum_pages and fraged_pages lists being * in order by blkno. @@ -1406,19 +1416,20 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, blkno--) { /* - * Forget fraged_pages pages at or after this one; they're no longer - * useful as move targets, since we only want to move down. Note - * that since we stop the outer loop at last_move_dest_block, pages - * removed here cannot have had anything moved onto them already. + * Forget fraged_pages pages at or after this one; they're no + * longer useful as move targets, since we only want to move down. + * Note that since we stop the outer loop at last_move_dest_block, + * pages removed here cannot have had anything moved onto them + * already. * - * Also note that we don't change the stored fraged_pages list, - * only our local variable num_fraged_pages; so the forgotten pages - * are still available to be loaded into the free space map later. + * Also note that we don't change the stored fraged_pages list, only + * our local variable num_fraged_pages; so the forgotten pages are + * still available to be loaded into the free space map later. */ while (num_fraged_pages > 0 && - fraged_pages->pagedesc[num_fraged_pages-1]->blkno >= blkno) + fraged_pages->pagedesc[num_fraged_pages - 1]->blkno >= blkno) { - Assert(fraged_pages->pagedesc[num_fraged_pages-1]->offsets_used == 0); + Assert(fraged_pages->pagedesc[num_fraged_pages - 1]->offsets_used == 0); --num_fraged_pages; } @@ -1534,7 +1545,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, * tuples to another places. */ if ((tuple.t_data->t_infomask & HEAP_UPDATED && - !TransactionIdPrecedes(tuple.t_data->t_xmin, OldestXmin)) || + !TransactionIdPrecedes(tuple.t_data->t_xmin, OldestXmin)) || (!(tuple.t_data->t_infomask & HEAP_XMAX_INVALID) && !(ItemPointerEquals(&(tuple.t_self), &(tuple.t_data->t_ctid))))) @@ -1581,7 +1592,6 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, ItemPointerGetOffsetNumber(&Ctid)); if (!ItemIdIsUsed(Citemid)) { - /* * This means that in the middle of chain there * was tuple updated by older (than OldestXmin) @@ -1652,7 +1662,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, /* All done ? */ if (!(tp.t_data->t_infomask & HEAP_UPDATED) || - TransactionIdPrecedes(tp.t_data->t_xmin, OldestXmin)) + TransactionIdPrecedes(tp.t_data->t_xmin, OldestXmin)) break; /* Well, try to find tuple with old row version */ @@ -2109,9 +2119,9 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, /* * We are not going to move any more tuples across pages, but we still * need to apply vacuum_page to compact free space in the remaining - * pages in vacuum_pages list. Note that some of these pages may also - * be in the fraged_pages list, and may have had tuples moved onto them; - * if so, we already did vacuum_page and needn't do it again. + * pages in vacuum_pages list. Note that some of these pages may also + * be in the fraged_pages list, and may have had tuples moved onto + * them; if so, we already did vacuum_page and needn't do it again. */ for (i = 0, curpage = vacuum_pages->pagedesc; i < vacuumed_pages; @@ -2132,15 +2142,15 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, } /* - * Now scan all the pages that we moved tuples onto and update - * tuple status bits. This is not really necessary, but will save time - * for future transactions examining these tuples. + * Now scan all the pages that we moved tuples onto and update tuple + * status bits. This is not really necessary, but will save time for + * future transactions examining these tuples. * * XXX Notice that this code fails to clear HEAP_MOVED_OFF tuples from - * pages that were move source pages but not move dest pages. One also - * wonders whether it wouldn't be better to skip this step and let the - * tuple status updates happen someplace that's not holding an exclusive - * lock on the relation. + * pages that were move source pages but not move dest pages. One + * also wonders whether it wouldn't be better to skip this step and + * let the tuple status updates happen someplace that's not holding an + * exclusive lock on the relation. */ checked_moved = 0; for (i = 0, curpage = fraged_pages->pagedesc; @@ -2226,7 +2236,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, if (vacpage->blkno == (blkno - 1) && vacpage->offsets_free > 0) { - OffsetNumber unbuf[BLCKSZ/sizeof(OffsetNumber)]; + OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)]; OffsetNumber *unused = unbuf; int uncnt; @@ -2297,7 +2307,7 @@ repair_frag(VRelStats *vacrelstats, Relation onerel, if (blkno < nblocks) { blkno = smgrtruncate(DEFAULT_SMGR, onerel, blkno); - onerel->rd_nblocks = blkno; /* update relcache immediately */ + onerel->rd_nblocks = blkno; /* update relcache immediately */ onerel->rd_targblock = InvalidBlockNumber; vacrelstats->rel_pages = blkno; /* set new number of blocks */ } @@ -2323,7 +2333,7 @@ vacuum_heap(VRelStats *vacrelstats, Relation onerel, VacPageList vacuum_pages) { Buffer buf; VacPage *vacpage; - BlockNumber relblocks; + BlockNumber relblocks; int nblocks; int i; @@ -2363,7 +2373,7 @@ vacuum_heap(VRelStats *vacrelstats, Relation onerel, VacPageList vacuum_pages) RelationGetRelationName(onerel), vacrelstats->rel_pages, relblocks); relblocks = smgrtruncate(DEFAULT_SMGR, onerel, relblocks); - onerel->rd_nblocks = relblocks; /* update relcache immediately */ + onerel->rd_nblocks = relblocks; /* update relcache immediately */ onerel->rd_targblock = InvalidBlockNumber; vacrelstats->rel_pages = relblocks; /* set new number of * blocks */ @@ -2377,7 +2387,7 @@ vacuum_heap(VRelStats *vacrelstats, Relation onerel, VacPageList vacuum_pages) static void vacuum_page(Relation onerel, Buffer buffer, VacPage vacpage) { - OffsetNumber unbuf[BLCKSZ/sizeof(OffsetNumber)]; + OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)]; OffsetNumber *unused = unbuf; int uncnt; Page page = BufferGetPage(buffer); @@ -2420,8 +2430,8 @@ scan_index(Relation indrel, double num_tuples) /* * Even though we're not planning to delete anything, use the - * ambulkdelete call, so that the scan happens within the index AM - * for more speed. + * ambulkdelete call, so that the scan happens within the index AM for + * more speed. */ stats = index_bulk_delete(indrel, dummy_tid_reaped, NULL); @@ -2439,13 +2449,13 @@ scan_index(Relation indrel, double num_tuples) vac_show_rusage(&ru0)); /* - * Check for tuple count mismatch. If the index is partial, then - * it's OK for it to have fewer tuples than the heap; else we got trouble. + * Check for tuple count mismatch. If the index is partial, then it's + * OK for it to have fewer tuples than the heap; else we got trouble. */ if (stats->num_index_tuples != num_tuples) { if (stats->num_index_tuples > num_tuples || - ! vac_is_partial_index(indrel)) + !vac_is_partial_index(indrel)) elog(NOTICE, "Index %s: NUMBER OF INDEX' TUPLES (%.0f) IS NOT THE SAME AS HEAP' (%.0f).\ \n\tRecreate the index.", RelationGetRelationName(indrel), @@ -2493,13 +2503,13 @@ vacuum_index(VacPageList vacpagelist, Relation indrel, vac_show_rusage(&ru0)); /* - * Check for tuple count mismatch. If the index is partial, then - * it's OK for it to have fewer tuples than the heap; else we got trouble. + * Check for tuple count mismatch. If the index is partial, then it's + * OK for it to have fewer tuples than the heap; else we got trouble. */ if (stats->num_index_tuples != num_tuples + keep_tuples) { if (stats->num_index_tuples > num_tuples + keep_tuples || - ! vac_is_partial_index(indrel)) + !vac_is_partial_index(indrel)) elog(NOTICE, "Index %s: NUMBER OF INDEX' TUPLES (%.0f) IS NOT THE SAME AS HEAP' (%.0f).\ \n\tRecreate the index.", RelationGetRelationName(indrel), @@ -2519,7 +2529,7 @@ vacuum_index(VacPageList vacpagelist, Relation indrel, static bool tid_reaped(ItemPointer itemptr, void *state) { - VacPageList vacpagelist = (VacPageList) state; + VacPageList vacpagelist = (VacPageList) state; OffsetNumber ioffno; OffsetNumber *voff; VacPage vp, @@ -2591,9 +2601,11 @@ vac_update_fsm(Relation onerel, VacPageList fraged_pages, { pages[i] = fraged_pages->pagedesc[i]->blkno; spaceAvail[i] = fraged_pages->pagedesc[i]->free; + /* - * fraged_pages may contain entries for pages that we later decided - * to truncate from the relation; don't enter them into the map! + * fraged_pages may contain entries for pages that we later + * decided to truncate from the relation; don't enter them into + * the map! */ if (pages[i] >= rel_pages) { @@ -2617,7 +2629,7 @@ copy_vac_page(VacPage vacpage) /* allocate a VacPageData entry */ newvacpage = (VacPage) palloc(sizeof(VacPageData) + - vacpage->offsets_free * sizeof(OffsetNumber)); + vacpage->offsets_free * sizeof(OffsetNumber)); /* fill it in */ if (vacpage->offsets_free > 0) @@ -2661,7 +2673,7 @@ vpage_insert(VacPageList vacpagelist, VacPage vpnew) /* * vac_bsearch: just like standard C library routine bsearch(), * except that we first test to see whether the target key is outside - * the range of the table entries. This case is handled relatively slowly + * the range of the table entries. This case is handled relatively slowly * by the normal binary search algorithm (ie, no faster than any other key) * but it occurs often enough in VACUUM to be worth optimizing. */ @@ -2802,14 +2814,15 @@ vac_is_partial_index(Relation indrel) Form_pg_index indexStruct; /* - * If the index's AM doesn't support nulls, it's partial for our purposes + * If the index's AM doesn't support nulls, it's partial for our + * purposes */ - if (! indrel->rd_am->amindexnulls) + if (!indrel->rd_am->amindexnulls) return true; /* Otherwise, look to see if there's a partial-index predicate */ cachetuple = SearchSysCache(INDEXRELID, - ObjectIdGetDatum(RelationGetRelid(indrel)), + ObjectIdGetDatum(RelationGetRelid(indrel)), 0, 0, 0); if (!HeapTupleIsValid(cachetuple)) elog(ERROR, "vac_is_partial_index: index %u not found", @@ -2888,9 +2901,9 @@ vac_show_rusage(VacRUsage *ru0) snprintf(result, sizeof(result), "CPU %d.%02ds/%d.%02du sec elapsed %d.%02d sec.", (int) (ru1.ru.ru_stime.tv_sec - ru0->ru.ru_stime.tv_sec), - (int) (ru1.ru.ru_stime.tv_usec - ru0->ru.ru_stime.tv_usec) / 10000, + (int) (ru1.ru.ru_stime.tv_usec - ru0->ru.ru_stime.tv_usec) / 10000, (int) (ru1.ru.ru_utime.tv_sec - ru0->ru.ru_utime.tv_sec), - (int) (ru1.ru.ru_utime.tv_usec - ru0->ru.ru_utime.tv_usec) / 10000, + (int) (ru1.ru.ru_utime.tv_usec - ru0->ru.ru_utime.tv_usec) / 10000, (int) (ru1.tv.tv_sec - ru0->tv.tv_sec), (int) (ru1.tv.tv_usec - ru0->tv.tv_usec) / 10000); diff --git a/src/backend/commands/vacuumlazy.c b/src/backend/commands/vacuumlazy.c index 38405f6c6c..8431dcdb0f 100644 --- a/src/backend/commands/vacuumlazy.c +++ b/src/backend/commands/vacuumlazy.c @@ -18,8 +18,8 @@ * * We can limit the storage for page free space to MaxFSMPages entries, * since that's the most the free space map will be willing to remember - * anyway. If the relation has fewer than that many pages with free space, - * life is easy: just build an array of per-page info. If it has more, + * anyway. If the relation has fewer than that many pages with free space, + * life is easy: just build an array of per-page info. If it has more, * we store the free space info as a heap ordered by amount of free space, * so that we can discard the pages with least free space to ensure we never * have more than MaxFSMPages entries in all. The surviving page entries @@ -31,7 +31,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/commands/vacuumlazy.c,v 1.8 2001/09/29 04:02:22 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/vacuumlazy.c,v 1.9 2001/10/25 05:49:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -51,7 +51,7 @@ * Space/time tradeoff parameters: do these need to be user-tunable? * * A page with less than PAGE_SPACE_THRESHOLD free space will be forgotten - * immediately, and not even passed to the free space map. Removing the + * immediately, and not even 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 * MultiRecordFreeSpace. Since the FSM will ignore pages below its own @@ -74,21 +74,21 @@ typedef struct LVRelStats { /* Overall statistics about rel */ - BlockNumber rel_pages; + BlockNumber rel_pages; double rel_tuples; - BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */ + BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */ /* List of TIDs of tuples we intend to delete */ /* NB: this list is ordered by TID address */ - int num_dead_tuples; /* current # of entries */ - int max_dead_tuples; /* # slots allocated in array */ - ItemPointer dead_tuples; /* array of ItemPointerData */ + int num_dead_tuples; /* current # of entries */ + int max_dead_tuples; /* # slots allocated in array */ + ItemPointer dead_tuples; /* array of ItemPointerData */ /* Array or heap of per-page info about free space */ /* We use a simple array until it fills up, then convert to heap */ - bool fs_is_heap; /* are we using heap organization? */ - int num_free_pages; /* current # of entries */ - int max_free_pages; /* # slots allocated in arrays */ - BlockNumber *free_pages; /* array or heap of block numbers */ - Size *free_spaceavail; /* array or heap of available space */ + bool fs_is_heap; /* are we using heap organization? */ + int num_free_pages; /* current # of entries */ + int max_free_pages; /* # slots allocated in arrays */ + BlockNumber *free_pages; /* array or heap of block numbers */ + Size *free_spaceavail; /* array or heap of available space */ } LVRelStats; @@ -100,20 +100,20 @@ static TransactionId FreezeLimit; /* non-export function prototypes */ static void lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, - Relation *Irel, int nindexes); + Relation *Irel, int nindexes); static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats); static void lazy_scan_index(Relation indrel, LVRelStats *vacrelstats); static void lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats); -static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, - int tupindex, LVRelStats *vacrelstats); +static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, + int tupindex, LVRelStats *vacrelstats); static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats); static BlockNumber count_nondeletable_pages(Relation onerel, - LVRelStats *vacrelstats); + LVRelStats *vacrelstats); static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks); static void lazy_record_dead_tuple(LVRelStats *vacrelstats, - ItemPointer itemptr); + ItemPointer itemptr); static void lazy_record_free_space(LVRelStats *vacrelstats, - BlockNumber page, Size avail); + BlockNumber page, Size avail); static bool lazy_tid_reaped(ItemPointer itemptr, void *state); static bool dummy_tid_reaped(ItemPointer itemptr, void *state); static void lazy_update_fsm(Relation onerel, LVRelStats *vacrelstats); @@ -136,7 +136,7 @@ lazy_vacuum_rel(Relation onerel, VacuumStmt *vacstmt) Relation *Irel; int nindexes; bool hasindex; - BlockNumber possibly_freeable; + BlockNumber possibly_freeable; /* initialize */ if (vacstmt->verbose) @@ -163,8 +163,8 @@ lazy_vacuum_rel(Relation onerel, VacuumStmt *vacstmt) /* * Optionally truncate the relation. * - * Don't even think about it unless we have a shot at releasing a - * goodly number of pages. Otherwise, the time taken isn't worth it. + * Don't even think about it unless we have a shot at releasing a goodly + * number of pages. Otherwise, the time taken isn't worth it. */ possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages; if (possibly_freeable > vacrelstats->rel_pages / REL_TRUNCATE_FRACTION) @@ -195,7 +195,7 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, blkno; HeapTupleData tuple; char *relname; - BlockNumber empty_pages, + BlockNumber empty_pages, changed_pages; double num_tuples, tups_vacuumed, @@ -231,8 +231,9 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, int prev_dead_count; /* - * If we are close to overrunning the available space for dead-tuple - * TIDs, pause and do a cycle of vacuuming before we tackle this page. + * If we are close to overrunning the available space for + * dead-tuple TIDs, pause and do a cycle of vacuuming before we + * tackle this page. */ if ((vacrelstats->max_dead_tuples - vacrelstats->num_dead_tuples) < MAX_TUPLES_PER_PAGE && vacrelstats->num_dead_tuples > 0) @@ -312,17 +313,18 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin)) { case HEAPTUPLE_DEAD: - tupgone = true; /* we can delete the tuple */ + tupgone = true; /* we can delete the tuple */ break; case HEAPTUPLE_LIVE: + /* - * Tuple is good. Consider whether to replace its xmin - * value with FrozenTransactionId. + * Tuple is good. Consider whether to replace its + * xmin value with FrozenTransactionId. * - * NB: Since we hold only a shared buffer lock here, - * we are assuming that TransactionId read/write - * is atomic. This is not the only place that makes - * such an assumption. It'd be possible to avoid the + * NB: Since we hold only a shared buffer lock here, we + * are assuming that TransactionId read/write is + * atomic. This is not the only place that makes such + * an assumption. It'd be possible to avoid the * assumption by momentarily acquiring exclusive lock, * but for the moment I see no need to. */ @@ -337,9 +339,10 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, } break; case HEAPTUPLE_RECENTLY_DEAD: + /* - * If tuple is recently deleted then we must not remove - * it from relation. + * If tuple is recently deleted then we must not + * remove it from relation. */ nkeep += 1; break; @@ -376,11 +379,11 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, num_tuples += 1; hastup = true; } - } /* scan along page */ + } /* scan along page */ /* - * If we remembered any tuples for deletion, then the page will - * be visited again by lazy_vacuum_heap, which will compute and + * If we remembered any tuples for deletion, then the page will be + * visited again by lazy_vacuum_heap, which will compute and * record its post-compaction free space. If not, then we're done * with this page, so remember its free space as-is. */ @@ -418,7 +421,7 @@ lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, /* Remove tuples from heap */ lazy_vacuum_heap(onerel, vacrelstats); } - else if (! did_vacuum_index) + else if (!did_vacuum_index) { /* Scan indexes just to update pg_class statistics about them */ for (i = 0; i < nindexes; i++) @@ -457,7 +460,7 @@ lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats) tupindex = 0; while (tupindex < vacrelstats->num_dead_tuples) { - BlockNumber tblk; + BlockNumber tblk; Buffer buf; Page page; @@ -493,7 +496,7 @@ static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats) { - OffsetNumber unbuf[BLCKSZ/sizeof(OffsetNumber)]; + OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)]; OffsetNumber *unused = unbuf; int uncnt; Page page = BufferGetPage(buffer); @@ -502,8 +505,8 @@ lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, START_CRIT_SECTION(); for (; tupindex < vacrelstats->num_dead_tuples; tupindex++) { - BlockNumber tblk; - OffsetNumber toff; + BlockNumber tblk; + OffsetNumber toff; tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]); if (tblk != blkno) @@ -542,10 +545,10 @@ lazy_scan_index(Relation indrel, LVRelStats *vacrelstats) vac_init_rusage(&ru0); /* - * If the index is not partial, skip the scan, and just assume it - * has the same number of tuples as the heap. + * If the index is not partial, skip the scan, and just assume it has + * the same number of tuples as the heap. */ - if (! vac_is_partial_index(indrel)) + if (!vac_is_partial_index(indrel)) { vac_update_relstats(RelationGetRelid(indrel), RelationGetNumberOfBlocks(indrel), @@ -555,23 +558,23 @@ lazy_scan_index(Relation indrel, LVRelStats *vacrelstats) } /* - * If index is unsafe for concurrent access, must lock it; - * but a shared lock should be sufficient. + * If index is unsafe for concurrent access, must lock it; but a + * shared lock should be sufficient. */ - if (! indrel->rd_am->amconcurrent) + if (!indrel->rd_am->amconcurrent) LockRelation(indrel, AccessShareLock); /* * Even though we're not planning to delete anything, use the - * ambulkdelete call, so that the scan happens within the index AM - * for more speed. + * ambulkdelete call, so that the scan happens within the index AM for + * more speed. */ stats = index_bulk_delete(indrel, dummy_tid_reaped, NULL); /* * Release lock acquired above. */ - if (! indrel->rd_am->amconcurrent) + if (!indrel->rd_am->amconcurrent) UnlockRelation(indrel, AccessShareLock); if (!stats) @@ -610,7 +613,7 @@ lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats) /* * If index is unsafe for concurrent access, must lock it. */ - if (! indrel->rd_am->amconcurrent) + if (!indrel->rd_am->amconcurrent) LockRelation(indrel, AccessExclusiveLock); /* Do bulk deletion */ @@ -619,7 +622,7 @@ lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats) /* * Release lock acquired above. */ - if (! indrel->rd_am->amconcurrent) + if (!indrel->rd_am->amconcurrent) UnlockRelation(indrel, AccessExclusiveLock); /* now update statistics in pg_class */ @@ -644,8 +647,8 @@ lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats) static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats) { - BlockNumber old_rel_pages = vacrelstats->rel_pages; - BlockNumber new_rel_pages; + BlockNumber old_rel_pages = vacrelstats->rel_pages; + BlockNumber new_rel_pages; BlockNumber *pages; Size *spaceavail; int n; @@ -656,12 +659,13 @@ lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats) vac_init_rusage(&ru0); /* - * We need full exclusive lock on the relation in order to do truncation. - * If we can't get it, give up rather than waiting --- we don't want - * to block other backends, and we don't want to deadlock (which is - * quite possible considering we already hold a lower-grade lock). + * We need full exclusive lock on the relation in order to do + * truncation. If we can't get it, give up rather than waiting --- we + * don't want to block other backends, and we don't want to deadlock + * (which is quite possible considering we already hold a lower-grade + * lock). */ - if (! ConditionalLockRelation(onerel, AccessExclusiveLock)) + if (!ConditionalLockRelation(onerel, AccessExclusiveLock)) return; /* @@ -680,9 +684,9 @@ lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats) /* * Scan backwards from the end to verify that the end pages actually - * contain nothing we need to keep. This is *necessary*, not optional, - * because other backends could have added tuples to these pages whilst - * we were vacuuming. + * contain nothing we need to keep. This is *necessary*, not + * optional, because other backends could have added tuples to these + * pages whilst we were vacuuming. */ new_rel_pages = count_nondeletable_pages(onerel, vacrelstats); @@ -710,9 +714,10 @@ lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats) * Do the physical truncation. */ new_rel_pages = smgrtruncate(DEFAULT_SMGR, onerel, new_rel_pages); - onerel->rd_nblocks = new_rel_pages; /* update relcache immediately */ + onerel->rd_nblocks = new_rel_pages; /* update relcache immediately */ onerel->rd_targblock = InvalidBlockNumber; - vacrelstats->rel_pages = new_rel_pages; /* save new number of blocks */ + vacrelstats->rel_pages = new_rel_pages; /* save new number of + * blocks */ /* * Drop free-space info for removed blocks; these must not get entered @@ -808,15 +813,16 @@ count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats) switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin)) { case HEAPTUPLE_DEAD: - tupgone = true; /* we can delete the tuple */ + tupgone = true; /* we can delete the tuple */ break; case HEAPTUPLE_LIVE: /* Shouldn't be necessary to re-freeze anything */ break; case HEAPTUPLE_RECENTLY_DEAD: + /* - * If tuple is recently deleted then we must not remove - * it from relation. + * If tuple is recently deleted then we must not + * remove it from relation. */ break; case HEAPTUPLE_INSERT_IN_PROGRESS: @@ -839,7 +845,7 @@ count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats) hastup = true; break; /* can stop scanning */ } - } /* scan along page */ + } /* scan along page */ LockBuffer(buf, BUFFER_LOCK_UNLOCK); @@ -855,8 +861,8 @@ count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats) /* * If we fall out of the loop, all the previously-thought-to-be-empty - * pages really are; we need not bother to look at the last known-nonempty - * page. + * pages really are; we need not bother to look at the last + * known-nonempty page. */ return vacrelstats->nonempty_pages; } @@ -907,9 +913,9 @@ lazy_record_dead_tuple(LVRelStats *vacrelstats, ItemPointer itemptr) { /* - * The array shouldn't overflow under normal behavior, - * but perhaps it could if we are given a really small VacuumMem. - * In that case, just forget the last few tuples. + * The array shouldn't overflow under normal behavior, but perhaps it + * could if we are given a really small VacuumMem. In that case, just + * forget the last few tuples. */ if (vacrelstats->num_dead_tuples < vacrelstats->max_dead_tuples) { @@ -960,29 +966,29 @@ lazy_record_free_space(LVRelStats *vacrelstats, */ /* If we haven't yet converted the array to heap organization, do it */ - if (! vacrelstats->fs_is_heap) + if (!vacrelstats->fs_is_heap) { /* * Scan backwards through the array, "sift-up" each value into its - * correct position. We can start the scan at n/2-1 since each entry - * above that position has no children to worry about. + * correct position. We can start the scan at n/2-1 since each + * entry above that position has no children to worry about. */ - int l = n / 2; + int l = n / 2; while (--l >= 0) { - BlockNumber R = pages[l]; + BlockNumber R = pages[l]; Size K = spaceavail[l]; int i; /* i is where the "hole" is */ i = l; for (;;) { - int j = 2*i + 1; + int j = 2 * i + 1; if (j >= n) break; - if (j+1 < n && spaceavail[j] > spaceavail[j+1]) + if (j + 1 < n && spaceavail[j] > spaceavail[j + 1]) j++; if (K <= spaceavail[j]) break; @@ -1001,20 +1007,20 @@ lazy_record_free_space(LVRelStats *vacrelstats, if (avail > spaceavail[0]) { /* - * Notionally, we replace the zero'th entry with the new data, - * and then sift-up to maintain the heap property. Physically, - * the new data doesn't get stored into the arrays until we find - * the right location for it. + * Notionally, we replace the zero'th entry with the new data, and + * then sift-up to maintain the heap property. Physically, the + * new data doesn't get stored into the arrays until we find the + * right location for it. */ - int i = 0; /* i is where the "hole" is */ + int i = 0; /* i is where the "hole" is */ for (;;) { - int j = 2*i + 1; + int j = 2 * i + 1; if (j >= n) break; - if (j+1 < n && spaceavail[j] > spaceavail[j+1]) + if (j + 1 < n && spaceavail[j] > spaceavail[j + 1]) j++; if (avail <= spaceavail[j]) break; @@ -1038,7 +1044,7 @@ static bool lazy_tid_reaped(ItemPointer itemptr, void *state) { LVRelStats *vacrelstats = (LVRelStats *) state; - ItemPointer res; + ItemPointer res; res = (ItemPointer) bsearch((void *) itemptr, (void *) vacrelstats->dead_tuples, @@ -1066,9 +1072,9 @@ static void lazy_update_fsm(Relation onerel, LVRelStats *vacrelstats) { /* - * Since MultiRecordFreeSpace doesn't currently impose any restrictions - * on the ordering of the input, we can just pass it the arrays as-is, - * whether they are in heap or linear order. + * Since MultiRecordFreeSpace doesn't currently impose any + * restrictions on the ordering of the input, we can just pass it the + * arrays as-is, whether they are in heap or linear order. */ MultiRecordFreeSpace(&onerel->rd_node, 0, MaxBlockNumber, diff --git a/src/backend/commands/variable.c b/src/backend/commands/variable.c index 9da6776074..4ed17e8fbe 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.54 2001/10/18 17:30:14 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.55 2001/10/25 05:49:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -334,9 +334,10 @@ set_default_datestyle(void) */ DBDate = strdup(DBDate); - /* Parse desired setting into DateStyle/EuroDates - * Use parse_datestyle_internal() to avoid any palloc() issues per above - * - thomas 2001-10-15 + /* + * Parse desired setting into DateStyle/EuroDates Use + * parse_datestyle_internal() to avoid any palloc() issues per above - + * thomas 2001-10-15 */ parse_datestyle_internal(DBDate); @@ -380,7 +381,7 @@ parse_timezone(List *args) foreach(arg, args) { - A_Const *p; + A_Const *p; Assert(IsA(arg, List)); p = lfirst(arg); @@ -394,24 +395,28 @@ parse_timezone(List *args) Interval *interval; interval = DatumGetIntervalP(DirectFunctionCall3(interval_in, - CStringGetDatum(p->val.val.str), - ObjectIdGetDatum(InvalidOid), - Int32GetDatum(-1))); + CStringGetDatum(p->val.val.str), + ObjectIdGetDatum(InvalidOid), + Int32GetDatum(-1))); if (interval->month != 0) elog(ERROR, "SET TIME ZONE illegal INTERVAL; month not allowed"); CTimeZone = interval->time; } else if (strcmp(type->name, "float8") == 0) { - float8 time; + float8 time; time = DatumGetFloat8(DirectFunctionCall1(float8in, CStringGetDatum(p->val.val.str))); CTimeZone = time * 3600; } - /* We do not actually generate an integer constant in gram.y so this is not used... */ + + /* + * We do not actually generate an integer constant in gram.y + * so this is not used... + */ else if (strcmp(type->name, "int4") == 0) { - int32 time; + int32 time; time = p->val.val.ival; CTimeZone = time * 3600; @@ -462,11 +467,11 @@ parse_timezone(List *args) static bool show_timezone(void) { - char *tzn; + char *tzn; if (HasCTZSet) { - Interval interval; + Interval interval; interval.month = 0; interval.time = CTimeZone; @@ -474,9 +479,7 @@ show_timezone(void) tzn = DatumGetCString(DirectFunctionCall1(interval_out, IntervalPGetDatum(&interval))); } else - { tzn = getenv("TZ"); - } if (tzn != NULL) elog(NOTICE, "Time zone is '%s'", tzn); @@ -500,9 +503,7 @@ static bool reset_timezone(void) { if (HasCTZSet) - { HasCTZSet = false; - } /* no time zone has been set in this session? */ else if (defaultTZ == NULL) @@ -545,7 +546,7 @@ reset_timezone(void) static bool parse_XactIsoLevel(List *args) { - char *value; + char *value; if (args == NULL) return reset_XactIsoLevel(); @@ -603,8 +604,8 @@ reset_XactIsoLevel(void) static bool parse_random_seed(List *args) { - char *value; - double seed = 0; + char *value; + double seed = 0; if (args == NULL) return reset_random_seed(); @@ -648,9 +649,10 @@ reset_random_seed(void) static bool parse_client_encoding(List *args) { - char *value; + char *value; + #ifdef MULTIBYTE - int encoding; + int encoding; #endif if (args == NULL) @@ -679,7 +681,7 @@ parse_client_encoding(List *args) } #else if (value && - strcasecmp(value, pg_get_client_encoding_name()) != 0) + strcasecmp(value, pg_get_client_encoding_name()) != 0) elog(ERROR, "Client encoding %s is not supported", value); #endif return TRUE; @@ -766,14 +768,14 @@ SetPGVariable(const char *name, List *args) parse_random_seed(args); else { - /* For routines defined somewhere else, - * go ahead and extract the string argument - * to match the original interface definition. + /* + * For routines defined somewhere else, go ahead and extract the + * string argument to match the original interface definition. * Later, we can change this code too... */ - char *value; + char *value; - value = ((args != NULL)? ((A_Const *) lfirst(args))->val.val.str: NULL); + value = ((args != NULL) ? ((A_Const *) lfirst(args))->val.val.str : NULL); if (strcasecmp(name, "session_authorization") == 0) SetSessionAuthorization(value); diff --git a/src/backend/commands/view.c b/src/backend/commands/view.c index 2bb9fd75a7..9d1254a4cb 100644 --- a/src/backend/commands/view.c +++ b/src/backend/commands/view.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: view.c,v 1.57 2001/08/16 20:38:53 tgl Exp $ + * $Id: view.c,v 1.58 2001/10/25 05:49:26 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -131,7 +131,6 @@ DefineViewRules(char *viewName, Query *viewParse) RuleStmt *replace_rule; RuleStmt *append_rule; RuleStmt *delete_rule; - #endif retrieve_rule = FormViewRetrieveRule(viewName, viewParse); @@ -141,7 +140,6 @@ DefineViewRules(char *viewName, Query *viewParse) replace_rule = FormViewReplaceRule(viewName, viewParse); append_rule = FormViewAppendRule(viewName, viewParse); delete_rule = FormViewDeleteRule(viewName, viewParse); - #endif DefineQueryRewrite(retrieve_rule); @@ -229,7 +227,6 @@ UpdateRangeTableOfViewParse(char *viewName, Query *viewParse) void DefineView(char *viewName, Query *viewParse) { - /* * Create the "view" relation NOTE: if it already exists, the xact * will be aborted. @@ -264,7 +261,6 @@ DefineView(char *viewName, Query *viewParse) void RemoveView(char *viewName) { - /* * We just have to drop the relation; the associated rules will be * cleaned up automatically. diff --git a/src/backend/executor/_deadcode/nodeTee.c b/src/backend/executor/_deadcode/nodeTee.c index 5ec43e377e..dd7460634e 100644 --- a/src/backend/executor/_deadcode/nodeTee.c +++ b/src/backend/executor/_deadcode/nodeTee.c @@ -15,7 +15,7 @@ * ExecInitTee * ExecEndTee * - * $Id: nodeTee.c,v 1.10 2001/03/22 06:16:13 momjian Exp $ + * $Id: nodeTee.c,v 1.11 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -336,7 +336,6 @@ ExecTee(Tee * node, Plan *parent) slot = ExecProcNode(childNode, (Plan *) node); if (!TupIsNull(slot)) { - /* * heap_insert changes something... */ @@ -361,7 +360,6 @@ ExecTee(Tee * node, Plan *parent) teeState->tee_leftScanDesc : teeState->tee_rightScanDesc; { - /* * move the scandesc forward so we don't re-read this * tuple later diff --git a/src/backend/executor/execAmi.c b/src/backend/executor/execAmi.c index 6303613faa..af0e190d39 100644 --- a/src/backend/executor/execAmi.c +++ b/src/backend/executor/execAmi.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: execAmi.c,v 1.59 2001/09/18 01:59:06 tgl Exp $ + * $Id: execAmi.c,v 1.60 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -224,7 +224,6 @@ ExecCloseR(Plan *node) for (i = 0; i < numIndices; i++) { - /* * shut down each of the index scans and close each of the * index relations @@ -410,7 +409,7 @@ ExecMarkPos(Plan *node) { switch (nodeTag(node)) { - case T_SeqScan: + case T_SeqScan: ExecSeqMarkPos((SeqScan *) node); break; @@ -452,7 +451,7 @@ ExecRestrPos(Plan *node) { switch (nodeTag(node)) { - case T_SeqScan: + case T_SeqScan: ExecSeqRestrPos((SeqScan *) node); break; diff --git a/src/backend/executor/execFlatten.c b/src/backend/executor/execFlatten.c index 3be50c09bb..8d1eaea402 100644 --- a/src/backend/executor/execFlatten.c +++ b/src/backend/executor/execFlatten.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/Attic/execFlatten.c,v 1.14 2001/01/24 19:42:53 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/Attic/execFlatten.c,v 1.15 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -33,7 +33,6 @@ #ifdef SETS_FIXED static bool FjoinBumpOuterNodes(TargetEntry *tlist, ExprContext *econtext, DatumPtr results, char *nulls); - #endif @@ -81,7 +80,6 @@ ExecEvalFjoin(TargetEntry *tlist, */ if (!fjNode->fj_initialized) { - /* * Initialize all of the Outer nodes */ @@ -127,7 +125,6 @@ ExecEvalFjoin(TargetEntry *tlist, } else { - /* * If we're already initialized, all we need to do is get the next * inner result and pair it up with the existing outer node result @@ -242,5 +239,4 @@ FjoinBumpOuterNodes(TargetEntry *tlist, } return false; } - #endif diff --git a/src/backend/executor/execJunk.c b/src/backend/executor/execJunk.c index 68dc74a3a8..1a11015498 100644 --- a/src/backend/executor/execJunk.c +++ b/src/backend/executor/execJunk.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execJunk.c,v 1.28 2001/05/27 20:48:51 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execJunk.c,v 1.29 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -111,7 +111,6 @@ ExecInitJunkFilter(List *targetList, TupleDesc tupType, resjunk = resdom->resjunk; if (!resjunk) { - /* * make a copy of the resdom node, changing its resno. */ diff --git a/src/backend/executor/execMain.c b/src/backend/executor/execMain.c index 6b1db391ee..6e1145ac77 100644 --- a/src/backend/executor/execMain.c +++ b/src/backend/executor/execMain.c @@ -27,7 +27,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.148 2001/09/18 01:59:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.149 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -287,7 +287,6 @@ ExecutorEnd(QueryDesc *queryDesc, EState *estate) static void ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan) { - /* * Check RTEs in the query's primary rangetable. */ @@ -428,7 +427,6 @@ ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation) if (rte->checkForWrite) { - /* * Note: write access in a SELECT context means SELECT FOR UPDATE. * Right now we don't distinguish that from true update as far as @@ -521,7 +519,6 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) if (resultRelations != NIL) { - /* * Multiple result relations (due to inheritance) * parseTree->resultRelations identifies them all @@ -544,7 +541,6 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) } else { - /* * Single result relation identified by * parseTree->resultRelation @@ -564,7 +560,6 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) } else { - /* * if no result relation, then set state appropriately */ @@ -599,9 +594,9 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) /* * initialize the executor "tuple" table. We need slots for all the - * plan nodes, plus possibly output slots for the junkfilter(s). - * At this point we aren't sure if we need junkfilters, so just add - * slots for them unconditionally. + * plan nodes, plus possibly output slots for the junkfilter(s). At + * this point we aren't sure if we need junkfilters, so just add slots + * for them unconditionally. */ { int nSlots = ExecCountSlotsNode(plan); @@ -669,7 +664,6 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) if (junk_filter_needed) { - /* * If there are multiple result relations, each one needs its * own junk filter. Note this is only possible for @@ -694,7 +688,7 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) j = ExecInitJunkFilter(subplan->targetlist, ExecGetTupType(subplan), - ExecAllocTableSlot(estate->es_tupleTable)); + ExecAllocTableSlot(estate->es_tupleTable)); resultRelInfo->ri_junkFilter = j; resultRelInfo++; subplans = lnext(subplans); @@ -714,7 +708,7 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) j = ExecInitJunkFilter(plan->targetlist, tupType, - ExecAllocTableSlot(estate->es_tupleTable)); + ExecAllocTableSlot(estate->es_tupleTable)); estate->es_junkFilter = j; if (estate->es_result_relation_info) estate->es_result_relation_info->ri_junkFilter = j; @@ -741,13 +735,11 @@ InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate) if (!parseTree->isPortal) { - /* * a select into table */ if (parseTree->into != NULL) { - /* * create the "into" relation */ @@ -1101,7 +1093,7 @@ lnext: ; newTuple = ExecRemoveJunk(junkfilter, slot); slot = ExecStoreTuple(newTuple, /* tuple to store */ - junkfilter->jf_resultSlot, /* dest slot */ + junkfilter->jf_resultSlot, /* dest slot */ InvalidBuffer, /* this tuple has no * buffer */ true); /* tuple should be pfreed */ @@ -1234,7 +1226,7 @@ ExecAppend(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; @@ -1245,7 +1237,6 @@ ExecAppend(TupleTableSlot *slot, if (newtuple != tuple) /* modified by Trigger(s) */ { - /* * Insert modified tuple into tuple table slot, replacing the * original. We assume that it was allocated in per-tuple @@ -1314,7 +1305,7 @@ ExecDelete(TupleTableSlot *slot, /* BEFORE ROW DELETE Triggers */ if (resultRelInfo->ri_TrigDesc && - resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0) + resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0) { bool dodelete; @@ -1421,7 +1412,7 @@ ExecReplace(TupleTableSlot *slot, /* BEFORE ROW UPDATE Triggers */ if (resultRelInfo->ri_TrigDesc && - resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0) + resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0) { HeapTuple newtuple; @@ -1433,7 +1424,6 @@ ExecReplace(TupleTableSlot *slot, if (newtuple != tuple) /* modified by Trigger(s) */ { - /* * Insert modified tuple into tuple table slot, replacing the * original. We assume that it was allocated in per-tuple @@ -1448,11 +1438,11 @@ ExecReplace(TupleTableSlot *slot, /* * Check the constraints of the tuple * - * If we generate a new candidate tuple after EvalPlanQual testing, - * we must loop back here and recheck constraints. (We don't need to - * redo triggers, however. If there are any BEFORE triggers then - * trigger.c will have done mark4update to lock the correct tuple, - * so there's no need to do them again.) + * If we generate a new candidate tuple after EvalPlanQual testing, we + * must loop back here and recheck constraints. (We don't need to + * redo triggers, however. If there are any BEFORE triggers then + * trigger.c will have done mark4update to lock the correct tuple, so + * there's no need to do them again.) */ lreplace:; if (resultRelationDesc->rd_att->constr) @@ -1483,7 +1473,7 @@ lreplace:; *tupleid = ctid; tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot); slot = ExecStoreTuple(tuple, - estate->es_junkFilter->jf_resultSlot, + estate->es_junkFilter->jf_resultSlot, InvalidBuffer, true); goto lreplace; } @@ -1641,9 +1631,7 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) */ if (estate->es_result_relation_info != NULL && estate->es_result_relation_info->ri_RangeTableIndex == rti) - { relation = estate->es_result_relation_info->ri_RelationDesc; - } else { List *l; @@ -1724,7 +1712,7 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) *tid = tuple.t_self; /* - * Need to run a recheck subquery. Find or create a PQ stack entry. + * Need to run a recheck subquery. Find or create a PQ stack entry. */ epq = (evalPlanQual *) estate->es_evalPlanQual; rtsize = length(estate->es_range_table); @@ -1782,18 +1770,20 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) { newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual)); newepq->free = NULL; + /* - * Each stack level has its own copy of the plan tree. This + * Each stack level has its own copy of the plan tree. This * is wasteful, but necessary as long as plan nodes point to - * exec state nodes rather than vice versa. Note that copyfuncs.c - * doesn't attempt to copy the exec state nodes, which is a good - * thing in this situation. + * exec state nodes rather than vice versa. Note that + * copyfuncs.c doesn't attempt to copy the exec state nodes, + * which is a good thing in this situation. */ newepq->plan = copyObject(estate->es_origPlan); + /* * Init stack level's EState. We share top level's copy of - * es_result_relations array and other non-changing status. - * We need our own tupletable, es_param_exec_vals, and other + * es_result_relations array and other non-changing status. We + * need our own tupletable, es_param_exec_vals, and other * changeable state. */ epqstate = &(newepq->estate); @@ -1805,11 +1795,12 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) sizeof(ParamExecData)); epqstate->es_tupleTable = NULL; epqstate->es_per_tuple_exprcontext = NULL; + /* - * 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 *) palloc(rtsize * sizeof(bool)); if (epq == NULL) @@ -1842,12 +1833,12 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) epqstate = &(epq->estate); /* - * Ok - we're requested for the same RTE. Unfortunately we still - * have to end and restart execution of the plan, because ExecReScan + * Ok - we're requested for the same RTE. Unfortunately we still have + * to end and restart execution of the plan, because ExecReScan * wouldn't ensure that upper plan nodes would reset themselves. We - * could make that work if insertion of the target tuple were integrated - * with the Param mechanism somehow, so that the upper plan nodes know - * that their children's outputs have changed. + * could make that work if insertion of the target tuple were + * integrated with the Param mechanism somehow, so that the upper plan + * nodes know that their children's outputs have changed. */ if (endNode) { @@ -1858,8 +1849,8 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid) } /* - * free old RTE' tuple, if any, and store target tuple where relation's - * scan node will see it + * free old RTE' tuple, if any, and store target tuple where + * relation's scan node will see it */ if (epqstate->es_evTuple[rti - 1] != NULL) heap_freetuple(epqstate->es_evTuple[rti - 1]); diff --git a/src/backend/executor/execProcnode.c b/src/backend/executor/execProcnode.c index 0d66cd76c1..5cbd2ea562 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.27 2001/09/18 01:59:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execProcnode.c,v 1.28 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -267,9 +267,9 @@ ExecProcNode(Plan *node, Plan *parent) switch (nodeTag(node)) { - /* - * control nodes - */ + /* + * control nodes + */ case T_Result: result = ExecResult((Result *) node); break; @@ -473,9 +473,9 @@ ExecEndNode(Plan *node, Plan *parent) switch (nodeTag(node)) { - /* - * control nodes - */ + /* + * control nodes + */ case T_Result: ExecEndResult((Result *) node); break; diff --git a/src/backend/executor/execQual.c b/src/backend/executor/execQual.c index ea32b5ab1d..f78517b184 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.88 2001/09/21 00:11:30 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.89 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -62,9 +62,9 @@ static Datum ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull); static Datum ExecEvalCase(CaseExpr *caseExpr, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); static Datum ExecEvalNullTest(NullTest *ntest, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull, ExprDoneCond *isDone); static Datum ExecEvalBooleanTest(BooleanTest *btest, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull, ExprDoneCond *isDone); /*---------- @@ -126,7 +126,6 @@ ExecEvalArrayRef(ArrayRef *arrayRef, } else { - /* * Empty refexpr indicates we are doing an INSERT into an array * column. For now, we just take the refassgnexpr (which the @@ -339,9 +338,9 @@ ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull) * the entire tuple; we give back a whole slot so that callers know * what the tuple looks like. * - * 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 + * 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 * TransactionCommandContext 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 @@ -434,7 +433,6 @@ ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull) matchFound = 0; if (paramList != NULL) { - /* * search for an entry in 'paramList' that matches the * `expression'. @@ -485,7 +483,6 @@ ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull) if (!matchFound) { - /* * ooops! we couldn't find this parameter in the parameter list. * Signal an error @@ -1128,28 +1125,28 @@ ExecEvalNullTest(NullTest *ntest, result = ExecEvalExpr(ntest->arg, econtext, isNull, isDone); switch (ntest->nulltesttype) - { - case IS_NULL: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(true); - } - else - return BoolGetDatum(false); - case IS_NOT_NULL: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(false); - } - else - return BoolGetDatum(true); - default: - elog(ERROR, "ExecEvalNullTest: unexpected nulltesttype %d", - (int) ntest->nulltesttype); - return (Datum) 0; /* keep compiler quiet */ - } + { + case IS_NULL: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(true); + } + else + return BoolGetDatum(false); + case IS_NOT_NULL: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(false); + } + else + return BoolGetDatum(true); + default: + elog(ERROR, "ExecEvalNullTest: unexpected nulltesttype %d", + (int) ntest->nulltesttype); + return (Datum) 0; /* keep compiler quiet */ + } } /* ---------------------------------------------------------------- @@ -1168,68 +1165,68 @@ ExecEvalBooleanTest(BooleanTest *btest, result = ExecEvalExpr(btest->arg, econtext, isNull, isDone); switch (btest->booltesttype) - { - case IS_TRUE: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(false); - } - else if (DatumGetBool(result)) - return BoolGetDatum(true); + { + case IS_TRUE: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(false); + } + else if (DatumGetBool(result)) + return BoolGetDatum(true); else - return BoolGetDatum(false); - case IS_NOT_TRUE: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(true); - } - else if (DatumGetBool(result)) - return BoolGetDatum(false); + return BoolGetDatum(false); + case IS_NOT_TRUE: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(true); + } + else if (DatumGetBool(result)) + return BoolGetDatum(false); else - return BoolGetDatum(true); - case IS_FALSE: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(false); - } - else if (DatumGetBool(result)) - return BoolGetDatum(false); + return BoolGetDatum(true); + case IS_FALSE: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(false); + } + else if (DatumGetBool(result)) + return BoolGetDatum(false); else - return BoolGetDatum(true); - case IS_NOT_FALSE: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(true); - } - else if (DatumGetBool(result)) - return BoolGetDatum(true); + return BoolGetDatum(true); + case IS_NOT_FALSE: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(true); + } + else if (DatumGetBool(result)) + return BoolGetDatum(true); else - return BoolGetDatum(false); - case IS_UNKNOWN: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(true); - } + return BoolGetDatum(false); + case IS_UNKNOWN: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(true); + } else - return BoolGetDatum(false); - case IS_NOT_UNKNOWN: - if (*isNull) - { - *isNull = false; - return BoolGetDatum(false); - } + return BoolGetDatum(false); + case IS_NOT_UNKNOWN: + if (*isNull) + { + *isNull = false; + return BoolGetDatum(false); + } else - return BoolGetDatum(true); - default: - elog(ERROR, "ExecEvalBooleanTest: unexpected booltesttype %d", - (int) btest->booltesttype); - return (Datum) 0; /* keep compiler quiet */ - } + return BoolGetDatum(true); + default: + elog(ERROR, "ExecEvalBooleanTest: unexpected booltesttype %d", + (int) btest->booltesttype); + return (Datum) 0; /* keep compiler quiet */ + } } /* ---------------------------------------------------------------- @@ -1409,15 +1406,15 @@ ExecEvalExpr(Node *expression, break; case T_NullTest: retDatum = ExecEvalNullTest((NullTest *) expression, - econtext, - isNull, - isDone); + econtext, + isNull, + isDone); break; case T_BooleanTest: retDatum = ExecEvalBooleanTest((BooleanTest *) expression, - econtext, - isNull, - isDone); + econtext, + isNull, + isDone); break; default: @@ -1665,7 +1662,7 @@ ExecTargetList(List *targetlist, * generating multiple tuples, when one or more tlist items return * sets. (We expect the caller to call us again if we return: * - * isDone = ExprMultipleResult.) + * isDone = ExprMultipleResult.) */ if (nodomains > NPREALLOCDOMAINS) { @@ -1774,13 +1771,11 @@ ExecTargetList(List *targetlist, if (haveDoneSets) { - /* * note: can't get here unless we verified isDone != NULL */ if (*isDone == ExprSingleResult) { - /* * all sets are done, so report that tlist expansion is * complete. @@ -1792,7 +1787,6 @@ ExecTargetList(List *targetlist, } else { - /* * We have some done and some undone sets. Restart the done * ones so that we can deliver a tuple (if possible). @@ -1815,7 +1809,6 @@ 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. diff --git a/src/backend/executor/execScan.c b/src/backend/executor/execScan.c index 51a05a6457..63aaa63858 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.17 2001/03/22 06:16:12 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execScan.c,v 1.18 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -122,7 +122,6 @@ ExecScan(Scan *node, */ if (!qual || ExecQual(qual, econtext, false)) { - /* * Found a satisfactory scan tuple. * diff --git a/src/backend/executor/execTuples.c b/src/backend/executor/execTuples.c index b6f7b1ee6f..2c63acb8b6 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.48 2001/03/22 06:16:12 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execTuples.c,v 1.49 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -241,10 +241,10 @@ ExecAllocTableSlot(TupleTable table) Assert(table != NULL); /* - * if our table is full we have to allocate a larger size table. - * Since ExecAllocTableSlot() is only called before the table is ever - * used to store tuples, we don't have to worry about the contents of - * the old table. If this changes, then we will have to preserve the + * if our table is full we have to allocate a larger size table. Since + * ExecAllocTableSlot() is only called before the table is ever used + * to store tuples, we don't have to worry about the contents of the + * old table. If this changes, then we will have to preserve the * contents. -cim 6/23/90 * * Unfortunately, we *cannot* do this. All of the nodes in the plan that @@ -347,7 +347,6 @@ ExecStoreTuple(HeapTuple tuple, Buffer buffer, bool shouldFree) { - /* * sanity checks */ @@ -407,7 +406,7 @@ ExecClearTuple(TupleTableSlot *slot) /* slot in which to store tuple */ slot->val = (HeapTuple) NULL; - slot->ttc_shouldFree = true;/* probably useless code... */ + slot->ttc_shouldFree = true; /* probably useless code... */ /* * Drop the pin on the referenced buffer, if there is one. diff --git a/src/backend/executor/execUtils.c b/src/backend/executor/execUtils.c index 2c76c9b7d9..d710c82703 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.77 2001/07/16 05:06:58 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/execUtils.c,v 1.78 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -78,7 +78,6 @@ ResetTupleCount(void) NTupleReplaced = 0; NIndexTupleProcessed = 0; } - #endif /* ---------------------------------------------------------------- @@ -117,7 +116,6 @@ DisplayTupleCount(FILE *statfp) (NTupleReplaced == 1) ? "" : "s"); fprintf(statfp, "\n"); } - #endif /* ---------------------------------------------------------------- @@ -504,26 +502,26 @@ ExecOpenIndices(ResultRelInfo *resultRelInfo) /* * Open (and lock, if necessary) the index relation * - * If the index AM is not safe for concurrent updates, obtain - * an exclusive lock on the index to lock out other updaters as - * well as readers (index_beginscan places AccessShareLock). - * We will release this lock in ExecCloseIndices. + * If the index AM is not safe for concurrent updates, obtain an + * exclusive lock on the index to lock out other updaters as well + * as readers (index_beginscan places AccessShareLock). We will + * release this lock in ExecCloseIndices. * * If the index AM supports concurrent updates, we obtain no lock * here at all, which is a tad weird, but safe since any critical - * operation on the index (like deleting it) will acquire exclusive - * lock on the parent table. Perhaps someday we should acquire - * RowExclusiveLock on the index here? + * operation on the index (like deleting it) will acquire + * exclusive lock on the parent table. Perhaps someday we should + * acquire RowExclusiveLock on the index here? * * If there are multiple not-concurrent-safe indexes, all backends - * must lock the indexes in the same order or we will get deadlocks - * here during concurrent updates. This is guaranteed by - * RelationGetIndexList(), which promises to return the index list - * in OID order. + * must lock the indexes in the same order or we will get + * deadlocks here during concurrent updates. This is guaranteed + * by RelationGetIndexList(), which promises to return the index + * list in OID order. */ indexDesc = index_open(indexOid); - if (! indexDesc->rd_am->amconcurrent) + if (!indexDesc->rd_am->amconcurrent) LockRelation(indexDesc, AccessExclusiveLock); /* @@ -572,7 +570,7 @@ ExecCloseIndices(ResultRelInfo *resultRelInfo) continue; /* Drop lock, if one was acquired by ExecOpenIndices */ - if (! indexDescs[i]->rd_am->amconcurrent) + if (!indexDescs[i]->rd_am->amconcurrent) UnlockRelation(indexDescs[i], AccessExclusiveLock); index_close(indexDescs[i]); diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c index 73dd6937d7..fbe8e7f5bf 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.45 2001/03/22 06:16:12 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/functions.c,v 1.46 2001/10/25 05:49:27 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -32,7 +32,7 @@ */ typedef enum { - F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE + F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE } ExecStatus; typedef struct local_es @@ -201,7 +201,6 @@ init_sql_fcache(FmgrInfo *finfo) } else { - /* * This is a hack. We assume here that any function returning a * tuple returns it by reference. This needs to be fixed, since @@ -257,7 +256,6 @@ init_sql_fcache(FmgrInfo *finfo) static void postquel_start(execution_state *es) { - /* * Do nothing for utility commands. (create, destroy...) DZ - * 30-8-1996 @@ -274,7 +272,6 @@ postquel_getnext(execution_state *es) if (es->qd->operation == CMD_UTILITY) { - /* * Process a utility command. (create, destroy...) DZ - 30-8-1996 */ @@ -292,7 +289,6 @@ postquel_getnext(execution_state *es) static void postquel_end(execution_state *es) { - /* * Do nothing for utility commands. (create, destroy...) DZ - * 30-8-1996 @@ -417,7 +413,6 @@ postquel_execute(execution_state *es, */ if (fcache->returnsTuple) { - /* * XXX do we need to remove junk attrs from the result tuple? * Probably OK to leave them, as long as they are at the end. @@ -528,7 +523,6 @@ fmgr_sql(PG_FUNCTION_ARGS) */ if (es == (execution_state *) NULL) { - /* * Reset the execution states to start over again */ diff --git a/src/backend/executor/instrument.c b/src/backend/executor/instrument.c index 753efbcee9..e270f7c771 100644 --- a/src/backend/executor/instrument.c +++ b/src/backend/executor/instrument.c @@ -1,13 +1,13 @@ /*------------------------------------------------------------------------- * * instrument.c - * functions for instrumentation of plan execution + * functions for instrumentation of plan execution * * * Copyright (c) 2001, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/instrument.c,v 1.1 2001/09/18 01:59:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/instrument.c,v 1.2 2001/10/25 05:49:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -22,9 +22,9 @@ Instrumentation * InstrAlloc(void) { - Instrumentation *instr = palloc( sizeof(Instrumentation) ); + Instrumentation *instr = palloc(sizeof(Instrumentation)); - memset( instr, 0, sizeof(Instrumentation) ); + memset(instr, 0, sizeof(Instrumentation)); return instr; } @@ -47,7 +47,7 @@ void InstrStopNode(Instrumentation *instr, bool returnedTuple) { struct timeval endtime; - + if (!instr) return; @@ -56,10 +56,10 @@ InstrStopNode(Instrumentation *instr, bool returnedTuple) elog(DEBUG, "InstrStopNode without start"); return; } - + gettimeofday(&endtime, NULL); - - instr->counter.tv_sec += endtime.tv_sec - instr->starttime.tv_sec; + + instr->counter.tv_sec += endtime.tv_sec - instr->starttime.tv_sec; instr->counter.tv_usec += endtime.tv_usec - instr->starttime.tv_usec; /* Normalize after each add to avoid overflow/underflow of tv_usec */ @@ -90,10 +90,10 @@ InstrStopNode(Instrumentation *instr, bool returnedTuple) } /* Finish a run cycle for a plan node */ -void +void InstrEndLoop(Instrumentation *instr) { - double totaltime; + double totaltime; if (!instr) return; @@ -104,10 +104,10 @@ InstrEndLoop(Instrumentation *instr) /* Accumulate statistics */ totaltime = (double) instr->counter.tv_sec + - (double) instr->counter.tv_usec / 1000000.0; + (double) instr->counter.tv_usec / 1000000.0; instr->startup += instr->firsttuple; - instr->total += totaltime; + instr->total += totaltime; instr->ntuples += instr->tuplecount; instr->nloops += 1; diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c index 73f2b56cf3..90369c5a7a 100644 --- a/src/backend/executor/nodeAgg.c +++ b/src/backend/executor/nodeAgg.c @@ -46,7 +46,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeAgg.c,v 1.77 2001/03/22 06:16:12 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeAgg.c,v 1.78 2001/10/25 05:49:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -73,7 +73,6 @@ */ typedef struct AggStatePerAggData { - /* * These values are set up during ExecInitAgg() and do not change * thereafter: @@ -178,7 +177,6 @@ initialize_aggregate(AggStatePerAgg peraggstate) */ if (aggref->aggdistinct) { - /* * In case of rescan, maybe there could be an uncompleted sort * operation? Clean it up if so. @@ -228,7 +226,6 @@ advance_transition_function(AggStatePerAgg peraggstate, { if (isNull) { - /* * For a strict transfn, nothing happens at a NULL input * tuple; we just keep the prior transValue. However, if the @@ -243,7 +240,6 @@ advance_transition_function(AggStatePerAgg peraggstate, } if (peraggstate->noTransValue) { - /* * transValue has not been initialized. This is the first * non-NULL input value. We use it as the initial value for @@ -264,7 +260,6 @@ advance_transition_function(AggStatePerAgg peraggstate, } if (peraggstate->transValueIsNull) { - /* * Don't call a strict function with NULL inputs. Note it is * possible to get here despite the above tests, if the @@ -333,7 +328,6 @@ process_sorted_aggregate(AggState *aggstate, while (tuplesort_getdatum(peraggstate->sortstate, true, &newVal, &isNull)) { - /* * DISTINCT always suppresses nulls, per SQL spec, regardless of * the transition function's strictness. @@ -398,7 +392,6 @@ static void finalize_aggregate(AggStatePerAgg peraggstate, Datum *resultVal, bool *resultIsNull) { - /* * Apply the agg's finalfn if one is provided, else return transValue. */ @@ -757,7 +750,6 @@ ExecInitAgg(Agg *node, EState *estate, Plan *parent) aggstate->numaggs = numaggs = length(aggstate->aggs); if (numaggs <= 0) { - /* * This used to be treated as an error, but we can't do that * anymore because constant-expression simplification could @@ -897,7 +889,6 @@ ExecInitAgg(Agg *node, EState *estate, Plan *parent) */ if (peraggstate->transfn.fn_strict && peraggstate->initValueIsNull) { - /* * Note: use the type from the input expression here, not * aggform->aggbasetype, because the latter might be 0. @@ -913,7 +904,6 @@ ExecInitAgg(Agg *node, EState *estate, Plan *parent) if (aggref->aggdistinct) { - /* * Note: use the type from the input expression here, not * aggform->aggbasetype, because the latter might be 0. @@ -947,8 +937,8 @@ int ExecCountSlotsAgg(Agg *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - AGG_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + AGG_NSLOTS; } void diff --git a/src/backend/executor/nodeAppend.c b/src/backend/executor/nodeAppend.c index f8bdbed6cc..41b05118e0 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.42 2001/05/15 00:33:36 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeAppend.c,v 1.43 2001/10/25 05:49:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -90,7 +90,6 @@ exec_append_initialize_next(Append *node) if (whichplan < appendstate->as_firstplan) { - /* * if scanning in reverse, we start at the last scan in the list * and then proceed back to the first.. in any case we inform @@ -102,7 +101,6 @@ exec_append_initialize_next(Append *node) } else if (whichplan > appendstate->as_lastplan) { - /* * as above, end the scan if we go beyond the last scan in our * list.. @@ -112,7 +110,6 @@ exec_append_initialize_next(Append *node) } else { - /* * initialize the scan * @@ -182,12 +179,13 @@ ExecInitAppend(Append *node, EState *estate, Plan *parent) node->appendstate = appendstate; /* - * Do we want to scan just one subplan? (Special case for EvalPlanQual) - * XXX pretty dirty way of determining that this case applies ... + * Do we want to scan just one subplan? (Special case for + * EvalPlanQual) XXX pretty dirty way of determining that this case + * applies ... */ if (node->isTarget && estate->es_evTuple != NULL) { - int tplan; + int tplan; tplan = estate->es_result_relation_info - estate->es_result_relations; Assert(tplan >= 0 && tplan < nplans); @@ -301,7 +299,6 @@ ExecProcAppend(Append *node) if (!TupIsNull(result)) { - /* * if the subplan gave us something then place a copy of whatever * we get into our result slot and return it. @@ -313,7 +310,6 @@ ExecProcAppend(Append *node) } else { - /* * .. go on to the "next" subplan in the appropriate direction and * try processing again (recursively) @@ -385,15 +381,17 @@ ExecReScanAppend(Append *node, ExprContext *exprCtxt, Plan *parent) Plan *subnode; subnode = (Plan *) nth(i, node->appendplans); + /* * ExecReScan doesn't know about my subplans, so I have to do * changed-parameter signaling myself. */ if (node->plan.chgParam != NULL) SetChangedParamList(subnode, node->plan.chgParam); + /* - * 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 (subnode->chgParam == NULL) { diff --git a/src/backend/executor/nodeGroup.c b/src/backend/executor/nodeGroup.c index 6dda57f6e9..e3aea3b789 100644 --- a/src/backend/executor/nodeGroup.c +++ b/src/backend/executor/nodeGroup.c @@ -15,7 +15,7 @@ * locate group boundaries. * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeGroup.c,v 1.43 2001/03/22 06:16:12 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeGroup.c,v 1.44 2001/10/25 05:49:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -122,7 +122,6 @@ ExecGroupEveryTuple(Group *node) } else { - /* * Compare with first tuple and see if this tuple is of the * same group. @@ -133,7 +132,6 @@ ExecGroupEveryTuple(Group *node) grpstate->eqfunctions, econtext->ecxt_per_tuple_memory)) { - /* * No; save the tuple to return it next time, and return * NULL @@ -478,7 +476,7 @@ execTuplesMatch(HeapTuple tuple1, * Look up the equality functions needed for execTuplesMatch. * The result is a palloc'd array. */ -FmgrInfo * +FmgrInfo * execTuplesMatchPrepare(TupleDesc tupdesc, int numCols, AttrNumber *matchColIdx) diff --git a/src/backend/executor/nodeHash.c b/src/backend/executor/nodeHash.c index f387e5a759..bf9bf6eeb0 100644 --- a/src/backend/executor/nodeHash.c +++ b/src/backend/executor/nodeHash.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * - * $Id: nodeHash.c,v 1.59 2001/08/13 19:50:11 tgl Exp $ + * $Id: nodeHash.c,v 1.60 2001/10/25 05:49:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -69,7 +69,6 @@ ExecHash(Hash *node) if (nbatch > 0) { - /* * Open temp files for inner batches, if needed. Note that file * buffers are palloc'd in regular executor context. @@ -165,8 +164,8 @@ int ExecCountSlotsHash(Hash *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - HASH_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + HASH_NSLOTS; } /* --------------------------------------------------------------- @@ -279,7 +278,6 @@ ExecHashTableCreate(Hash *node) if (nbatch > 0) { - /* * allocate and initialize the file arrays in hashCxt */ @@ -480,7 +478,6 @@ ExecHashTableInsert(HashJoinTable hashtable, */ if (bucketno < hashtable->nbuckets) { - /* * put the tuple in hash table */ @@ -506,7 +503,6 @@ ExecHashTableInsert(HashJoinTable hashtable, } else { - /* * put the tuple into a tmp file for other batches */ @@ -536,8 +532,8 @@ ExecHashGetBucket(HashJoinTable hashtable, MemoryContext oldContext; /* - * We reset the eval context each time to reclaim any memory leaked - * in the hashkey expression or hashFunc itself. + * We reset the eval context each time to reclaim any memory leaked in + * the hashkey expression or hashFunc itself. */ ResetExprContext(econtext); @@ -657,15 +653,15 @@ hashFunc(Datum key, int len, bool byVal) else { /* - * If this is a variable length type, then 'key' points to a "struct - * varlena" and len == -1. NOTE: VARSIZE returns the "real" data - * length plus the sizeof the "vl_len" attribute of varlena (the - * length information). 'key' points to the beginning of the varlena - * struct, so we have to use "VARDATA" to find the beginning of - * the "real" data. Also, we have to be careful to detoast the - * datum if it's toasted. (We don't worry about freeing the detoasted - * copy; that happens for free when the per-tuple memory context - * is reset in ExecHashGetBucket.) + * If this is a variable length type, then 'key' points to a + * "struct varlena" and len == -1. NOTE: VARSIZE returns the + * "real" data length plus the sizeof the "vl_len" attribute of + * varlena (the length information). 'key' points to the beginning + * of the varlena struct, so we have to use "VARDATA" to find the + * beginning of the "real" data. Also, we have to be careful to + * detoast the datum if it's toasted. (We don't worry about + * freeing the detoasted copy; that happens for free when the + * per-tuple memory context is reset in ExecHashGetBucket.) */ unsigned char *k; @@ -737,7 +733,6 @@ ExecHashTableReset(HashJoinTable hashtable, long ntuples) void ExecReScanHash(Hash *node, ExprContext *exprCtxt, Plan *parent) { - /* * if chgParam of subnode is not null then plan will be re-scanned by * first ExecProcNode. diff --git a/src/backend/executor/nodeHashjoin.c b/src/backend/executor/nodeHashjoin.c index 12f6d58443..58e97b8adb 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.38 2001/03/22 06:16:13 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeHashjoin.c,v 1.39 2001/10/25 05:49:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -148,7 +148,6 @@ ExecHashJoin(HashJoin *node) for (;;) { - /* * If we don't have an outer tuple, get the next one */ @@ -159,7 +158,6 @@ ExecHashJoin(HashJoin *node) hjstate); if (TupIsNull(outerTupleSlot)) { - /* * when the last batch runs out, clean up and exit */ @@ -193,7 +191,6 @@ ExecHashJoin(HashJoin *node) if (batch > 0) { - /* * Need to postpone this outer tuple to a later batch. * Save it in the corresponding outer-batch file. @@ -270,7 +267,6 @@ ExecHashJoin(HashJoin *node) if (!hjstate->hj_MatchedOuter && node->join.jointype == JOIN_LEFT) { - /* * We are doing an outer join and there were no join matches * for this outer tuple. Generate a fake join tuple with @@ -281,7 +277,6 @@ ExecHashJoin(HashJoin *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification was satisfied so we project and return * the slot containing the result tuple using @@ -411,8 +406,8 @@ int ExecCountSlotsHashJoin(HashJoin *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - HASHJOIN_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + HASHJOIN_NSLOTS; } /* ---------------------------------------------------------------- @@ -565,7 +560,6 @@ ExecHashJoinNewBatch(HashJoinState *hjstate) if (newbatch > 1) { - /* * We no longer need the previous outer batch file; close it right * away to free disk space. diff --git a/src/backend/executor/nodeIndexscan.c b/src/backend/executor/nodeIndexscan.c index ec26ed05cc..3c5ebc4c8b 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.62 2001/07/15 22:48:17 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeIndexscan.c,v 1.63 2001/10/25 05:49:28 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -222,7 +222,7 @@ IndexNext(IndexScan *node) qual = lnext(qual); } if (!prev_matches) - return slot;/* OK to return tuple */ + return slot; /* OK to return tuple */ /* Duplicate tuple, so drop it and loop back for another */ ExecClearTuple(slot); } @@ -337,7 +337,6 @@ ExecIndexReScan(IndexScan *node, ExprContext *exprCtxt, Plan *parent) if (econtext) { - /* * If we are being passed an outer tuple, save it for runtime key * calc @@ -377,7 +376,6 @@ ExecIndexReScan(IndexScan *node, ExprContext *exprCtxt, Plan *parent) run_keys = runtimeKeyInfo[i]; for (j = 0; j < n_keys; j++) { - /* * If we have a run-time key, then extract the run-time * expression and evaluate it with respect to the current @@ -703,10 +701,10 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) Expr *clause; /* one clause of index qual */ Oper *op; /* operator used in clause */ Node *leftop; /* expr on lhs of operator */ - Node *rightop;/* expr on rhs ... */ + Node *rightop; /* expr on rhs ... */ bits16 flags = 0; - int scanvar;/* which var identifies varattno */ + int scanvar; /* which var identifies varattno */ AttrNumber varattno = 0; /* att number used in scan */ Oid opid; /* operator id used in scan */ Datum scanvalue = 0; /* value used in scan (if const) */ @@ -772,7 +770,6 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) if (IsA(leftop, Var) &&var_is_rel((Var *) leftop)) { - /* * if the leftop is a "rel-var", then it means that it is * a var node which tells us which attribute to use for @@ -783,7 +780,6 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) } else if (IsA(leftop, Const)) { - /* * if the leftop is a const node then it means it * identifies the value to place in our scan key. @@ -820,7 +816,6 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) } else { - /* * otherwise, the leftop contains an expression evaluable * at runtime to figure out the value to place in our scan @@ -842,7 +837,6 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) if (IsA(rightop, Var) &&var_is_rel((Var *) rightop)) { - /* * here we make sure only one op identifies the * scan-attribute... @@ -861,7 +855,6 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) } else if (IsA(rightop, Const)) { - /* * if the rightop is a const node then it means it * identifies the value to place in our scan key. @@ -898,7 +891,6 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) } else { - /* * otherwise, the rightop contains an expression evaluable * at runtime to figure out the value to place in our scan @@ -1023,7 +1015,7 @@ ExecInitIndexScan(IndexScan *node, EState *estate, Plan *parent) ExecOpenScanR(indexOid, /* relation */ numScanKeys[i], /* nkeys */ scanKeys[i], /* scan key */ - true, /* is index */ + true, /* is index */ direction, /* scan direction */ estate->es_snapshot, &(relationDescs[i]), /* return: rel desc */ @@ -1045,5 +1037,5 @@ int ExecCountSlotsIndexScan(IndexScan *node) { return ExecCountSlotsNode(outerPlan((Plan *) node)) + - ExecCountSlotsNode(innerPlan((Plan *) node)) + INDEXSCAN_NSLOTS; + ExecCountSlotsNode(innerPlan((Plan *) node)) + INDEXSCAN_NSLOTS; } diff --git a/src/backend/executor/nodeLimit.c b/src/backend/executor/nodeLimit.c index da0e669776..1ce376418d 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.7 2001/08/06 18:05:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeLimit.c,v 1.8 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -66,7 +66,6 @@ ExecLimit(Limit *node) */ for (;;) { - /* * If we have reached the subplan EOF or the limit, just quit. * @@ -76,11 +75,11 @@ ExecLimit(Limit *node) * here is for position > netlimit not position >= netlimit. * * Similarly, when scanning backwards, we must re-fetch the last - * tuple in the offset region before we can return NULL. - * Otherwise we won't be correctly aligned to start going forward - * again. So, although you might think we can quit when position - * equals offset + 1, we have to fetch a subplan tuple first, and - * then exit when position = offset. + * tuple in the offset region before we can return NULL. Otherwise + * we won't be correctly aligned to start going forward again. + * So, although you might think we can quit when position equals + * offset + 1, we have to fetch a subplan tuple first, and then + * exit when position = offset. */ if (ScanDirectionIsForward(direction)) { @@ -101,7 +100,6 @@ ExecLimit(Limit *node) slot = ExecProcNode(outerPlan, (Plan *) node); if (TupIsNull(slot)) { - /* * We are at start or end of the subplan. Update local state * appropriately, but always return NULL. @@ -269,8 +267,8 @@ int ExecCountSlotsLimit(Limit *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - LIMIT_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + LIMIT_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/nodeMaterial.c b/src/backend/executor/nodeMaterial.c index c4ec5c9a38..8578f02074 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.36 2001/05/27 20:42:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeMaterial.c,v 1.37 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -185,8 +185,8 @@ int ExecCountSlotsMaterial(Material *node) { return ExecCountSlotsNode(outerPlan((Plan *) node)) + - ExecCountSlotsNode(innerPlan((Plan *) node)) + - MATERIAL_NSLOTS; + ExecCountSlotsNode(innerPlan((Plan *) node)) + + MATERIAL_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/nodeMergejoin.c b/src/backend/executor/nodeMergejoin.c index 9733bc47d5..8ac71b0cc9 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.45 2001/03/23 04:49:53 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeMergejoin.c,v 1.46 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -124,7 +124,6 @@ MJFormSkipQual(List *qualList, char *replaceopname) foreach(qualcdr, qualCopy) { - /* * first get the current (op .. ..) list */ @@ -321,7 +320,6 @@ ExecMergeTupleDump(MergeJoinState *mergestate) printf("******** \n"); } - #endif /* ---------------------------------------------------------------- @@ -431,7 +429,7 @@ ExecMergeJoin(MergeJoin *node) default: elog(ERROR, "ExecMergeJoin: unsupported join type %d", (int) node->join.jointype); - doFillOuter = false;/* keep compiler quiet */ + doFillOuter = false; /* keep compiler quiet */ doFillInner = false; break; } @@ -476,7 +474,6 @@ ExecMergeJoin(MergeJoin *node) */ for (;;) { - /* * get the current state of the join and do things accordingly. * Note: The join states are highlighted with 32-* comments for @@ -486,7 +483,6 @@ ExecMergeJoin(MergeJoin *node) switch (mergestate->mj_JoinState) { - /* * EXEC_MJ_INITIALIZE means that this is the first time * ExecMergeJoin() has been called and so we have to fetch @@ -505,7 +501,6 @@ ExecMergeJoin(MergeJoin *node) MJ_printf("ExecMergeJoin: outer subplan is empty\n"); if (doFillInner) { - /* * Need to emit right-join tuples for remaining * inner tuples. We set MatchedInner = true to @@ -526,7 +521,6 @@ ExecMergeJoin(MergeJoin *node) MJ_printf("ExecMergeJoin: inner subplan is empty\n"); if (doFillOuter) { - /* * Need to emit left-join tuples for all outer * tuples, including the one we just fetched. We @@ -632,7 +626,6 @@ ExecMergeJoin(MergeJoin *node) if (qualResult) { - /* * qualification succeeded. now form the desired * projection tuple and return the slot containing @@ -669,7 +662,6 @@ ExecMergeJoin(MergeJoin *node) if (doFillInner && !mergestate->mj_MatchedInner) { - /* * Generate a fake join tuple with nulls for the outer * tuple, and return it if it passes the non-join @@ -686,7 +678,6 @@ ExecMergeJoin(MergeJoin *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification succeeded. now form the desired * projection tuple and return the slot containing @@ -747,7 +738,6 @@ ExecMergeJoin(MergeJoin *node) if (doFillOuter && !mergestate->mj_MatchedOuter) { - /* * Generate a fake join tuple with nulls for the inner * tuple, and return it if it passes the non-join @@ -764,7 +754,6 @@ ExecMergeJoin(MergeJoin *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification succeeded. now form the desired * projection tuple and return the slot containing @@ -805,7 +794,6 @@ ExecMergeJoin(MergeJoin *node) innerTupleSlot = mergestate->mj_InnerTupleSlot; if (doFillInner && !TupIsNull(innerTupleSlot)) { - /* * Need to emit right-join tuples for remaining * inner tuples. @@ -873,7 +861,6 @@ ExecMergeJoin(MergeJoin *node) if (qualResult) { - /* * the merge clause matched so now we restore the * inner scan position to the first mark, and loop @@ -915,7 +902,6 @@ ExecMergeJoin(MergeJoin *node) { if (doFillOuter) { - /* * Need to emit left-join tuples for remaining * outer tuples. @@ -1036,7 +1022,6 @@ ExecMergeJoin(MergeJoin *node) if (doFillOuter && !mergestate->mj_MatchedOuter) { - /* * Generate a fake join tuple with nulls for the inner * tuple, and return it if it passes the non-join @@ -1053,7 +1038,6 @@ ExecMergeJoin(MergeJoin *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification succeeded. now form the desired * projection tuple and return the slot containing @@ -1094,7 +1078,6 @@ ExecMergeJoin(MergeJoin *node) innerTupleSlot = mergestate->mj_InnerTupleSlot; if (doFillInner && !TupIsNull(innerTupleSlot)) { - /* * Need to emit right-join tuples for remaining * inner tuples. @@ -1216,7 +1199,6 @@ ExecMergeJoin(MergeJoin *node) if (doFillInner && !mergestate->mj_MatchedInner) { - /* * Generate a fake join tuple with nulls for the outer * tuple, and return it if it passes the non-join @@ -1233,7 +1215,6 @@ ExecMergeJoin(MergeJoin *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification succeeded. now form the desired * projection tuple and return the slot containing @@ -1274,7 +1255,6 @@ ExecMergeJoin(MergeJoin *node) outerTupleSlot = mergestate->mj_OuterTupleSlot; if (doFillOuter && !TupIsNull(outerTupleSlot)) { - /* * Need to emit left-join tuples for remaining * outer tuples. @@ -1304,7 +1284,6 @@ ExecMergeJoin(MergeJoin *node) if (!mergestate->mj_MatchedInner) { - /* * Generate a fake join tuple with nulls for the outer * tuple, and return it if it passes the non-join @@ -1321,7 +1300,6 @@ ExecMergeJoin(MergeJoin *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification succeeded. now form the desired * projection tuple and return the slot containing @@ -1373,7 +1351,6 @@ ExecMergeJoin(MergeJoin *node) if (!mergestate->mj_MatchedOuter) { - /* * Generate a fake join tuple with nulls for the inner * tuple, and return it if it passes the non-join @@ -1390,7 +1367,6 @@ ExecMergeJoin(MergeJoin *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification succeeded. now form the desired * projection tuple and return the slot containing @@ -1579,8 +1555,8 @@ int ExecCountSlotsMergeJoin(MergeJoin *node) { return ExecCountSlotsNode(outerPlan((Plan *) node)) + - ExecCountSlotsNode(innerPlan((Plan *) node)) + - MERGEJOIN_NSLOTS; + ExecCountSlotsNode(innerPlan((Plan *) node)) + + MERGEJOIN_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index b695903887..e99b02fce4 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.24 2001/03/22 06:16:13 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeNestloop.c,v 1.25 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -118,7 +118,6 @@ ExecNestLoop(NestLoop *node) for (;;) { - /* * If we don't have an outer tuple, get the next one and reset the * inner scan. @@ -174,7 +173,6 @@ ExecNestLoop(NestLoop *node) if (!nlstate->nl_MatchedOuter && node->join.jointype == JOIN_LEFT) { - /* * We are doing an outer join and there were no join * matches for this outer tuple. Generate a fake join @@ -187,7 +185,6 @@ ExecNestLoop(NestLoop *node) if (ExecQual(otherqual, econtext, false)) { - /* * qualification was satisfied so we project and * return the slot containing the result tuple using @@ -231,7 +228,6 @@ ExecNestLoop(NestLoop *node) if (otherqual == NIL || ExecQual(otherqual, econtext, false)) { - /* * qualification was satisfied so we project and return * the slot containing the result tuple using @@ -346,8 +342,8 @@ int ExecCountSlotsNestLoop(NestLoop *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - NESTLOOP_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + NESTLOOP_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/nodeResult.c b/src/backend/executor/nodeResult.c index f9f325f637..5e59cb0c12 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.19 2001/03/22 06:16:13 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeResult.c,v 1.20 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -125,7 +125,6 @@ ExecResult(Result *node) if (outerPlan != NULL) { - /* * retrieve tuples from the outer plan until there are no * more. @@ -146,7 +145,6 @@ ExecResult(Result *node) } else { - /* * if we don't have an outer plan, then we are just generating * the results from a constant target list. Do it only once. diff --git a/src/backend/executor/nodeSeqscan.c b/src/backend/executor/nodeSeqscan.c index 48beffd792..1767379d67 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.31 2001/07/15 22:48:18 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSeqscan.c,v 1.32 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -127,7 +127,6 @@ SeqNext(SeqScan *node) TupleTableSlot * ExecSeqScan(SeqScan *node) { - /* * use SeqNext as access method */ @@ -246,8 +245,8 @@ int ExecCountSlotsSeqScan(SeqScan *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - SEQSCAN_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + SEQSCAN_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/nodeSetOp.c b/src/backend/executor/nodeSetOp.c index 3072fe5f96..cd5d5b9122 100644 --- a/src/backend/executor/nodeSetOp.c +++ b/src/backend/executor/nodeSetOp.c @@ -21,7 +21,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeSetOp.c,v 1.4 2001/03/22 06:16:13 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSetOp.c,v 1.5 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -100,7 +100,6 @@ ExecSetOp(SetOp *node) if (TupIsNull(resultTupleSlot)) { - /* * First of group: save a copy in result slot, and reset * duplicate-counters for new group. @@ -118,7 +117,6 @@ ExecSetOp(SetOp *node) } else if (setopstate->subplan_done) { - /* * Reached end of input, so finish processing final group */ @@ -126,7 +124,6 @@ ExecSetOp(SetOp *node) } else { - /* * Else test if the new tuple and the previously saved tuple * match. @@ -144,7 +141,6 @@ ExecSetOp(SetOp *node) if (endOfGroup) { - /* * We've reached the end of the group containing resultTuple. * Decide how many copies (if any) to emit. This logic is @@ -187,7 +183,6 @@ ExecSetOp(SetOp *node) } else { - /* * Current tuple is member of same group as resultTuple. Count * it in the appropriate counter. @@ -294,8 +289,8 @@ int ExecCountSlotsSetOp(SetOp *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - SETOP_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + SETOP_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/nodeSort.c b/src/backend/executor/nodeSort.c index a83a841142..82bb4cc3c9 100644 --- a/src/backend/executor/nodeSort.c +++ b/src/backend/executor/nodeSort.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeSort.c,v 1.34 2001/05/27 20:42:19 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSort.c,v 1.35 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -275,8 +275,8 @@ int ExecCountSlotsSort(Sort *node) { return ExecCountSlotsNode(outerPlan((Plan *) node)) + - ExecCountSlotsNode(innerPlan((Plan *) node)) + - SORT_NSLOTS; + ExecCountSlotsNode(innerPlan((Plan *) node)) + + SORT_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/nodeSubplan.c b/src/backend/executor/nodeSubplan.c index 6719df94e7..3aa30d25a3 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.31 2001/09/18 01:59:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSubplan.c,v 1.32 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -257,7 +257,6 @@ ExecSubPlan(SubPlan *node, List *pvar, ExprContext *econtext, bool *isNull) if (!found) { - /* * deal with empty subplan result. result/isNull were previously * initialized correctly for all sublink types except EXPR and diff --git a/src/backend/executor/nodeSubqueryscan.c b/src/backend/executor/nodeSubqueryscan.c index 8c178ad0aa..edd4640ba4 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.10 2001/09/18 01:59:06 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeSubqueryscan.c,v 1.11 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -63,8 +63,8 @@ SubqueryNext(SubqueryScan *node) direction = estate->es_direction; /* - * We need not support EvalPlanQual here, since we are not scanning - * a real relation. + * We need not support EvalPlanQual here, since we are not scanning a + * real relation. */ /* @@ -92,7 +92,6 @@ SubqueryNext(SubqueryScan *node) TupleTableSlot * ExecSubqueryScan(SubqueryScan *node) { - /* * use SubqueryNext as access method */ @@ -181,8 +180,8 @@ ExecCountSlotsSubqueryScan(SubqueryScan *node) * The subplan has its own tuple table and must not be counted here! */ return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - SUBQUERYSCAN_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + SUBQUERYSCAN_NSLOTS; } /* ---------------------------------------------------------------- @@ -251,6 +250,7 @@ ExecSubqueryReScan(SubqueryScan *node, ExprContext *exprCtxt, Plan *parent) */ if (node->scan.plan.chgParam != NULL) SetChangedParamList(node->subplan, node->scan.plan.chgParam); + /* * if chgParam of subnode is not null then plan will be re-scanned by * first ExecProcNode. diff --git a/src/backend/executor/nodeTidscan.c b/src/backend/executor/nodeTidscan.c index 404ed6a215..380632a78b 100644 --- a/src/backend/executor/nodeTidscan.c +++ b/src/backend/executor/nodeTidscan.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/executor/nodeTidscan.c,v 1.19 2001/09/29 07:57:06 inoue Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeTidscan.c,v 1.20 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -29,7 +29,7 @@ #include "access/heapam.h" #include "parser/parsetree.h" -static int TidListCreate(List *, ExprContext *, ItemPointerData []); +static int TidListCreate(List *, ExprContext *, ItemPointerData[]); static TupleTableSlot *TidNext(TidScan *node); static int @@ -80,7 +80,7 @@ TidNext(TidScan *node) bool bBackward; int tidNumber; - ItemPointerData* tidList; + ItemPointerData *tidList; /* * extract necessary information from tid scan node @@ -233,7 +233,6 @@ TidNext(TidScan *node) TupleTableSlot * ExecTidScan(TidScan *node) { - /* * use TidNext as access method */ @@ -249,7 +248,7 @@ ExecTidReScan(TidScan *node, ExprContext *exprCtxt, Plan *parent) { EState *estate; TidScanState *tidstate; - ItemPointerData* tidList; + ItemPointerData *tidList; tidstate = node->tidstate; estate = node->scan.plan.state; @@ -357,7 +356,6 @@ ExecTidRestrPos(TidScan *node) tidstate = node->tidstate; tidstate->tss_TidPtr = tidstate->tss_MarkTidPtr; } - #endif /* ---------------------------------------------------------------- @@ -376,7 +374,7 @@ ExecInitTidScan(TidScan *node, EState *estate, Plan *parent) { TidScanState *tidstate; CommonScanState *scanstate; - ItemPointerData* tidList; + ItemPointerData *tidList; int numTids; int tidPtr; List *rangeTable; @@ -482,5 +480,5 @@ int ExecCountSlotsTidScan(TidScan *node) { return ExecCountSlotsNode(outerPlan((Plan *) node)) + - ExecCountSlotsNode(innerPlan((Plan *) node)) + TIDSCAN_NSLOTS; + ExecCountSlotsNode(innerPlan((Plan *) node)) + TIDSCAN_NSLOTS; } diff --git a/src/backend/executor/nodeUnique.c b/src/backend/executor/nodeUnique.c index 2a139d8e1c..975dd84fe8 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.32 2001/03/22 06:16:13 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/nodeUnique.c,v 1.33 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -61,7 +61,6 @@ ExecUnique(Unique *node) */ for (;;) { - /* * fetch a tuple from the outer subplan */ @@ -186,8 +185,8 @@ int ExecCountSlotsUnique(Unique *node) { return ExecCountSlotsNode(outerPlan(node)) + - ExecCountSlotsNode(innerPlan(node)) + - UNIQUE_NSLOTS; + ExecCountSlotsNode(innerPlan(node)) + + UNIQUE_NSLOTS; } /* ---------------------------------------------------------------- diff --git a/src/backend/executor/spi.c b/src/backend/executor/spi.c index 73457491d6..e4c2dac40d 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.59 2001/10/23 17:38:25 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/executor/spi.c,v 1.60 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -37,7 +37,7 @@ static int _SPI_execute_plan(_SPI_plan *plan, Datum *Values, char *Nulls, int tcount); static void _SPI_cursor_operation(Portal portal, bool forward, int count, - CommandDest dest); + CommandDest dest); static _SPI_plan *_SPI_copy_plan(_SPI_plan *plan, int location); @@ -51,7 +51,6 @@ static bool _SPI_checktuples(void); extern int ShowExecutorStats; extern void ResetUsage(void); extern void ShowUsage(void); - #endif /* =================== interface functions =================== */ @@ -298,7 +297,7 @@ SPI_saveplan(void *plan) int SPI_freeplan(void *plan) { - _SPI_plan *spiplan = (_SPI_plan *)plan; + _SPI_plan *spiplan = (_SPI_plan *) plan; if (plan == NULL) return SPI_ERROR_ARGUMENT; @@ -444,7 +443,7 @@ SPI_fnumber(TupleDesc tupdesc, char *fname) return res + 1; } - sysatt = SystemAttributeByName(fname, true /* "oid" will be accepted */); + sysatt = SystemAttributeByName(fname, true /* "oid" will be accepted */ ); if (sysatt != NULL) return sysatt->attnum; @@ -673,26 +672,26 @@ SPI_freetuptable(SPITupleTable *tuptable) Portal SPI_cursor_open(char *name, void *plan, Datum *Values, char *Nulls) { - static int unnamed_portal_count = 0; - - _SPI_plan *spiplan = (_SPI_plan *)plan; - List *qtlist = spiplan->qtlist; - List *ptlist = spiplan->ptlist; - Query *queryTree; - Plan *planTree; - QueryDesc *queryDesc; - EState *eState; - TupleDesc attinfo; - MemoryContext oldcontext; - Portal portal; - char portalname[64]; - int k; + static int unnamed_portal_count = 0; + + _SPI_plan *spiplan = (_SPI_plan *) plan; + List *qtlist = spiplan->qtlist; + List *ptlist = spiplan->ptlist; + Query *queryTree; + Plan *planTree; + QueryDesc *queryDesc; + EState *eState; + TupleDesc attinfo; + MemoryContext oldcontext; + Portal portal; + char portalname[64]; + int k; /* Ensure that the plan contains only one regular SELECT query */ if (length(ptlist) != 1) elog(ERROR, "cannot open multi-query plan as cursor"); - queryTree = (Query *)lfirst(qtlist); - planTree = (Plan *)lfirst(ptlist); + queryTree = (Query *) lfirst(qtlist); + planTree = (Plan *) lfirst(ptlist); if (queryTree->commandType != CMD_SELECT) elog(ERROR, "plan in SPI_cursor_open() is not a SELECT"); @@ -712,7 +711,7 @@ SPI_cursor_open(char *name, void *plan, Datum *Values, char *Nulls) { for (;;) { - unnamed_portal_count++; + unnamed_portal_count++; if (unnamed_portal_count < 0) unnamed_portal_count = 0; sprintf(portalname, "<unnamed cursor %d>", unnamed_portal_count); @@ -735,30 +734,31 @@ SPI_cursor_open(char *name, void *plan, Datum *Values, char *Nulls) /* Switch to portals memory and copy the parsetree and plan to there */ oldcontext = MemoryContextSwitchTo(PortalGetHeapMemory(portal)); - queryTree = copyObject(queryTree); - planTree = copyObject(planTree); + queryTree = copyObject(queryTree); + planTree = copyObject(planTree); /* Modify the parsetree to be a cursor */ queryTree->isPortal = true; - queryTree->into = pstrdup(name); + queryTree->into = pstrdup(name); queryTree->isBinary = false; - + /* Create the QueryDesc object and the executor state */ queryDesc = CreateQueryDesc(queryTree, planTree, SPI); - eState = CreateExecutorState(); + eState = CreateExecutorState(); /* If the plan has parameters, put them into the executor state */ if (spiplan->nargs > 0) { - ParamListInfo paramLI = (ParamListInfo) palloc((spiplan->nargs + 1) * - sizeof(ParamListInfoData)); + ParamListInfo paramLI = (ParamListInfo) palloc((spiplan->nargs + 1) * + sizeof(ParamListInfoData)); + eState->es_param_list_info = paramLI; for (k = 0; k < spiplan->nargs; paramLI++, k++) { - paramLI->kind = PARAM_NUM; - paramLI->id = k + 1; - paramLI->isnull = (Nulls && Nulls[k] == 'n'); - paramLI->value = Values[k]; + paramLI->kind = PARAM_NUM; + paramLI->id = k + 1; + paramLI->isnull = (Nulls && Nulls[k] == 'n'); + paramLI->value = Values[k]; } paramLI->kind = PARAM_INVALID; } @@ -872,7 +872,7 @@ spi_printtup(HeapTuple tuple, TupleDesc tupdesc, DestReceiver *self) tuptable->vals = (HeapTuple *) palloc(tuptable->alloced * sizeof(HeapTuple)); tuptable->tupdesc = CreateTupleDescCopy(tupdesc); } - else + else { MemoryContextSwitchTo(tuptable->tuptabcxt); @@ -881,7 +881,7 @@ spi_printtup(HeapTuple tuple, TupleDesc tupdesc, DestReceiver *self) tuptable->free = 256; tuptable->alloced += tuptable->free; tuptable->vals = (HeapTuple *) repalloc(tuptable->vals, - tuptable->alloced * sizeof(HeapTuple)); + tuptable->alloced * sizeof(HeapTuple)); } } @@ -1171,12 +1171,12 @@ _SPI_pquery(QueryDesc *queryDesc, EState *state, int tcount) */ static void _SPI_cursor_operation(Portal portal, bool forward, int count, - CommandDest dest) + CommandDest dest) { - QueryDesc *querydesc; - EState *estate; - MemoryContext oldcontext; - CommandDest olddest; + QueryDesc *querydesc; + EState *estate; + MemoryContext oldcontext; + CommandDest olddest; /* Check that the portal is valid */ if (!PortalIsValid(portal)) @@ -1193,8 +1193,8 @@ _SPI_cursor_operation(Portal portal, bool forward, int count, /* Switch to the portals memory context */ oldcontext = MemoryContextSwitchTo(PortalGetHeapMemory(portal)); - querydesc = PortalGetQueryDesc(portal); - estate = PortalGetState(portal); + querydesc = PortalGetQueryDesc(portal); + estate = PortalGetState(portal); /* Save the queries command destination and set it to SPI (for fetch) */ /* or None (for move) */ @@ -1206,7 +1206,7 @@ _SPI_cursor_operation(Portal portal, bool forward, int count, { if (!portal->atEnd) { - ExecutorRun(querydesc, estate, EXEC_FOR, (long)count); + ExecutorRun(querydesc, estate, EXEC_FOR, (long) count); _SPI_current->processed = estate->es_processed; if (estate->es_processed > 0) portal->atStart = false; @@ -1237,7 +1237,7 @@ _SPI_cursor_operation(Portal portal, bool forward, int count, /* Put the result into place for access by caller */ SPI_processed = _SPI_current->processed; - SPI_tuptable = _SPI_current->tuptable; + SPI_tuptable = _SPI_current->tuptable; /* Pop the SPI stack */ _SPI_end_call(true); @@ -1278,7 +1278,6 @@ _SPI_begin_call(bool execmem) static int _SPI_end_call(bool procmem) { - /* * We' returning to procedure where _SPI_curid == _SPI_connected - 1 */ diff --git a/src/backend/lib/bit.c b/src/backend/lib/bit.c index 57da3522c4..41c799fb5a 100644 --- a/src/backend/lib/bit.c +++ b/src/backend/lib/bit.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/lib/Attic/bit.c,v 1.13 2001/03/22 03:59:29 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/lib/Attic/bit.c,v 1.14 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -22,14 +22,14 @@ void BitArraySetBit(BitArray bitArray, BitIndex bitIndex) { bitArray[bitIndex / BITS_PER_BYTE] |= - (1 << (BITS_PER_BYTE - 1 - (bitIndex % BITS_PER_BYTE))); + (1 << (BITS_PER_BYTE - 1 - (bitIndex % BITS_PER_BYTE))); } void BitArrayClearBit(BitArray bitArray, BitIndex bitIndex) { bitArray[bitIndex / BITS_PER_BYTE] &= - ~(1 << (BITS_PER_BYTE - 1 - (bitIndex % BITS_PER_BYTE))); + ~(1 << (BITS_PER_BYTE - 1 - (bitIndex % BITS_PER_BYTE))); } bool diff --git a/src/backend/lib/lispsort.c b/src/backend/lib/lispsort.c index a3c89b201e..f06448b578 100644 --- a/src/backend/lib/lispsort.c +++ b/src/backend/lib/lispsort.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/lib/Attic/lispsort.c,v 1.14 2001/01/24 19:42:55 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/lib/Attic/lispsort.c,v 1.15 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -55,5 +55,4 @@ lisp_qsort(List *the_list, /* the list to be sorted */ return output; } - #endif diff --git a/src/backend/lib/stringinfo.c b/src/backend/lib/stringinfo.c index f4b4294eaa..1745f0f9ca 100644 --- a/src/backend/lib/stringinfo.c +++ b/src/backend/lib/stringinfo.c @@ -9,7 +9,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: stringinfo.c,v 1.28 2001/03/22 06:16:13 momjian Exp $ + * $Id: stringinfo.c,v 1.29 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -106,7 +106,6 @@ appendStringInfo(StringInfo str, const char *fmt,...) for (;;) { - /* * Try to format the given string into the available space; but if * there's hardly any space, don't bother trying, just fall diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c index b6d1e6166f..44fb1f390c 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.69 2001/10/18 22:44:37 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/auth.c,v 1.70 2001/10/25 05:49:29 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,22 +45,22 @@ char *pg_krb_server_keyfile; #ifdef USE_PAM #include <security/pam_appl.h> - -#define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */ -static int CheckPAMAuth(Port *port, char *user, char *password); -static int pam_passwd_conv_proc(int num_msg, const struct pam_message **msg, - struct pam_response **resp, void *appdata_ptr); +#define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */ + +static int CheckPAMAuth(Port *port, char *user, char *password); +static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg, + struct pam_response ** resp, void *appdata_ptr); static struct pam_conv pam_passw_conv = { - &pam_passwd_conv_proc, - NULL + &pam_passwd_conv_proc, + NULL }; -static char * pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */ -static Port * pam_port_cludge; /* Workaround for passing "Port - * *port" into pam_passwd_conv_proc */ -#endif /* USE_PAM */ +static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */ +static Port *pam_port_cludge; /* Workaround for passing "Port *port" + * into pam_passwd_conv_proc */ +#endif /* USE_PAM */ #ifdef KRB4 /*---------------------------------------------------------------- @@ -429,13 +429,13 @@ auth_failed(Port *port, int status) const char *authmethod = "Unknown auth method:"; /* - * If we failed due to EOF from client, just quit; there's no point - * in trying to send a message to the client, and not much point in + * If we failed due to EOF from client, just quit; there's no point in + * trying to send a message to the client, and not much point in * logging the failure in the postmaster log. (Logging the failure * might be desirable, were it not for the fact that libpq closes the * connection unceremoniously if challenged for a password when it - * hasn't got one to send. We'll get a useless log entry for - * every psql connection under password auth, even if it's perfectly + * hasn't got one to send. We'll get a useless log entry for every + * psql connection under password auth, even if it's perfectly * successful, if we log STATUS_EOF events.) */ if (status == STATUS_EOF) @@ -467,7 +467,7 @@ auth_failed(Port *port, int status) case uaPAM: authmethod = "PAM"; break; -#endif /* USE_PAM */ +#endif /* USE_PAM */ } elog(FATAL, "%s authentication failed for user \"%s\"", @@ -483,7 +483,7 @@ auth_failed(Port *port, int status) void ClientAuthentication(Port *port) { - int status = STATUS_ERROR; + int status = STATUS_ERROR; /* * Get the authentication method to use for this frontend/database @@ -507,25 +507,26 @@ ClientAuthentication(Port *port) switch (port->auth_method) { case uaReject: - /* - * This could have come from an explicit "reject" entry in - * pg_hba.conf, but more likely it means there was no - * matching entry. Take pity on the poor user and issue a - * helpful error message. NOTE: this is not a security - * breach, because all the info reported here is known at - * the frontend and must be assumed known to bad guys. - * We're merely helping out the less clueful good guys. - */ - { - const char *hostinfo = "localhost"; - if (port->raddr.sa.sa_family == AF_INET) - hostinfo = inet_ntoa(port->raddr.in.sin_addr); - elog(FATAL, - "No pg_hba.conf entry for host %s, user %s, database %s", - hostinfo, port->user, port->database); - break; - } + /* + * This could have come from an explicit "reject" entry in + * pg_hba.conf, but more likely it means there was no matching + * entry. Take pity on the poor user and issue a helpful + * error message. NOTE: this is not a security breach, + * because all the info reported here is known at the frontend + * and must be assumed known to bad guys. We're merely helping + * out the less clueful good guys. + */ + { + const char *hostinfo = "localhost"; + + if (port->raddr.sa.sa_family == AF_INET) + hostinfo = inet_ntoa(port->raddr.in.sin_addr); + elog(FATAL, + "No pg_hba.conf entry for host %s, user %s, database %s", + hostinfo, port->user, port->database); + break; + } case uaKrb4: sendAuthRequest(port, AUTH_REQ_KRB4); @@ -539,23 +540,27 @@ ClientAuthentication(Port *port) case uaIdent: #if !defined(SO_PEERCRED) && (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))) + /* - * If we are doing ident on unix-domain sockets, - * use SCM_CREDS only if it is defined and SO_PEERCRED isn't. + * If we are doing ident on unix-domain sockets, use SCM_CREDS + * only if it is defined and SO_PEERCRED isn't. */ #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED) + /* - * Receive credentials on next message receipt, BSD/OS, NetBSD. - * We need to set this before the client sends the next packet. + * Receive credentials on next message receipt, BSD/OS, + * NetBSD. We need to set this before the client sends the + * next packet. */ { - int on = 1; + int on = 1; + if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0) elog(FATAL, "pg_local_sendauth: can't do setsockopt: %s\n", strerror(errno)); } #endif - if (port->raddr.sa.sa_family == AF_UNIX) + if (port->raddr.sa.sa_family == AF_UNIX) sendAuthRequest(port, AUTH_REQ_SCM_CREDS); #endif status = authident(port); @@ -569,8 +574,8 @@ ClientAuthentication(Port *port) case uaCrypt: sendAuthRequest(port, AUTH_REQ_CRYPT); status = recv_and_check_password_packet(port); - break; - + break; + case uaPassword: sendAuthRequest(port, AUTH_REQ_PASSWORD); status = recv_and_check_password_packet(port); @@ -581,7 +586,7 @@ ClientAuthentication(Port *port) pam_port_cludge = port; status = CheckPAMAuth(port, port->user, ""); break; -#endif /* USE_PAM */ +#endif /* USE_PAM */ case uaTrust: status = STATUS_OK; @@ -609,13 +614,9 @@ sendAuthRequest(Port *port, AuthRequest areq) /* Add the salt for encrypted passwords. */ if (areq == AUTH_REQ_MD5) - { pq_sendbytes(&buf, port->md5Salt, 4); - } else if (areq == AUTH_REQ_CRYPT) - { pq_sendbytes(&buf, port->cryptSalt, 2); - } pq_endmessage(&buf); pq_flush(); @@ -628,53 +629,60 @@ sendAuthRequest(Port *port, AuthRequest areq) */ static int -pam_passwd_conv_proc (int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) +pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg, struct pam_response ** resp, void *appdata_ptr) { StringInfoData buf; - int32 len; + int32 len; - if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF) { - switch(msg[0]->msg_style) { + if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF) + { + switch (msg[0]->msg_style) + { case PAM_ERROR_MSG: - snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "pam_passwd_conv_proc: Error from underlying PAM layer: '%s'\n", msg[0]->msg); + snprintf(PQerrormsg, PQERRORMSG_LENGTH, + "pam_passwd_conv_proc: Error from underlying PAM layer: '%s'\n", msg[0]->msg); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); return PAM_CONV_ERR; default: snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "pam_passwd_conv_proc: Unexpected PAM conversation %d/'%s'\n", - msg[0]->msg_style, msg[0]->msg); + "pam_passwd_conv_proc: Unexpected PAM conversation %d/'%s'\n", + msg[0]->msg_style, msg[0]->msg); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); return PAM_CONV_ERR; } } - if (!appdata_ptr) { - /* Workaround for Solaris 2.6 where the PAM library is broken - * and does not pass appdata_ptr to the conversation routine + if (!appdata_ptr) + { + /* + * Workaround for Solaris 2.6 where the PAM library is broken and + * does not pass appdata_ptr to the conversation routine */ appdata_ptr = pam_passwd; } - /* Password wasn't passed to PAM the first time around - let's go - * ask the client to send a password, which we then stuff into - * PAM. + /* + * Password wasn't passed to PAM the first time around - let's go ask + * the client to send a password, which we then stuff into PAM. */ - if(strlen(appdata_ptr) == 0) { + if (strlen(appdata_ptr) == 0) + { sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD); - if (pq_eof() == EOF || pq_getint(&len, 4) == EOF) { - return PAM_CONV_ERR; /* client didn't want to send password */ + if (pq_eof() == EOF || pq_getint(&len, 4) == EOF) + { + return PAM_CONV_ERR; /* client didn't want to send password */ } - initStringInfo(&buf); - pq_getstr(&buf); - if (DebugLvl > 5) + initStringInfo(&buf); + pq_getstr(&buf); + if (DebugLvl > 5) fprintf(stderr, "received PAM packet with len=%d, pw=%s\n", - len, buf.data); + len, buf.data); - if(strlen(buf.data) == 0) { + if (strlen(buf.data) == 0) + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, "pam_passwd_conv_proc: no password\n"); fputs(PQerrormsg, stderr); return PAM_CONV_ERR; @@ -682,17 +690,19 @@ pam_passwd_conv_proc (int num_msg, const struct pam_message **msg, struct pam_re appdata_ptr = buf.data; } - /* Explicitly not using palloc here - PAM will free this memory in + /* + * Explicitly not using palloc here - PAM will free this memory in * pam_end() */ *resp = calloc(num_msg, sizeof(struct pam_response)); - if (!*resp) { + if (!*resp) + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, "pam_passwd_conv_proc: Out of memory!\n"); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); - if(buf.data) + if (buf.data) pfree(buf.data); - return PAM_CONV_ERR; + return PAM_CONV_ERR; } (*resp)[0].resp = strdup((char *) appdata_ptr); @@ -708,101 +718,108 @@ pam_passwd_conv_proc (int num_msg, const struct pam_message **msg, struct pam_re static int CheckPAMAuth(Port *port, char *user, char *password) { - int retval; + int retval; pam_handle_t *pamh = NULL; /* - * Apparently, Solaris 2.6 is broken, and needs ugly static - * variable workaround + * Apparently, Solaris 2.6 is broken, and needs ugly static variable + * workaround */ pam_passwd = password; - /* Set the application data portion of the conversation struct - * This is later used inside the PAM conversation to pass the - * password to the authentication module. + /* + * Set the application data portion of the conversation struct This is + * later used inside the PAM conversation to pass the password to the + * authentication module. */ - pam_passw_conv.appdata_ptr = (char*) password; /* from password above, not allocated */ + pam_passw_conv.appdata_ptr = (char *) password; /* from password above, + * not allocated */ /* Optionally, one can set the service name in pg_hba.conf */ - if(port->auth_arg[0] == '\0') { + if (port->auth_arg[0] == '\0') retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@", &pam_passw_conv, &pamh); - } else { + else retval = pam_start(port->auth_arg, "pgsql@", &pam_passw_conv, &pamh); - } - if (retval != PAM_SUCCESS) { + if (retval != PAM_SUCCESS) + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "CheckPAMAuth: Failed to create PAM authenticator: '%s'\n", - pam_strerror(pamh, retval)); + "CheckPAMAuth: Failed to create PAM authenticator: '%s'\n", + pam_strerror(pamh, retval)); fputs(PQerrormsg, stderr); - pqdebug("%s", PQerrormsg); - pam_passwd = NULL; /* Unset pam_passwd */ + pqdebug("%s", PQerrormsg); + pam_passwd = NULL; /* Unset pam_passwd */ return STATUS_ERROR; } - if (retval == PAM_SUCCESS) { + if (retval == PAM_SUCCESS) retval = pam_set_item(pamh, PAM_USER, user); - } else { + else + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "CheckPAMAuth: pam_set_item(PAM_USER) failed: '%s'\n", - pam_strerror(pamh, retval)); + "CheckPAMAuth: pam_set_item(PAM_USER) failed: '%s'\n", + pam_strerror(pamh, retval)); fputs(PQerrormsg, stderr); - pqdebug("%s", PQerrormsg); - pam_passwd = NULL; /* Unset pam_passwd */ + pqdebug("%s", PQerrormsg); + pam_passwd = NULL; /* Unset pam_passwd */ return STATUS_ERROR; } - if (retval == PAM_SUCCESS) { + if (retval == PAM_SUCCESS) retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv); - } else { + else + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "CheckPAMAuth: pam_set_item(PAM_CONV) failed: '%s'\n", - pam_strerror(pamh, retval)); + "CheckPAMAuth: pam_set_item(PAM_CONV) failed: '%s'\n", + pam_strerror(pamh, retval)); fputs(PQerrormsg, stderr); - pqdebug("%s", PQerrormsg); - pam_passwd = NULL; /* Unset pam_passwd */ + pqdebug("%s", PQerrormsg); + pam_passwd = NULL; /* Unset pam_passwd */ return STATUS_ERROR; } - if (retval == PAM_SUCCESS) { + if (retval == PAM_SUCCESS) retval = pam_authenticate(pamh, 0); - } else { + else + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "CheckPAMAuth: pam_authenticate failed: '%s'\n", - pam_strerror(pamh, retval)); + "CheckPAMAuth: pam_authenticate failed: '%s'\n", + pam_strerror(pamh, retval)); fputs(PQerrormsg, stderr); - pqdebug("%s", PQerrormsg); - pam_passwd = NULL; /* Unset pam_passwd */ + pqdebug("%s", PQerrormsg); + pam_passwd = NULL; /* Unset pam_passwd */ return STATUS_ERROR; } - if (retval == PAM_SUCCESS) { + if (retval == PAM_SUCCESS) retval = pam_acct_mgmt(pamh, 0); - } else { + else + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "CheckPAMAuth: pam_acct_mgmt failed: '%s'\n", - pam_strerror(pamh, retval)); + "CheckPAMAuth: pam_acct_mgmt failed: '%s'\n", + pam_strerror(pamh, retval)); fputs(PQerrormsg, stderr); - pqdebug("%s", PQerrormsg); - pam_passwd = NULL; /* Unset pam_passwd */ + pqdebug("%s", PQerrormsg); + pam_passwd = NULL; /* Unset pam_passwd */ return STATUS_ERROR; } - if (retval == PAM_SUCCESS) { + if (retval == PAM_SUCCESS) + { retval = pam_end(pamh, retval); - if(retval != PAM_SUCCESS) { + if (retval != PAM_SUCCESS) + { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "CheckPAMAuth: Failed to release PAM authenticator: '%s'\n", - pam_strerror(pamh, retval)); + "CheckPAMAuth: Failed to release PAM authenticator: '%s'\n", + pam_strerror(pamh, retval)); fputs(PQerrormsg, stderr); - pqdebug("%s", PQerrormsg); + pqdebug("%s", PQerrormsg); } - pam_passwd = NULL; /* Unset pam_passwd */ + pam_passwd = NULL; /* Unset pam_passwd */ return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR); - } else { - return STATUS_ERROR; } + else + return STATUS_ERROR; } - -#endif /* USE_PAM */ +#endif /* USE_PAM */ /* @@ -819,7 +836,7 @@ recv_and_check_password_packet(Port *port) return STATUS_EOF; /* client didn't want to send password */ initStringInfo(&buf); - if (pq_getstr(&buf) == EOF) /* receive password */ + if (pq_getstr(&buf) == EOF) /* receive password */ { pfree(buf.data); return STATUS_EOF; @@ -903,7 +920,7 @@ map_old_to_new(Port *port, UserAuth old, int status) case uaReject: #ifdef USE_PAM case uaPAM: -#endif /* USE_PAM */ +#endif /* USE_PAM */ status = STATUS_ERROR; break; diff --git a/src/backend/libpq/crypt.c b/src/backend/libpq/crypt.c index 1d6b80a264..e2aaba3232 100644 --- a/src/backend/libpq/crypt.c +++ b/src/backend/libpq/crypt.c @@ -9,7 +9,7 @@ * Dec 17, 1997 - Todd A. Brandys * Orignal Version Completed. * - * $Id: crypt.c,v 1.38 2001/09/21 20:31:45 tgl Exp $ + * $Id: crypt.c,v 1.39 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -163,7 +163,6 @@ crypt_loadpwdfile(void) */ while (fgets(buffer, 256, pwd_file) != NULL) { - /* * We must remove the return char at the end of the string, as * this will affect the correct parsing of the password entry. @@ -281,8 +280,8 @@ md5_crypt_verify(const Port *port, const char *user, const char *pgpass) if (isMD5(passwd) && port->auth_method != uaMD5) { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "Password is stored MD5 encrypted. " - "'password' and 'crypt' auth methods cannot be used.\n"); + "Password is stored MD5 encrypted. " + "'password' and 'crypt' auth methods cannot be used.\n"); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); return STATUS_ERROR; @@ -295,11 +294,11 @@ md5_crypt_verify(const Port *port, const char *user, const char *pgpass) switch (port->auth_method) { case uaMD5: - crypt_pwd = palloc(MD5_PASSWD_LEN+1); + crypt_pwd = palloc(MD5_PASSWD_LEN + 1); if (isMD5(passwd)) { if (!EncryptMD5(passwd + strlen("md5"), - (char *)port->md5Salt, + (char *) port->md5Salt, sizeof(port->md5Salt), crypt_pwd)) { pfree(crypt_pwd); @@ -308,7 +307,7 @@ md5_crypt_verify(const Port *port, const char *user, const char *pgpass) } else { - char *crypt_pwd2 = palloc(MD5_PASSWD_LEN+1); + char *crypt_pwd2 = palloc(MD5_PASSWD_LEN + 1); if (!EncryptMD5(passwd, port->user, strlen(port->user), crypt_pwd2)) @@ -328,12 +327,13 @@ md5_crypt_verify(const Port *port, const char *user, const char *pgpass) } break; case uaCrypt: - { - char salt[3]; - StrNCpy(salt, port->cryptSalt,3); - crypt_pwd = crypt(passwd, salt); - break; - } + { + char salt[3]; + + StrNCpy(salt, port->cryptSalt, 3); + crypt_pwd = crypt(passwd, salt); + break; + } default: crypt_pwd = passwd; break; diff --git a/src/backend/libpq/hba.c b/src/backend/libpq/hba.c index b23710a8f6..6aafdc0913 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.74 2001/09/26 19:57:01 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/hba.c,v 1.75 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -45,14 +45,14 @@ /* * These variables hold the pre-parsed contents of the hba and ident * configuration files. Each is a list of sublists, one sublist for - * each (non-empty, non-comment) line of the file. Each sublist's + * each (non-empty, non-comment) line of the file. Each sublist's * first item is an integer line number (so we can give somewhat-useful * location info in error messages). Remaining items are palloc'd strings, * one string per token on the line. Note there will always be at least * one token, since blank lines are not entered in the data structure. */ static List *hba_lines = NIL; /* pre-parsed contents of hba file */ -static List *ident_lines = NIL; /* pre-parsed contents of ident file */ +static List *ident_lines = NIL; /* pre-parsed contents of ident file */ /* @@ -67,13 +67,13 @@ isblank(const char c) /* - * Grab one token out of fp. Tokens are strings of non-blank - * characters bounded by blank characters, beginning of line, and end - * of line. Blank means space or tab. Return the token as *buf. - * Leave file positioned to character immediately after the token or - * EOF, whichever comes first. If no more tokens on line, return null - * string as *buf and position file to beginning of next line or EOF, - * whichever comes first. + * Grab one token out of fp. Tokens are strings of non-blank + * characters bounded by blank characters, beginning of line, and end + * of line. Blank means space or tab. Return the token as *buf. + * Leave file positioned to character immediately after the token or + * EOF, whichever comes first. If no more tokens on line, return null + * string as *buf and position file to beginning of next line or EOF, + * whichever comes first. */ static void next_token(FILE *fp, char *buf, const int bufsz) @@ -89,8 +89,8 @@ next_token(FILE *fp, char *buf, const int bufsz) { /* * build a token in buf of next characters up to EOF, eol, or - * blank. If the token gets too long, we still parse it correctly, - * but the excess characters are not stored into *buf. + * blank. If the token gets too long, we still parse it + * correctly, but the excess characters are not stored into *buf. */ while (c != EOF && c != '\n' && !isblank(c)) { @@ -98,9 +98,10 @@ next_token(FILE *fp, char *buf, const int bufsz) *buf++ = c; c = getc(fp); } + /* - * Put back the char right after the token (critical in case it - * is eol, since we need to detect end-of-line at next call). + * Put back the char right after the token (critical in case it is + * eol, since we need to detect end-of-line at next call). */ if (c != EOF) ungetc(c, fp); @@ -120,7 +121,7 @@ read_to_eol(FILE *file) /* - * Read the given file and create a list of line sublists. + * Read the given file and create a list of line sublists. */ static List * tokenize_file(FILE *file) @@ -182,11 +183,12 @@ free_lines(List **lines) { if (*lines) { - List *line, *token; + List *line, + *token; foreach(line, *lines) { - List *ln = lfirst(line); + List *ln = lfirst(line); /* free the pstrdup'd tokens (don't try it on the line number) */ foreach(token, lnext(ln)) @@ -203,15 +205,15 @@ free_lines(List **lines) /* - * Scan the rest of a host record (after the mask field) - * and return the interpretation of it as *userauth_p, auth_arg, and - * *error_p. line points to the next token of the line. + * Scan the rest of a host record (after the mask field) + * and return the interpretation of it as *userauth_p, auth_arg, and + * *error_p. line points to the next token of the line. */ static void parse_hba_auth(List *line, UserAuth *userauth_p, char *auth_arg, bool *error_p) { - char *token; + char *token; if (!line) *error_p = true; @@ -261,21 +263,21 @@ parse_hba_auth(List *line, UserAuth *userauth_p, char *auth_arg, /* - * Process one line from the hba config file. + * Process one line from the hba config file. * - * See if it applies to a connection from a host with IP address port->raddr - * to a database named port->database. If so, return *found_p true - * and fill in the auth arguments into the appropriate port fields. - * If not, leave *found_p as it was. If the record has a syntax error, - * return *error_p true, after issuing a message to stderr. If no error, - * leave *error_p as it was. + * See if it applies to a connection from a host with IP address port->raddr + * to a database named port->database. If so, return *found_p true + * and fill in the auth arguments into the appropriate port fields. + * If not, leave *found_p as it was. If the record has a syntax error, + * return *error_p true, after issuing a message to stderr. If no error, + * leave *error_p as it was. */ static void parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) { int line_number; - char *token; - char *db; + char *token; + char *db; Assert(line != NIL); line_number = lfirsti(line); @@ -319,7 +321,8 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) } else if (strcmp(token, "host") == 0 || strcmp(token, "hostssl") == 0) { - struct in_addr file_ip_addr, mask; + struct in_addr file_ip_addr, + mask; if (strcmp(token, "hostssl") == 0) { @@ -401,17 +404,17 @@ hba_syntax: /* - * Scan the (pre-parsed) hba file line by line, looking for a match + * Scan the (pre-parsed) hba file line by line, looking for a match * to the port's connection request. */ static bool check_hba(hbaPort *port) { - bool found_entry = false; - bool error = false; - List *line; + bool found_entry = false; + bool error = false; + List *line; - foreach (line, hba_lines) + foreach(line, hba_lines) { parse_hba(lfirst(line), port, &found_entry, &error); if (found_entry || error) @@ -447,10 +450,11 @@ load_hba(void) if (hba_lines) free_lines(&hba_lines); + /* - * The name of old config file that better not exist. - * Fail if config file by old name exists. - * Put together the full pathname to the old config file. + * The name of old config file that better not exist. Fail if config + * file by old name exists. Put together the full pathname to the old + * config file. */ bufsize = (strlen(DataDir) + strlen(OLD_CONF_FILE) + 2) * sizeof(char); old_conf_file = (char *) palloc(bufsize); @@ -461,10 +465,10 @@ load_hba(void) /* Old config file exists. Tell this guy he needs to upgrade. */ close(fd); snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "A file exists by the name used for host-based authentication " - "in prior releases of Postgres (%s). The name and format of " - "the configuration file have changed, so this file should be " - "converted.\n", old_conf_file); + "A file exists by the name used for host-based authentication " + "in prior releases of Postgres (%s). The name and format of " + "the configuration file have changed, so this file should be " + "converted.\n", old_conf_file); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); } @@ -502,7 +506,7 @@ load_hba(void) /* * Process one line from the ident config file. * - * Take the line and compare it to the needed map, pg_user and ident_user. + * Take the line and compare it to the needed map, pg_user and ident_user. * *found_p and *error_p are set according to our results. */ static void @@ -510,10 +514,10 @@ parse_ident_usermap(List *line, const char *usermap_name, const char *pg_user, const char *ident_user, bool *found_p, bool *error_p) { int line_number; - char *token; - char *file_map; - char *file_pguser; - char *file_ident_user; + char *token; + char *file_map; + char *file_pguser; + char *file_ident_user; *found_p = false; *error_p = false; @@ -562,32 +566,33 @@ ident_syntax: /* - * Scan the (pre-parsed) ident usermap file line by line, looking for a match + * Scan the (pre-parsed) ident usermap file line by line, looking for a match * - * See if the user with ident username "ident_user" is allowed to act - * as Postgres user "pguser" according to usermap "usermap_name". + * See if the user with ident username "ident_user" is allowed to act + * as Postgres user "pguser" according to usermap "usermap_name". * - * Special case: For usermap "sameuser", don't look in the usermap - * file. That's an implied map where "pguser" must be identical to - * "ident_user" in order to be authorized. + * Special case: For usermap "sameuser", don't look in the usermap + * file. That's an implied map where "pguser" must be identical to + * "ident_user" in order to be authorized. * - * Iff authorized, return true. + * Iff authorized, return true. */ static bool check_ident_usermap(const char *usermap_name, const char *pg_user, const char *ident_user) { - List *line; - bool found_entry = false, error = false; + List *line; + bool found_entry = false, + error = false; if (usermap_name[0] == '\0') { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "check_ident_usermap: hba configuration file does not " - "have the usermap field filled in in the entry that pertains " - "to this connection. That field is essential for Ident-based " - "authentication.\n"); + "check_ident_usermap: hba configuration file does not " + "have the usermap field filled in in the entry that pertains " + "to this connection. That field is essential for Ident-based " + "authentication.\n"); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); found_entry = false; @@ -619,9 +624,9 @@ check_ident_usermap(const char *usermap_name, static void load_ident(void) { - FILE *file; /* The map file we have to read */ - char *map_file; /* The name of the map file we have to - * read */ + FILE *file; /* The map file we have to read */ + char *map_file; /* The name of the map file we have to + * read */ int bufsize; if (ident_lines) @@ -652,16 +657,17 @@ load_ident(void) /* - * Parse the string "*ident_response" as a response from a query to an Ident - * server. If it's a normal response indicating a username, return true - * and store the username at *ident_user. If it's anything else, + * Parse the string "*ident_response" as a response from a query to an Ident + * server. If it's a normal response indicating a username, return true + * and store the username at *ident_user. If it's anything else, * return false. */ static bool interpret_ident_response(char *ident_response, char *ident_user) { - char *cursor = ident_response; /* Cursor into *ident_response */ + char *cursor = ident_response; /* Cursor into + * *ident_response */ /* * Ident's response, in the telnet tradition, should end in crlf @@ -735,14 +741,14 @@ interpret_ident_response(char *ident_response, /* - * Talk to the ident server on host "remote_ip_addr" and find out who - * owns the tcp connection from his port "remote_port" to port - * "local_port_addr" on host "local_ip_addr". Return the username the - * ident server gives as "*ident_user". + * Talk to the ident server on host "remote_ip_addr" and find out who + * owns the tcp connection from his port "remote_port" to port + * "local_port_addr" on host "local_ip_addr". Return the username the + * ident server gives as "*ident_user". * - * IP addresses and port numbers are in network byte order. + * IP addresses and port numbers are in network byte order. * - * But iff we're unable to get the information from ident, return false. + * But iff we're unable to get the information from ident, return false. */ static bool ident_inet(const struct in_addr remote_ip_addr, @@ -755,14 +761,14 @@ ident_inet(const struct in_addr remote_ip_addr, * talk to Ident */ rc; /* Return code from a locally called * function */ - bool ident_return; + bool ident_return; sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if (sock_fd == -1) { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "Failed to create socket on which to talk to Ident server. " - "socket() returned errno = %s (%d)\n", strerror(errno), errno); + "Failed to create socket on which to talk to Ident server. " + "socket() returned errno = %s (%d)\n", strerror(errno), errno); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); ident_return = false; @@ -799,10 +805,10 @@ ident_inet(const struct in_addr remote_ip_addr, { snprintf(PQerrormsg, PQERRORMSG_LENGTH, "Unable to connect to Ident server on the host which is " - "trying to connect to Postgres " - "(IP address %s, Port %d). " - "errno = %s (%d)\n", - inet_ntoa(remote_ip_addr), IDENT_PORT, strerror(errno), errno); + "trying to connect to Postgres " + "(IP address %s, Port %d). " + "errno = %s (%d)\n", + inet_ntoa(remote_ip_addr), IDENT_PORT, strerror(errno), errno); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); ident_return = false; @@ -818,11 +824,11 @@ ident_inet(const struct in_addr remote_ip_addr, if (rc < 0) { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "Unable to send query to Ident server on the host which is " - "trying to connect to Postgres (Host %s, Port %d)," - "even though we successfully connected to it. " - "errno = %s (%d)\n", - inet_ntoa(remote_ip_addr), IDENT_PORT, strerror(errno), errno); + "Unable to send query to Ident server on the host which is " + "trying to connect to Postgres (Host %s, Port %d)," + "even though we successfully connected to it. " + "errno = %s (%d)\n", + inet_ntoa(remote_ip_addr), IDENT_PORT, strerror(errno), errno); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); ident_return = false; @@ -836,13 +842,13 @@ ident_inet(const struct in_addr remote_ip_addr, if (rc < 0) { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "Unable to receive response from Ident server " - "on the host which is " - "trying to connect to Postgres (Host %s, Port %d)," - "even though we successfully sent our query to it. " - "errno = %s (%d)\n", - inet_ntoa(remote_ip_addr), IDENT_PORT, - strerror(errno), errno); + "Unable to receive response from Ident server " + "on the host which is " + "trying to connect to Postgres (Host %s, Port %d)," + "even though we successfully sent our query to it. " + "errno = %s (%d)\n", + inet_ntoa(remote_ip_addr), IDENT_PORT, + strerror(errno), errno); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); ident_return = false; @@ -861,18 +867,18 @@ ident_inet(const struct in_addr remote_ip_addr, } /* - * Ask kernel about the credentials of the connecting process and - * determine the symbolic name of the corresponding user. + * Ask kernel about the credentials of the connecting process and + * determine the symbolic name of the corresponding user. * - * Returns either true and the username put into "ident_user", - * or false if we were unable to determine the username. + * Returns either true and the username put into "ident_user", + * or false if we were unable to determine the username. */ static bool ident_unix(int sock, char *ident_user) { #if defined(SO_PEERCRED) /* Linux style: use getsockopt(SO_PEERCRED) */ - struct ucred peercred; + struct ucred peercred; ACCEPT_TYPE_ARG3 so_len = sizeof(peercred); struct passwd *pass; @@ -894,13 +900,13 @@ ident_unix(int sock, char *ident_user) if (pass == NULL) { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "ident_unix: unknown local user with uid %d\n", peercred.uid); + "ident_unix: unknown local user with uid %d\n", peercred.uid); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); return false; } - StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX+1); + StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1); return true; @@ -910,36 +916,40 @@ ident_unix(int sock, char *ident_user) /* Credentials structure */ #ifdef HAVE_STRUCT_CMSGCRED typedef struct cmsgcred Cred; + #define cruid cmcred_uid #elif HAVE_STRUCT_FCRED typedef struct fcred Cred; + #define cruid fc_uid #elif HAVE_STRUCT_SOCKCRED typedef struct sockcred Cred; + #define cruid sc_uid #endif - Cred *cred; + Cred *cred; /* Compute size without padding */ - char cmsgmem[ALIGN(sizeof(struct cmsghdr)) + ALIGN(sizeof(Cred))]; /*for NetBSD*/ + char cmsgmem[ALIGN(sizeof(struct cmsghdr)) + ALIGN(sizeof(Cred))]; /* for NetBSD */ + /* Point to start of first structure */ - struct cmsghdr *cmsg = (struct cmsghdr *)cmsgmem; + struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem; struct iovec iov; - char buf; + char buf; struct passwd *pw; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; - msg.msg_control = (char *)cmsg; + msg.msg_control = (char *) cmsg; msg.msg_controllen = sizeof(cmsgmem); memset(cmsg, 0, sizeof(cmsgmem)); /* - * The one character which is received here is not meaningful; - * its purposes is only to make sure that recvmsg() blocks - * long enough for the other side to send its credentials. + * The one character which is received here is not meaningful; its + * purposes is only to make sure that recvmsg() blocks long enough for + * the other side to send its credentials. */ iov.iov_base = &buf; iov.iov_len = 1; @@ -956,20 +966,20 @@ ident_unix(int sock, char *ident_user) return false; } - cred = (Cred *)CMSG_DATA(cmsg); + cred = (Cred *) CMSG_DATA(cmsg); pw = getpwuid(cred->cruid); if (pw == NULL) { snprintf(PQerrormsg, PQERRORMSG_LENGTH, - "ident_unix: unknown local user with uid %d\n", - cred->cruid); + "ident_unix: unknown local user with uid %d\n", + cred->cruid); fputs(PQerrormsg, stderr); pqdebug("%s", PQerrormsg); return false; } - StrNCpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX+1); + StrNCpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1); return true; @@ -980,17 +990,16 @@ ident_unix(int sock, char *ident_user) pqdebug("%s", PQerrormsg); return false; - #endif } /* - * Determine the username of the initiator of the connection described - * by "port". Then look in the usermap file under the usermap - * port->auth_arg and see if that user is equivalent to Postgres user - * port->user. + * Determine the username of the initiator of the connection described + * by "port". Then look in the usermap file under the usermap + * port->auth_arg and see if that user is equivalent to Postgres user + * port->user. * - * Return STATUS_OK if yes, STATUS_ERROR if no match (or couldn't get info). + * Return STATUS_OK if yes, STATUS_ERROR if no match (or couldn't get info). */ int authident(hbaPort *port) @@ -1022,13 +1031,13 @@ authident(hbaPort *port) /* - * Determine what authentication method should be used when accessing database - * "database" from frontend "raddr", user "user". Return the method and - * an optional argument (stored in fields of *port), and STATUS_OK. + * Determine what authentication method should be used when accessing database + * "database" from frontend "raddr", user "user". Return the method and + * an optional argument (stored in fields of *port), and STATUS_OK. * - * Note that STATUS_ERROR indicates a problem with the hba config file. - * If the file is OK but does not contain any entry matching the request, - * we return STATUS_OK and method = uaReject. + * Note that STATUS_ERROR indicates a problem with the hba config file. + * If the file is OK but does not contain any entry matching the request, + * we return STATUS_OK and method = uaReject. */ int hba_getauthmethod(hbaPort *port) @@ -1252,5 +1261,4 @@ GetCharSetByHost(char *TableName, int host, const char *DataDir) pfree((struct CharsetItem *) ChArray[i]); } } - -#endif /* CYR_RECODE */ +#endif /* CYR_RECODE */ diff --git a/src/backend/libpq/md5.c b/src/backend/libpq/md5.c index c47abc71ce..b0fc834eb0 100644 --- a/src/backend/libpq/md5.c +++ b/src/backend/libpq/md5.c @@ -1,16 +1,16 @@ /* - * md5.c + * md5.c * - * Implements the MD5 Message-Digest Algorithm as specified in - * RFC 1321. This implementation is a simple one, in that it - * needs every input byte to be buffered before doing any - * calculations. I do not expect this file to be used for - * general purpose MD5'ing of large amounts of data, only for - * generating hashed passwords from limited input. + * Implements the MD5 Message-Digest Algorithm as specified in + * RFC 1321. This implementation is a simple one, in that it + * needs every input byte to be buffered before doing any + * calculations. I do not expect this file to be used for + * general purpose MD5'ing of large amounts of data, only for + * generating hashed passwords from limited input. * - * Sverre H. Huseby <sverrehu@online.no> + * Sverre H. Huseby <sverrehu@online.no> * - * $Header: /cvsroot/pgsql/src/backend/libpq/md5.c,v 1.8 2001/09/29 19:49:50 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/md5.c,v 1.9 2001/10/25 05:49:30 momjian Exp $ */ #include "postgres.h" @@ -32,15 +32,17 @@ /* * The returned array is allocated using malloc. the caller should free it - * when it is no longer needed. + * when it is no longer needed. */ static uint8 * createPaddedCopyWithLength(uint8 *b, uint32 *l) { - uint8 *ret; - uint32 q; - uint32 len, newLen448; - uint32 len_high, len_low; /* 64-bit value split into 32-bit sections */ + uint8 *ret; + uint32 q; + uint32 len, + newLen448; + uint32 len_high, + len_low; /* 64-bit value split into 32-bit sections */ len = ((b == NULL) ? 0 : *l); newLen448 = len + 64 - (len % 64) - 8; @@ -93,7 +95,10 @@ createPaddedCopyWithLength(uint8 *b, uint32 *l) static void doTheRounds(uint32 X[16], uint32 state[4]) { - uint32 a, b, c, d; + uint32 a, + b, + c, + d; a = state[0]; b = state[1]; @@ -101,76 +106,76 @@ doTheRounds(uint32 X[16], uint32 state[4]) d = state[3]; /* round 1 */ - a = b + ROT_LEFT((a + F(b, c, d) + X[ 0] + 0xd76aa478), 7); /* 1 */ - d = a + ROT_LEFT((d + F(a, b, c) + X[ 1] + 0xe8c7b756), 12); /* 2 */ - c = d + ROT_LEFT((c + F(d, a, b) + X[ 2] + 0x242070db), 17); /* 3 */ - b = c + ROT_LEFT((b + F(c, d, a) + X[ 3] + 0xc1bdceee), 22); /* 4 */ - a = b + ROT_LEFT((a + F(b, c, d) + X[ 4] + 0xf57c0faf), 7); /* 5 */ - d = a + ROT_LEFT((d + F(a, b, c) + X[ 5] + 0x4787c62a), 12); /* 6 */ - c = d + ROT_LEFT((c + F(d, a, b) + X[ 6] + 0xa8304613), 17); /* 7 */ - b = c + ROT_LEFT((b + F(c, d, a) + X[ 7] + 0xfd469501), 22); /* 8 */ - a = b + ROT_LEFT((a + F(b, c, d) + X[ 8] + 0x698098d8), 7); /* 9 */ - d = a + ROT_LEFT((d + F(a, b, c) + X[ 9] + 0x8b44f7af), 12); /* 10 */ - c = d + ROT_LEFT((c + F(d, a, b) + X[10] + 0xffff5bb1), 17); /* 11 */ - b = c + ROT_LEFT((b + F(c, d, a) + X[11] + 0x895cd7be), 22); /* 12 */ - a = b + ROT_LEFT((a + F(b, c, d) + X[12] + 0x6b901122), 7); /* 13 */ - d = a + ROT_LEFT((d + F(a, b, c) + X[13] + 0xfd987193), 12); /* 14 */ - c = d + ROT_LEFT((c + F(d, a, b) + X[14] + 0xa679438e), 17); /* 15 */ - b = c + ROT_LEFT((b + F(c, d, a) + X[15] + 0x49b40821), 22); /* 16 */ + a = b + ROT_LEFT((a + F(b, c, d) + X[0] + 0xd76aa478), 7); /* 1 */ + d = a + ROT_LEFT((d + F(a, b, c) + X[1] + 0xe8c7b756), 12); /* 2 */ + c = d + ROT_LEFT((c + F(d, a, b) + X[2] + 0x242070db), 17); /* 3 */ + b = c + ROT_LEFT((b + F(c, d, a) + X[3] + 0xc1bdceee), 22); /* 4 */ + a = b + ROT_LEFT((a + F(b, c, d) + X[4] + 0xf57c0faf), 7); /* 5 */ + d = a + ROT_LEFT((d + F(a, b, c) + X[5] + 0x4787c62a), 12); /* 6 */ + c = d + ROT_LEFT((c + F(d, a, b) + X[6] + 0xa8304613), 17); /* 7 */ + b = c + ROT_LEFT((b + F(c, d, a) + X[7] + 0xfd469501), 22); /* 8 */ + a = b + ROT_LEFT((a + F(b, c, d) + X[8] + 0x698098d8), 7); /* 9 */ + d = a + ROT_LEFT((d + F(a, b, c) + X[9] + 0x8b44f7af), 12); /* 10 */ + c = d + ROT_LEFT((c + F(d, a, b) + X[10] + 0xffff5bb1), 17); /* 11 */ + b = c + ROT_LEFT((b + F(c, d, a) + X[11] + 0x895cd7be), 22); /* 12 */ + a = b + ROT_LEFT((a + F(b, c, d) + X[12] + 0x6b901122), 7); /* 13 */ + d = a + ROT_LEFT((d + F(a, b, c) + X[13] + 0xfd987193), 12); /* 14 */ + c = d + ROT_LEFT((c + F(d, a, b) + X[14] + 0xa679438e), 17); /* 15 */ + b = c + ROT_LEFT((b + F(c, d, a) + X[15] + 0x49b40821), 22); /* 16 */ /* round 2 */ - a = b + ROT_LEFT((a + G(b, c, d) + X[ 1] + 0xf61e2562), 5); /* 17 */ - d = a + ROT_LEFT((d + G(a, b, c) + X[ 6] + 0xc040b340), 9); /* 18 */ - c = d + ROT_LEFT((c + G(d, a, b) + X[11] + 0x265e5a51), 14); /* 19 */ - b = c + ROT_LEFT((b + G(c, d, a) + X[ 0] + 0xe9b6c7aa), 20); /* 20 */ - a = b + ROT_LEFT((a + G(b, c, d) + X[ 5] + 0xd62f105d), 5); /* 21 */ - d = a + ROT_LEFT((d + G(a, b, c) + X[10] + 0x02441453), 9); /* 22 */ - c = d + ROT_LEFT((c + G(d, a, b) + X[15] + 0xd8a1e681), 14); /* 23 */ - b = c + ROT_LEFT((b + G(c, d, a) + X[ 4] + 0xe7d3fbc8), 20); /* 24 */ - a = b + ROT_LEFT((a + G(b, c, d) + X[ 9] + 0x21e1cde6), 5); /* 25 */ - d = a + ROT_LEFT((d + G(a, b, c) + X[14] + 0xc33707d6), 9); /* 26 */ - c = d + ROT_LEFT((c + G(d, a, b) + X[ 3] + 0xf4d50d87), 14); /* 27 */ - b = c + ROT_LEFT((b + G(c, d, a) + X[ 8] + 0x455a14ed), 20); /* 28 */ - a = b + ROT_LEFT((a + G(b, c, d) + X[13] + 0xa9e3e905), 5); /* 29 */ - d = a + ROT_LEFT((d + G(a, b, c) + X[ 2] + 0xfcefa3f8), 9); /* 30 */ - c = d + ROT_LEFT((c + G(d, a, b) + X[ 7] + 0x676f02d9), 14); /* 31 */ - b = c + ROT_LEFT((b + G(c, d, a) + X[12] + 0x8d2a4c8a), 20); /* 32 */ + a = b + ROT_LEFT((a + G(b, c, d) + X[1] + 0xf61e2562), 5); /* 17 */ + d = a + ROT_LEFT((d + G(a, b, c) + X[6] + 0xc040b340), 9); /* 18 */ + c = d + ROT_LEFT((c + G(d, a, b) + X[11] + 0x265e5a51), 14); /* 19 */ + b = c + ROT_LEFT((b + G(c, d, a) + X[0] + 0xe9b6c7aa), 20); /* 20 */ + a = b + ROT_LEFT((a + G(b, c, d) + X[5] + 0xd62f105d), 5); /* 21 */ + d = a + ROT_LEFT((d + G(a, b, c) + X[10] + 0x02441453), 9); /* 22 */ + c = d + ROT_LEFT((c + G(d, a, b) + X[15] + 0xd8a1e681), 14); /* 23 */ + b = c + ROT_LEFT((b + G(c, d, a) + X[4] + 0xe7d3fbc8), 20); /* 24 */ + a = b + ROT_LEFT((a + G(b, c, d) + X[9] + 0x21e1cde6), 5); /* 25 */ + d = a + ROT_LEFT((d + G(a, b, c) + X[14] + 0xc33707d6), 9); /* 26 */ + c = d + ROT_LEFT((c + G(d, a, b) + X[3] + 0xf4d50d87), 14); /* 27 */ + b = c + ROT_LEFT((b + G(c, d, a) + X[8] + 0x455a14ed), 20); /* 28 */ + a = b + ROT_LEFT((a + G(b, c, d) + X[13] + 0xa9e3e905), 5); /* 29 */ + d = a + ROT_LEFT((d + G(a, b, c) + X[2] + 0xfcefa3f8), 9); /* 30 */ + c = d + ROT_LEFT((c + G(d, a, b) + X[7] + 0x676f02d9), 14); /* 31 */ + b = c + ROT_LEFT((b + G(c, d, a) + X[12] + 0x8d2a4c8a), 20); /* 32 */ /* round 3 */ - a = b + ROT_LEFT((a + H(b, c, d) + X[ 5] + 0xfffa3942), 4); /* 33 */ - d = a + ROT_LEFT((d + H(a, b, c) + X[ 8] + 0x8771f681), 11); /* 34 */ - c = d + ROT_LEFT((c + H(d, a, b) + X[11] + 0x6d9d6122), 16); /* 35 */ - b = c + ROT_LEFT((b + H(c, d, a) + X[14] + 0xfde5380c), 23); /* 36 */ - a = b + ROT_LEFT((a + H(b, c, d) + X[ 1] + 0xa4beea44), 4); /* 37 */ - d = a + ROT_LEFT((d + H(a, b, c) + X[ 4] + 0x4bdecfa9), 11); /* 38 */ - c = d + ROT_LEFT((c + H(d, a, b) + X[ 7] + 0xf6bb4b60), 16); /* 39 */ - b = c + ROT_LEFT((b + H(c, d, a) + X[10] + 0xbebfbc70), 23); /* 40 */ - a = b + ROT_LEFT((a + H(b, c, d) + X[13] + 0x289b7ec6), 4); /* 41 */ - d = a + ROT_LEFT((d + H(a, b, c) + X[ 0] + 0xeaa127fa), 11); /* 42 */ - c = d + ROT_LEFT((c + H(d, a, b) + X[ 3] + 0xd4ef3085), 16); /* 43 */ - b = c + ROT_LEFT((b + H(c, d, a) + X[ 6] + 0x04881d05), 23); /* 44 */ - a = b + ROT_LEFT((a + H(b, c, d) + X[ 9] + 0xd9d4d039), 4); /* 45 */ - d = a + ROT_LEFT((d + H(a, b, c) + X[12] + 0xe6db99e5), 11); /* 46 */ - c = d + ROT_LEFT((c + H(d, a, b) + X[15] + 0x1fa27cf8), 16); /* 47 */ - b = c + ROT_LEFT((b + H(c, d, a) + X[ 2] + 0xc4ac5665), 23); /* 48 */ + a = b + ROT_LEFT((a + H(b, c, d) + X[5] + 0xfffa3942), 4); /* 33 */ + d = a + ROT_LEFT((d + H(a, b, c) + X[8] + 0x8771f681), 11); /* 34 */ + c = d + ROT_LEFT((c + H(d, a, b) + X[11] + 0x6d9d6122), 16); /* 35 */ + b = c + ROT_LEFT((b + H(c, d, a) + X[14] + 0xfde5380c), 23); /* 36 */ + a = b + ROT_LEFT((a + H(b, c, d) + X[1] + 0xa4beea44), 4); /* 37 */ + d = a + ROT_LEFT((d + H(a, b, c) + X[4] + 0x4bdecfa9), 11); /* 38 */ + c = d + ROT_LEFT((c + H(d, a, b) + X[7] + 0xf6bb4b60), 16); /* 39 */ + b = c + ROT_LEFT((b + H(c, d, a) + X[10] + 0xbebfbc70), 23); /* 40 */ + a = b + ROT_LEFT((a + H(b, c, d) + X[13] + 0x289b7ec6), 4); /* 41 */ + d = a + ROT_LEFT((d + H(a, b, c) + X[0] + 0xeaa127fa), 11); /* 42 */ + c = d + ROT_LEFT((c + H(d, a, b) + X[3] + 0xd4ef3085), 16); /* 43 */ + b = c + ROT_LEFT((b + H(c, d, a) + X[6] + 0x04881d05), 23); /* 44 */ + a = b + ROT_LEFT((a + H(b, c, d) + X[9] + 0xd9d4d039), 4); /* 45 */ + d = a + ROT_LEFT((d + H(a, b, c) + X[12] + 0xe6db99e5), 11); /* 46 */ + c = d + ROT_LEFT((c + H(d, a, b) + X[15] + 0x1fa27cf8), 16); /* 47 */ + b = c + ROT_LEFT((b + H(c, d, a) + X[2] + 0xc4ac5665), 23); /* 48 */ /* round 4 */ - a = b + ROT_LEFT((a + I(b, c, d) + X[ 0] + 0xf4292244), 6); /* 49 */ - d = a + ROT_LEFT((d + I(a, b, c) + X[ 7] + 0x432aff97), 10); /* 50 */ - c = d + ROT_LEFT((c + I(d, a, b) + X[14] + 0xab9423a7), 15); /* 51 */ - b = c + ROT_LEFT((b + I(c, d, a) + X[ 5] + 0xfc93a039), 21); /* 52 */ - a = b + ROT_LEFT((a + I(b, c, d) + X[12] + 0x655b59c3), 6); /* 53 */ - d = a + ROT_LEFT((d + I(a, b, c) + X[ 3] + 0x8f0ccc92), 10); /* 54 */ - c = d + ROT_LEFT((c + I(d, a, b) + X[10] + 0xffeff47d), 15); /* 55 */ - b = c + ROT_LEFT((b + I(c, d, a) + X[ 1] + 0x85845dd1), 21); /* 56 */ - a = b + ROT_LEFT((a + I(b, c, d) + X[ 8] + 0x6fa87e4f), 6); /* 57 */ - d = a + ROT_LEFT((d + I(a, b, c) + X[15] + 0xfe2ce6e0), 10); /* 58 */ - c = d + ROT_LEFT((c + I(d, a, b) + X[ 6] + 0xa3014314), 15); /* 59 */ - b = c + ROT_LEFT((b + I(c, d, a) + X[13] + 0x4e0811a1), 21); /* 60 */ - a = b + ROT_LEFT((a + I(b, c, d) + X[ 4] + 0xf7537e82), 6); /* 61 */ - d = a + ROT_LEFT((d + I(a, b, c) + X[11] + 0xbd3af235), 10); /* 62 */ - c = d + ROT_LEFT((c + I(d, a, b) + X[ 2] + 0x2ad7d2bb), 15); /* 63 */ - b = c + ROT_LEFT((b + I(c, d, a) + X[ 9] + 0xeb86d391), 21); /* 64 */ + a = b + ROT_LEFT((a + I(b, c, d) + X[0] + 0xf4292244), 6); /* 49 */ + d = a + ROT_LEFT((d + I(a, b, c) + X[7] + 0x432aff97), 10); /* 50 */ + c = d + ROT_LEFT((c + I(d, a, b) + X[14] + 0xab9423a7), 15); /* 51 */ + b = c + ROT_LEFT((b + I(c, d, a) + X[5] + 0xfc93a039), 21); /* 52 */ + a = b + ROT_LEFT((a + I(b, c, d) + X[12] + 0x655b59c3), 6); /* 53 */ + d = a + ROT_LEFT((d + I(a, b, c) + X[3] + 0x8f0ccc92), 10); /* 54 */ + c = d + ROT_LEFT((c + I(d, a, b) + X[10] + 0xffeff47d), 15); /* 55 */ + b = c + ROT_LEFT((b + I(c, d, a) + X[1] + 0x85845dd1), 21); /* 56 */ + a = b + ROT_LEFT((a + I(b, c, d) + X[8] + 0x6fa87e4f), 6); /* 57 */ + d = a + ROT_LEFT((d + I(a, b, c) + X[15] + 0xfe2ce6e0), 10); /* 58 */ + c = d + ROT_LEFT((c + I(d, a, b) + X[6] + 0xa3014314), 15); /* 59 */ + b = c + ROT_LEFT((b + I(c, d, a) + X[13] + 0x4e0811a1), 21); /* 60 */ + a = b + ROT_LEFT((a + I(b, c, d) + X[4] + 0xf7537e82), 6); /* 61 */ + d = a + ROT_LEFT((d + I(a, b, c) + X[11] + 0xbd3af235), 10); /* 62 */ + c = d + ROT_LEFT((c + I(d, a, b) + X[2] + 0x2ad7d2bb), 15); /* 63 */ + b = c + ROT_LEFT((b + I(c, d, a) + X[9] + 0xeb86d391), 21); /* 64 */ state[0] += a; state[1] += b; @@ -181,11 +186,15 @@ doTheRounds(uint32 X[16], uint32 state[4]) static int calculateDigestFromBuffer(uint8 *b, uint32 len, uint8 sum[16]) { - register uint32 i, j, k, newI; - uint32 l; - uint8 *input; + register uint32 i, + j, + k, + newI; + uint32 l; + uint8 *input; register uint32 *wbp; - uint32 workBuff[16], state[4]; + uint32 workBuff[16], + state[4]; l = len; @@ -197,11 +206,13 @@ calculateDigestFromBuffer(uint8 *b, uint32 len, uint8 sum[16]) if ((input = createPaddedCopyWithLength(b, &l)) == NULL) return 0; - for (i = 0;;) { + for (i = 0;;) + { if ((newI = i + 16 * 4) > l) break; k = i + 3; - for (j = 0; j < 16; j++) { + for (j = 0; j < 16; j++) + { wbp = (workBuff + j); *wbp = input[k--]; *wbp <<= 8; @@ -218,7 +229,8 @@ calculateDigestFromBuffer(uint8 *b, uint32 len, uint8 sum[16]) free(input); j = 0; - for (i = 0; i < 4; i++) { + for (i = 0; i < 4; i++) + { k = state[i]; sum[j++] = (k & 0xff); k >>= 8; @@ -235,9 +247,11 @@ static void bytesToHex(uint8 b[16], char *s) { static char *hex = "0123456789abcdef"; - int q, w; + int q, + w; - for (q = 0, w = 0; q < 16; q++) { + for (q = 0, w = 0; q < 16; q++) + { s[w++] = hex[(b[q] >> 4) & 0x0F]; s[w++] = hex[b[q] & 0x0F]; } @@ -245,39 +259,39 @@ bytesToHex(uint8 b[16], char *s) } /* - * PUBLIC FUNCTIONS + * PUBLIC FUNCTIONS */ /* - * md5_hash + * md5_hash * - * Calculates the MD5 sum of the bytes in a buffer. + * Calculates the MD5 sum of the bytes in a buffer. * - * SYNOPSIS #include "crypt.h" - * int md5_hash(const void *buff, size_t len, char *hexsum) + * SYNOPSIS #include "crypt.h" + * int md5_hash(const void *buff, size_t len, char *hexsum) * - * INPUT buff the buffer containing the bytes that you want - * the MD5 sum of. - * len number of bytes in the buffer. + * INPUT buff the buffer containing the bytes that you want + * the MD5 sum of. + * len number of bytes in the buffer. * - * OUTPUT hexsum the MD5 sum as a '\0'-terminated string of - * hexadecimal digits. an MD5 sum is 16 bytes long. - * each byte is represented by two heaxadecimal - * characters. you thus need to provide an array - * of 33 characters, including the trailing '\0'. + * OUTPUT hexsum the MD5 sum as a '\0'-terminated string of + * hexadecimal digits. an MD5 sum is 16 bytes long. + * each byte is represented by two heaxadecimal + * characters. you thus need to provide an array + * of 33 characters, including the trailing '\0'. * - * RETURNS 0 on failure (out of memory for internal buffers) or - * non-zero on success. + * RETURNS 0 on failure (out of memory for internal buffers) or + * non-zero on success. * - * STANDARDS MD5 is described in RFC 1321. + * STANDARDS MD5 is described in RFC 1321. * - * AUTHOR Sverre H. Huseby <sverrehu@online.no> + * AUTHOR Sverre H. Huseby <sverrehu@online.no> * */ bool md5_hash(const void *buff, size_t len, char *hexsum) { - uint8 sum[16]; + uint8 sum[16]; if (!calculateDigestFromBuffer((uint8 *) buff, len, sum)) return false; @@ -297,19 +311,20 @@ md5_hash(const void *buff, size_t len, char *hexsum) * * Returns TRUE if okay, FALSE on error (out of memory). */ -bool EncryptMD5(const char *passwd, const char *salt, size_t salt_len, - char *buf) +bool +EncryptMD5(const char *passwd, const char *salt, size_t salt_len, + char *buf) { - size_t passwd_len = strlen(passwd); - char *crypt_buf = palloc(passwd_len + salt_len); - bool ret; - + size_t passwd_len = strlen(passwd); + char *crypt_buf = palloc(passwd_len + salt_len); + bool ret; + /* - * Place salt at the end because it may be known by users - * trying to crack the MD5 output. - */ + * Place salt at the end because it may be known by users trying to + * crack the MD5 output. + */ strcpy(crypt_buf, passwd); - memcpy(crypt_buf+passwd_len, salt, salt_len); + memcpy(crypt_buf + passwd_len, salt, salt_len); strcpy(buf, "md5"); ret = md5_hash(crypt_buf, passwd_len + salt_len, buf + 3); diff --git a/src/backend/libpq/password.c b/src/backend/libpq/password.c index 4dde3afe99..96415ae4e7 100644 --- a/src/backend/libpq/password.c +++ b/src/backend/libpq/password.c @@ -2,7 +2,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: password.c,v 1.39 2001/08/17 15:44:17 momjian Exp $ + * $Id: password.c,v 1.40 2001/10/25 05:49:30 momjian Exp $ * */ @@ -78,9 +78,9 @@ verify_password(const Port *port, const char *user, const char *password) /* * If the password is empty or "+" then we use the regular * pg_shadow passwords. If we use crypt then we have to use - * pg_shadow passwords no matter what. This is because - * the current code needs non-encrypted passwords to - * encrypt with a random salt. + * pg_shadow passwords no matter what. This is because the + * current code needs non-encrypted passwords to encrypt with + * a random salt. */ if (port->auth_method == uaMD5 || port->auth_method == uaCrypt || diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c index b588f09a07..8ea425a701 100644 --- a/src/backend/libpq/pqcomm.c +++ b/src/backend/libpq/pqcomm.c @@ -29,7 +29,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pqcomm.c,v 1.121 2001/08/07 15:55:16 tgl Exp $ + * $Id: pqcomm.c,v 1.122 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -347,9 +347,9 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber, #endif /* HAVE_UNIX_SOCKETS */ /* - * 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) @@ -401,6 +401,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. @@ -701,8 +702,8 @@ pq_flush(void) int pq_eof(void) { - char x; - int res; + char x; + int res; res = recv(MyProcPort->sock, &x, 1, MSG_PEEK); diff --git a/src/backend/libpq/pqformat.c b/src/backend/libpq/pqformat.c index 6719017c6d..a0ea85f41f 100644 --- a/src/backend/libpq/pqformat.c +++ b/src/backend/libpq/pqformat.c @@ -16,7 +16,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pqformat.c,v 1.17 2001/04/16 01:46:57 tgl Exp $ + * $Id: pqformat.c,v 1.18 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -90,7 +90,6 @@ #else #error BYTE_ORDER not defined as anything understood - #endif #endif #endif @@ -309,7 +308,6 @@ pq_getstr(StringInfo s) #ifdef MULTIBYTE char *p; - #endif result = pq_getstring(s); diff --git a/src/backend/libpq/util.c b/src/backend/libpq/util.c index a80dc8781f..4ddf17d59b 100644 --- a/src/backend/libpq/util.c +++ b/src/backend/libpq/util.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/libpq/Attic/util.c,v 1.17 2001/01/24 19:42:56 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/libpq/Attic/util.c,v 1.18 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -50,7 +50,6 @@ pqdebug(char *fmt, char *msg) if (PQtracep) { - /* * if nothing else was suggested default to stderr */ diff --git a/src/backend/main/main.c b/src/backend/main/main.c index 43d9b6433d..be5896e375 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.47 2001/10/22 19:41:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/main/main.c,v 1.48 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -67,11 +67,9 @@ main(int argc, char *argv[]) #if defined(__alpha) #ifdef NOFIXADE int buffer[] = {SSIN_UACPROC, UAC_SIGBUS}; - #endif /* NOFIXADE */ #ifdef NOPRINTADE int buffer[] = {SSIN_UACPROC, UAC_NOPRINT}; - #endif /* NOPRINTADE */ #endif /* __alpha */ @@ -86,7 +84,6 @@ main(int argc, char *argv[]) (unsigned long) NULL) < 0) fprintf(stderr, gettext("%s: setsysinfo failed: %s\n"), argv[0], strerror(errno)); #endif - #endif /* NOFIXADE || NOPRINTADE */ #ifdef __BEOS__ @@ -107,16 +104,16 @@ main(int argc, char *argv[]) * affected if init_ps_display overwrites the original argv[]. * * (NB: do NOT think to remove the copying of argv[], even though - * postmaster.c finishes looking at argv[] long before we ever consider - * changing the ps display. On some platforms, getopt() keeps pointers - * into the argv array, and will get horribly confused when it is - * re-called to analyze a subprocess' argument string if the argv storage - * has been clobbered meanwhile.) + * postmaster.c finishes looking at argv[] long before we ever + * consider changing the ps display. On some platforms, getopt() + * keeps pointers into the argv array, and will get horribly confused + * when it is re-called to analyze a subprocess' argument string if + * the argv storage has been clobbered meanwhile.) * * On some platforms, save_ps_display_args moves the environment strings - * to make extra room. Therefore this should be done as early as - * possible during startup, to avoid entanglements with code that might - * save a getenv() result pointer. + * to make extra room. Therefore this should be done as early as + * possible during startup, to avoid entanglements with code that + * might save a getenv() result pointer. */ save_ps_display_args(argc, argv); @@ -135,8 +132,9 @@ main(int argc, char *argv[]) #endif /* - * Skip permission checks if we're just trying to do --help or --version; - * otherwise root will get unhelpful failure messages from initdb. + * Skip permission checks if we're just trying to do --help or + * --version; otherwise root will get unhelpful failure messages from + * initdb. */ if (!(argc > 1 && (strcmp(argv[1], "--help") == 0 || @@ -154,11 +152,11 @@ main(int argc, char *argv[]) if (geteuid() == 0) { fprintf(stderr, gettext( - "\"root\" execution of the PostgreSQL server is not permitted.\n\n" - "The server must be started under an unprivileged user id to prevent\n" - "a possible system security compromise. See the documentation for\n" - "more information on how to properly start the server.\n\n" - )); + "\"root\" execution of the PostgreSQL server is not permitted.\n\n" + "The server must be started under an unprivileged user id to prevent\n" + "a possible system security compromise. See the documentation for\n" + "more information on how to properly start the server.\n\n" + )); exit(1); } #endif /* __BEOS__ */ @@ -166,11 +164,11 @@ main(int argc, char *argv[]) /* * Also make sure that real and effective uids are the same. * Executing Postgres as a setuid program from a root shell is a - * security hole, since on many platforms a nefarious subroutine could - * setuid back to root if real uid is root. (Since nobody actually - * uses Postgres as a setuid program, trying to actively fix this - * situation seems more trouble than it's worth; we'll just expend the - * effort to check for it.) + * security hole, since on many platforms a nefarious subroutine + * could setuid back to root if real uid is root. (Since nobody + * actually uses Postgres as a setuid program, trying to actively + * fix this situation seems more trouble than it's worth; we'll + * just expend the effort to check for it.) */ if (getuid() != geteuid()) { diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c index abf5c08d27..620054380a 100644 --- a/src/backend/nodes/copyfuncs.c +++ b/src/backend/nodes/copyfuncs.c @@ -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.158 2001/10/18 17:30:14 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/copyfuncs.c,v 1.159 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -782,7 +782,6 @@ _copyConst(Const *from) if (from->constbyval || from->constisnull) { - /* * passed by value so just copy the datum. Also, don't try to copy * struct when value is null! @@ -792,7 +791,6 @@ _copyConst(Const *from) } else { - /* * not passed by value. datum contains a pointer. */ @@ -1024,7 +1022,7 @@ _copyCaseWhen(CaseWhen *from) static NullTest * _copyNullTest(NullTest *from) { - NullTest *newnode = makeNode(NullTest); + NullTest *newnode = makeNode(NullTest); /* * copy remainder of node @@ -1180,7 +1178,6 @@ _copyIndexOptInfo(IndexOptInfo *from) static void CopyPathFields(Path *from, Path *newnode) { - /* * Modify the next line, since it causes the copying to cycle (i.e. * the parent points right back here! -- JMH, 7/7/92. Old version: @@ -1780,8 +1777,8 @@ _copyQuery(Query *from) /* * We do not copy the planner internal fields: base_rel_list, - * other_rel_list, join_rel_list, equi_key_list, query_pathkeys. - * Not entirely clear if this is right? + * other_rel_list, join_rel_list, equi_key_list, query_pathkeys. Not + * entirely clear if this is right? */ return newnode; @@ -1892,7 +1889,7 @@ _copyAlterTableStmt(AlterTableStmt *from) static GrantStmt * _copyGrantStmt(GrantStmt *from) { - GrantStmt *newnode = makeNode(GrantStmt); + GrantStmt *newnode = makeNode(GrantStmt); newnode->is_grant = from->is_grant; Node_Copy(from, newnode, relnames); @@ -2426,7 +2423,7 @@ _copyLockStmt(LockStmt *from) LockStmt *newnode = makeNode(LockStmt); Node_Copy(from, newnode, rellist); - + newnode->mode = from->mode; return newnode; @@ -2536,7 +2533,6 @@ copyObject(void *from) switch (nodeTag(from)) { - /* * PLAN NODES */ diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c index 64e27f1780..0a48a194df 100644 --- a/src/backend/nodes/equalfuncs.c +++ b/src/backend/nodes/equalfuncs.c @@ -20,7 +20,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/equalfuncs.c,v 1.106 2001/10/18 17:30:14 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/equalfuncs.c,v 1.107 2001/10/25 05:49:30 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -87,7 +87,6 @@ _equalFjoin(Fjoin *a, Fjoin *b) static bool _equalExpr(Expr *a, Expr *b) { - /* * We do not examine typeOid, since the optimizer often doesn't bother * to set it in created nodes, and it is logically a derivative of the @@ -351,7 +350,6 @@ _equalJoinExpr(JoinExpr *a, JoinExpr *b) static bool _equalRelOptInfo(RelOptInfo *a, RelOptInfo *b) { - /* * We treat RelOptInfos as equal if they refer to the same base rels * joined in the same order. Is this appropriate/sufficient? @@ -362,7 +360,6 @@ _equalRelOptInfo(RelOptInfo *a, RelOptInfo *b) static bool _equalIndexOptInfo(IndexOptInfo *a, IndexOptInfo *b) { - /* * We treat IndexOptInfos as equal if they refer to the same index. Is * this sufficient? @@ -515,11 +512,12 @@ _equalRestrictInfo(RestrictInfo *a, RestrictInfo *b) return false; if (a->ispusheddown != b->ispusheddown) return false; + /* * We ignore eval_cost, this_selec, 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 ... + * derivable from the clause anyway. Probably it's not really + * necessary to compare any of these remaining fields ... */ if (!equal(a->subclauseindices, b->subclauseindices)) return false; @@ -622,9 +620,9 @@ _equalQuery(Query *a, Query *b) /* * We do not check the internal-to-the-planner 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; } @@ -773,7 +771,7 @@ _equalPrivGrantee(PrivGrantee *a, PrivGrantee *b) { return equalstr(a->username, b->username) && equalstr(a->groupname, b->groupname); -} +} static bool _equalClosePortalStmt(ClosePortalStmt *a, ClosePortalStmt *b) diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c index 42dd9a2dab..94b18d3752 100644 --- a/src/backend/nodes/nodeFuncs.c +++ b/src/backend/nodes/nodeFuncs.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/nodeFuncs.c,v 1.14 2001/03/22 03:59:32 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/nodeFuncs.c,v 1.15 2001/10/25 05:49:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -70,7 +70,7 @@ bool var_is_rel(Var *var) { return (bool) - !(var_is_inner(var) || var_is_outer(var)); + !(var_is_inner(var) || var_is_outer(var)); } /***************************************************************************** @@ -114,5 +114,4 @@ non_null(Expr *c) else return false; } - #endif diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c index 5b30fd2a21..417082b39b 100644 --- a/src/backend/nodes/outfuncs.c +++ b/src/backend/nodes/outfuncs.c @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/nodes/outfuncs.c,v 1.145 2001/08/21 16:36:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/outfuncs.c,v 1.146 2001/10/25 05:49:31 momjian Exp $ * * NOTES * Every (plan) node in POSTGRES has an associated "out" routine which @@ -218,7 +218,6 @@ _outQuery(StringInfo str, Query *node) if (node->utilityStmt) { - /* * Hack to make up for lack of outfuncs for utility-stmt nodes */ @@ -1271,7 +1270,7 @@ _outValue(StringInfo str, Value *value) { switch (value->type) { - case T_Integer: + case T_Integer: appendStringInfo(str, " %ld ", value->val.ival); break; case T_Float: diff --git a/src/backend/nodes/print.c b/src/backend/nodes/print.c index 9834769562..0e33a99d53 100644 --- a/src/backend/nodes/print.c +++ b/src/backend/nodes/print.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/print.c,v 1.48 2001/10/18 16:11:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/print.c,v 1.49 2001/10/25 05:49:31 momjian Exp $ * * HISTORY * AUTHOR DATE MAJOR EVENT @@ -215,7 +215,7 @@ print_expr(Node *expr, List *rtable) outputstr = DatumGetCString(OidFunctionCall3(typoutput, c->constvalue, - ObjectIdGetDatum(typelem), + ObjectIdGetDatum(typelem), Int32GetDatum(-1))); printf("%s", outputstr); pfree(outputstr); @@ -322,7 +322,7 @@ plannode_type(Plan *p) { switch (nodeTag(p)) { - case T_Plan: + case T_Plan: return "PLAN"; case T_Result: return "RESULT"; diff --git a/src/backend/nodes/read.c b/src/backend/nodes/read.c index 14a492b476..3a09732255 100644 --- a/src/backend/nodes/read.c +++ b/src/backend/nodes/read.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/read.c,v 1.30 2001/03/22 17:41:47 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/read.c,v 1.31 2001/10/25 05:49:31 momjian Exp $ * * HISTORY * AUTHOR DATE MAJOR EVENT @@ -220,17 +220,17 @@ nodeTokenType(char *token, int length) * us. We know the token will end at a character that strtol will * stop at, so we do not need to modify the string. */ - long val; - char *endptr; + long val; + char *endptr; errno = 0; val = strtol(token, &endptr, 10); if (endptr != token + length || errno == ERANGE #ifdef HAVE_LONG_INT_64 - /* if long > 32 bits, check for overflow of int4 */ + /* if long > 32 bits, check for overflow of int4 */ || val != (long) ((int32) val) #endif - ) + ) return T_Float; return T_Integer; } diff --git a/src/backend/nodes/readfuncs.c b/src/backend/nodes/readfuncs.c index b3e3105da6..26fbebea77 100644 --- a/src/backend/nodes/readfuncs.c +++ b/src/backend/nodes/readfuncs.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/nodes/readfuncs.c,v 1.112 2001/07/03 16:52:48 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/nodes/readfuncs.c,v 1.113 2001/10/25 05:49:31 momjian Exp $ * * NOTES * Most of the read functions for plan nodes are tested. (In fact, they @@ -129,7 +129,6 @@ _readQuery(void) local_node->utilityStmt = NULL; else { - /* * Hack to make up for lack of readfuncs for utility-stmt nodes * @@ -868,8 +867,8 @@ _readCaseWhen(void) static NullTest * _readNullTest(void) { - NullTest *local_node; - char *token; + NullTest *local_node; + char *token; int length; local_node = makeNode(NullTest); @@ -893,8 +892,8 @@ _readNullTest(void) static BooleanTest * _readBooleanTest(void) { - BooleanTest *local_node; - char *token; + BooleanTest *local_node; + char *token; int length; local_node = makeNode(BooleanTest); diff --git a/src/backend/optimizer/geqo/geqo_erx.c b/src/backend/optimizer/geqo/geqo_erx.c index 576ff5daa0..748f3f31df 100644 --- a/src/backend/optimizer/geqo/geqo_erx.c +++ b/src/backend/optimizer/geqo/geqo_erx.c @@ -3,7 +3,7 @@ * geqo_erx.c * edge recombination crossover [ER] * -* $Id: geqo_erx.c,v 1.15 1999/07/16 04:59:08 momjian Exp $ +* $Id: geqo_erx.c,v 1.16 2001/10/25 05:49:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -110,7 +110,6 @@ gimme_edge_table(Gene *tour1, Gene *tour2, int num_gene, Edge *edge_table) for (index1 = 0; index1 < num_gene; index1++) { - /* * presume the tour is circular, i.e. 1->2, 2->3, 3->1 this * operaton maps n back to 1 @@ -201,7 +200,6 @@ gimme_tour(Edge *edge_table, Gene *new_gene, int num_gene) for (i = 1; i < num_gene; i++) { - /* * as each point is entered into the tour, remove it from the edge * table diff --git a/src/backend/optimizer/geqo/geqo_main.c b/src/backend/optimizer/geqo/geqo_main.c index 61543985c5..496207d2a8 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-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: geqo_main.c,v 1.28 2001/06/03 14:53:56 petere Exp $ + * $Id: geqo_main.c,v 1.29 2001/10/25 05:49:31 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -82,16 +82,13 @@ geqo(Query *root, int number_of_rels, List *initial_rels) Edge *edge_table; /* list of edges */ int edge_failures = 0; float difference; - #endif #if defined(CX) || defined(PX) || defined(OX1) || defined(OX2) City *city_table; /* list of cities */ - #endif #if defined(CX) int cycle_diffs = 0; int mutations = 0; - #endif /* set GA parameters */ diff --git a/src/backend/optimizer/path/_deadcode/predmig.c b/src/backend/optimizer/path/_deadcode/predmig.c index 462f1dc24e..604de4b273 100644 --- a/src/backend/optimizer/path/_deadcode/predmig.c +++ b/src/backend/optimizer/path/_deadcode/predmig.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/_deadcode/Attic/predmig.c,v 1.10 2001/03/22 06:16:14 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/_deadcode/Attic/predmig.c,v 1.11 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -244,7 +244,6 @@ xfunc_llel_chains(Stream root, Stream bottom) if (is_clause(tmpstream) && get_pathptr(pathstream) != get_pathptr(tmpstream)) { - /* * * If restriction moved above a Join after sort, we pull it * * up in the join plan. * If restriction moved down, we @@ -470,7 +469,7 @@ xfunc_form_groups(Query *queryInfo, Stream root, Stream bottom) get_groupup((Stream) get_downstream(temp))) && get_grouprank(parent) < get_grouprank(temp)) { - progress = true;/* we formed a new group */ + progress = true; /* we formed a new group */ set_groupup(temp, true); set_groupcost(temp, get_groupcost(temp) + @@ -485,7 +484,7 @@ xfunc_form_groups(Query *queryInfo, Stream root, Stream bottom) } -/* ------------------- UTILITY FUNCTIONS ------------------------- */ +/* ------------------- UTILITY FUNCTIONS ------------------------- */ /* ** xfunc_free_stream diff --git a/src/backend/optimizer/path/_deadcode/xfunc.c b/src/backend/optimizer/path/_deadcode/xfunc.c index 82258d7baf..07866a9e4d 100644 --- a/src/backend/optimizer/path/_deadcode/xfunc.c +++ b/src/backend/optimizer/path/_deadcode/xfunc.c @@ -10,7 +10,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/_deadcode/Attic/xfunc.c,v 1.16 2001/03/22 06:16:14 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/_deadcode/Attic/xfunc.c,v 1.17 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -237,7 +237,6 @@ xfunc_shouldpull(Query *queryInfo, } else if (maxrank != -(MAXFLOAT)) { - /* * * we've left an expensive restriction below a join. Since * * we may pullup this restriction in predmig.c, we'd best * @@ -656,7 +655,6 @@ xfunc_width(LispValue clause) } else if (IsA(clause, Iter)) { - /* * * An Iter returns a setof things, so return the width of a * single * thing. * Note: THIS MAY NOT WORK RIGHT WHEN AGGS GET @@ -668,7 +666,6 @@ xfunc_width(LispValue clause) } else if (fast_is_clause(clause)) { - /* * * get function associated with this Oper, and treat this as * a * Func @@ -689,7 +686,6 @@ xfunc_width(LispValue clause) if (get_func_tlist(func) != LispNil) { - /* * this function has a projection on it. Get the length of * the projected attribute @@ -1150,7 +1146,6 @@ xfunc_fixvars(LispValue clause, /* clause being pulled up */ tle = tlistentry_member((Var) clause, get_targetlist(rel)); if (tle == LispNil) { - /* * * The attribute we need is not in the target list, * so we * have to add it. * diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index ebc303d465..15f29847d3 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.79 2001/10/18 16:11:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/allpaths.c,v 1.80 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -38,10 +38,10 @@ static void set_base_rel_pathlists(Query *root); static void set_plain_rel_pathlist(Query *root, RelOptInfo *rel, RangeTblEntry *rte); static void set_inherited_rel_pathlist(Query *root, RelOptInfo *rel, - Index rti, RangeTblEntry *rte, - List *inheritlist); + Index rti, RangeTblEntry *rte, + List *inheritlist); static void set_subquery_pathlist(Query *root, RelOptInfo *rel, - Index rti, RangeTblEntry *rte); + Index rti, RangeTblEntry *rte); static RelOptInfo *make_one_rel_by_joins(Query *root, int levels_needed, List *initial_rels); @@ -160,7 +160,7 @@ set_plain_rel_pathlist(Query *root, RelOptInfo *rel, RangeTblEntry *rte) * Build access paths for a inheritance tree rooted at rel * * inheritlist is a list of RT indexes of all tables in the inheritance tree, - * including a duplicate of the parent itself. Note we will not come here + * including a duplicate of the parent itself. Note we will not come here * unless there's at least one child in addition to the parent. * * NOTE: the passed-in rel and RTE will henceforth represent the appended @@ -192,9 +192,9 @@ set_inherited_rel_pathlist(Query *root, RelOptInfo *rel, elog(ERROR, "SELECT FOR UPDATE is not supported for inherit queries"); /* - * The executor will check the parent table's access permissions when it - * examines the parent's inheritlist entry. There's no need to check - * twice, so turn off access check bits in the original RTE. + * The executor will check the parent table's access permissions when + * it examines the parent's inheritlist entry. There's no need to + * check twice, so turn off access check bits in the original RTE. */ rte->checkForRead = false; rte->checkForWrite = false; @@ -230,8 +230,8 @@ set_inherited_rel_pathlist(Query *root, RelOptInfo *rel, /* * Copy the parent's targetlist and restriction quals to the * child, with attribute-number adjustment as needed. We don't - * bother to copy the join quals, since we can't do any joining - * of the individual tables. + * bother to copy the join quals, since we can't do any joining of + * the individual tables. */ childrel->targetlist = (List *) adjust_inherited_attrs((Node *) rel->targetlist, @@ -282,32 +282,32 @@ set_subquery_pathlist(Query *root, RelOptInfo *rel, /* * If there are any restriction clauses that have been attached to the - * subquery relation, consider pushing them down to become HAVING quals - * of the subquery itself. (Not WHERE clauses, since they may refer to - * subquery outputs that are aggregate results. But planner.c will - * transfer them into the subquery's WHERE if they do not.) This - * transformation is useful because it may allow us to generate a better - * plan for the subquery than evaluating all the subquery output rows - * and then filtering them. + * subquery relation, consider pushing them down to become HAVING + * quals of the subquery itself. (Not WHERE clauses, since they may + * refer to subquery outputs that are aggregate results. But + * planner.c will transfer them into the subquery's WHERE if they do + * not.) This transformation is useful because it may allow us to + * generate a better plan for the subquery than evaluating all the + * subquery output rows and then filtering them. * * There are several cases where we cannot push down clauses: * * 1. If the subquery contains set ops (UNION/INTERSECT/EXCEPT) we do not - * push down any qual clauses, since the planner doesn't support quals at - * the top level of a setop. (With suitable analysis we could try to push - * the quals down into the component queries of the setop, but getting it - * right seems nontrivial. Work on this later.) + * push down any qual clauses, since the planner doesn't support quals + * at the top level of a setop. (With suitable analysis we could try + * to push the quals down into the component queries of the setop, but + * getting it right seems nontrivial. Work on this later.) * * 2. If the subquery has a LIMIT clause or a DISTINCT ON clause, we must * not push down any quals, since that could change the set of rows * returned. (Actually, we could push down quals into a DISTINCT ON - * subquery if they refer only to DISTINCT-ed output columns, but checking - * that seems more work than it's worth. In any case, a plain DISTINCT is - * safe to push down past.) + * subquery if they refer only to DISTINCT-ed output columns, but + * checking that seems more work than it's worth. In any case, a + * plain DISTINCT is safe to push down past.) * * 3. We do not push down clauses that contain subselects, mainly because - * I'm not sure it will work correctly (the subplan hasn't yet transformed - * sublinks to subselects). + * I'm not sure it will work correctly (the subplan hasn't yet + * transformed sublinks to subselects). * * Non-pushed-down clauses will get evaluated as qpquals of the * SubqueryScan node. @@ -337,22 +337,23 @@ set_subquery_pathlist(Query *root, RelOptInfo *rel, else { /* - * We need to replace Vars in the clause (which must refer to - * outputs of the subquery) with copies of the subquery's - * targetlist expressions. Note that at this point, any - * uplevel Vars in the clause should have been replaced with - * Params, so they need no work. + * We need to replace Vars in the clause (which must refer + * to outputs of the subquery) with copies of the + * subquery's targetlist expressions. Note that at this + * point, any uplevel Vars in the clause should have been + * replaced with Params, so they need no work. */ clause = ResolveNew(clause, rti, 0, subquery->targetList, CMD_SELECT, 0); subquery->havingQual = make_and_qual(subquery->havingQual, clause); + /* * We need not change the subquery's hasAggs or - * hasSublinks flags, since we can't be pushing - * down any aggregates that weren't there before, - * and we don't push down subselects at all. + * hasSublinks flags, since we can't be pushing down any + * aggregates that weren't there before, and we don't push + * down subselects at all. */ } } @@ -412,7 +413,6 @@ make_fromexpr_rel(Query *root, FromExpr *from) if (levels_needed == 1) { - /* * Single jointree node, so we're done. */ @@ -420,7 +420,6 @@ make_fromexpr_rel(Query *root, FromExpr *from) } else { - /* * Consider the different orders in which we could join the rels, * using either GEQO or regular optimizer. @@ -552,7 +551,7 @@ print_restrictclauses(Query *root, List *clauses) static void print_path(Query *root, Path *path, int indent) { - const char *ptype; + const char *ptype; bool join; int i; @@ -650,7 +649,7 @@ debug_print_rel(Query *root, RelOptInfo *rel) foreach(l, rel->joininfo) { - JoinInfo *j = (JoinInfo *) lfirst(l); + JoinInfo *j = (JoinInfo *) lfirst(l); printf("\tjoininfo ("); print_relids(j->unjoined_relids); @@ -669,5 +668,4 @@ debug_print_rel(Query *root, RelOptInfo *rel) printf("\n"); fflush(stdout); } - #endif /* OPTIMIZER_DEBUG */ diff --git a/src/backend/optimizer/path/clausesel.c b/src/backend/optimizer/path/clausesel.c index 36d8f229f1..fc509c4d94 100644 --- a/src/backend/optimizer/path/clausesel.c +++ b/src/backend/optimizer/path/clausesel.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/clausesel.c,v 1.46 2001/06/25 21:11:43 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/clausesel.c,v 1.47 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -48,7 +48,7 @@ typedef struct RangeQueryClause } RangeQueryClause; static void addRangeClause(RangeQueryClause **rqlist, Node *clause, - bool varonleft, bool isLTsel, Selectivity s2); + bool varonleft, bool isLTsel, Selectivity s2); /**************************************************************************** @@ -212,7 +212,6 @@ clauselist_selectivity(Query *root, { if (s2 < -0.01) { - /* * No data available --- use a default estimate that * is small, but not real small. @@ -221,7 +220,6 @@ clauselist_selectivity(Query *root, } else { - /* * It's just roundoff error; use a small positive * value @@ -275,7 +273,6 @@ addRangeClause(RangeQueryClause **rqlist, Node *clause, for (rqelem = *rqlist; rqelem; rqelem = rqelem->next) { - /* * We use full equal() here because the "var" might be a function * of one or more attributes of the same relation... @@ -386,7 +383,6 @@ clause_selectivity(Query *root, if (rte->subquery) { - /* * XXX not smart about subquery references... any way to * do better? @@ -395,7 +391,6 @@ clause_selectivity(Query *root, } else { - /* * A Var at the top of a clause must be a bool Var. This * is equivalent to the clause reln.attribute = 't', so we @@ -405,7 +400,7 @@ clause_selectivity(Query *root, BooleanEqualOperator, makeList2(var, MAKEBOOLCONST(true, - false)), + false)), varRelid); } } @@ -436,7 +431,6 @@ clause_selectivity(Query *root, } else if (or_clause(clause)) { - /* * Selectivities for an 'or' clause are computed as s1+s2 - s1*s2 * to account for the probable overlap of selected tuple sets. XXX @@ -461,7 +455,6 @@ clause_selectivity(Query *root, if (varRelid != 0) { - /* * If we are considering a nestloop join then all clauses are * restriction clauses, since we are only interested in the @@ -471,7 +464,6 @@ clause_selectivity(Query *root, } else { - /* * Otherwise, it's a join if there's more than one relation * used. @@ -482,19 +474,18 @@ clause_selectivity(Query *root, if (is_join_clause) { /* Estimate selectivity for a join clause. */ - s1 = join_selectivity(root, opno, + s1 = join_selectivity(root, opno, ((Expr *) clause)->args); } else { /* Estimate selectivity for a restriction clause. */ - s1 = restriction_selectivity(root, opno, - ((Expr *) clause)->args, varRelid); + s1 = restriction_selectivity(root, opno, + ((Expr *) clause)->args, varRelid); } } else if (is_funcclause(clause)) { - /* * This is not an operator, so we guess at the selectivity. THIS * IS A HACK TO GET V4 OUT THE DOOR. FUNCS SHOULD BE ABLE TO HAVE @@ -504,7 +495,6 @@ clause_selectivity(Query *root, } else if (is_subplan(clause)) { - /* * Just for the moment! FIX ME! - vadim 02/04/98 */ diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c index 73d72a03cb..4cfddf9e6c 100644 --- a/src/backend/optimizer/path/costsize.c +++ b/src/backend/optimizer/path/costsize.c @@ -42,7 +42,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.78 2001/08/21 16:36:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.79 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -271,10 +271,10 @@ cost_index(Path *path, Query *root, * * When the index ordering is exactly correlated with the table ordering * (just after a CLUSTER, for example), the number of pages fetched should - * be just sT. What's more, these will be sequential fetches, not the - * random fetches that occur in the uncorrelated case. So, depending on + * be just sT. What's more, these will be sequential fetches, not the + * random fetches that occur in the uncorrelated case. So, depending on * the extent of correlation, we should estimate the actual I/O cost - * somewhere between s * T * 1.0 and PF * random_cost. We currently + * somewhere between s * T * 1.0 and PF * random_cost. We currently * interpolate linearly between these two endpoints based on the * correlation squared (XXX is that appropriate?). * @@ -301,7 +301,7 @@ cost_index(Path *path, Query *root, } else { - double lim; + double lim; lim = (2.0 * T * b) / (2.0 * T - b); if (tuples_fetched <= lim) @@ -317,18 +317,19 @@ cost_index(Path *path, Query *root, } /* - * min_IO_cost corresponds to the perfectly correlated case (csquared=1), - * max_IO_cost to the perfectly uncorrelated case (csquared=0). Note - * that we just charge random_page_cost per page in the uncorrelated - * case, rather than using cost_nonsequential_access, since we've already - * accounted for caching effects by using the Mackert model. + * min_IO_cost corresponds to the perfectly correlated case + * (csquared=1), max_IO_cost to the perfectly uncorrelated case + * (csquared=0). Note that we just charge random_page_cost per page + * in the uncorrelated case, rather than using + * cost_nonsequential_access, since we've already accounted for + * caching effects by using the Mackert model. */ min_IO_cost = ceil(indexSelectivity * T); max_IO_cost = pages_fetched * random_page_cost; /* - * Now interpolate based on estimated index order correlation - * to get total disk I/O cost for main table accesses. + * Now interpolate based on estimated index order correlation to get + * total disk I/O cost for main table accesses. */ csquared = indexCorrelation * indexCorrelation; @@ -337,14 +338,14 @@ cost_index(Path *path, Query *root, /* * Estimate CPU costs per tuple. * - * 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. 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. Also, 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. + * 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. 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. + * Also, 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. */ cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost; @@ -501,11 +502,11 @@ cost_nestloop(Path *path, Query *root, /* * NOTE: clearly, we must pay both outer and inner paths' startup_cost - * 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 + * 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, but probably - * is true otherwise. Since we don't yet have clean handling of the + * This is not true if the inner path is materialized, but probably is + * true otherwise. Since we don't yet have clean handling of the * decision whether to materialize a path, we can't tell here which * will happen. As a compromise, charge 50% of the inner startup cost * for each restart. @@ -615,9 +616,9 @@ cost_mergejoin(Path *path, Query *root, /* * The number of tuple comparisons needed depends drastically on the * number of equal keys in the two source relations, which we have no - * good way of estimating. Somewhat arbitrarily, we charge one - * tuple comparison (one cpu_operator_cost) for each tuple in the - * two source relations. This is probably a lower bound. + * good way of estimating. Somewhat arbitrarily, we charge one tuple + * comparison (one cpu_operator_cost) for each tuple in the two source + * relations. This is probably a lower bound. */ run_cost += cpu_operator_cost * (outer_path->parent->rows + inner_path->parent->rows); @@ -625,7 +626,7 @@ cost_mergejoin(Path *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. It's OK to use an + * clauses that are to be applied at the join. It's OK to use an * approximate selectivity here, since in most cases this is a minor * component of the cost. */ @@ -685,8 +686,8 @@ cost_hashjoin(Path *path, Query *root, run_cost += cpu_operator_cost * outer_path->parent->rows; /* - * Determine bucketsize fraction for inner relation. First we have - * to figure out which side of the hashjoin clause is the inner side. + * Determine bucketsize fraction for inner relation. First we have to + * figure out which side of the hashjoin clause is the inner side. */ Assert(length(hashclauses) == 1); Assert(IsA(lfirst(hashclauses), RestrictInfo)); @@ -696,9 +697,9 @@ cost_hashjoin(Path *path, Query *root, right = get_rightop(restrictinfo->clause); /* - * 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. + * 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. */ if (intMember(right->varno, inner_path->parent->relids)) { @@ -726,9 +727,9 @@ cost_hashjoin(Path *path, Query *root, /* * The number of tuple comparisons needed is the number of outer - * tuples times the typical number of tuples in a hash bucket, - * which is the inner relation size times its bucketsize fraction. - * We charge one cpu_operator_cost per tuple comparison. + * tuples times the typical number of tuples in a hash bucket, which + * is the inner relation size times its bucketsize fraction. We charge + * one cpu_operator_cost per tuple comparison. */ run_cost += cpu_operator_cost * outer_path->parent->rows * ceil(inner_path->parent->rows * innerbucketsize); @@ -736,7 +737,7 @@ cost_hashjoin(Path *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. It's OK to use an + * clauses that are to be applied at the join. It's OK to use an * approximate selectivity here, since in most cases this is a minor * component of the cost. */ @@ -792,11 +793,11 @@ cost_hashjoin(Path *path, Query *root, * distribution, so this will have to do for now. * * We can get the number of buckets the executor will use for the given - * input relation. If the data were perfectly distributed, with the same + * input relation. If the data were perfectly distributed, with the same * number of tuples going into each available bucket, then the bucketsize * fraction would be 1/nbuckets. But this happy state of affairs will occur * only if (a) there are at least nbuckets distinct data values, and (b) - * we have a not-too-skewed data distribution. Otherwise the buckets will + * we have a not-too-skewed data distribution. Otherwise the buckets will * be nonuniformly occupied. If the other relation in the join has a key * distribution similar to this one's, then the most-loaded buckets are * exactly those that will be probed most often. Therefore, the "average" @@ -828,8 +829,8 @@ estimate_hash_bucketsize(Query *root, Var *var) int nnumbers; /* - * Lookup info about var's relation and attribute; - * if none available, return default estimate. + * Lookup info about var's relation and attribute; if none available, + * return default estimate. */ if (!IsA(var, Var)) return 0.1; @@ -891,12 +892,13 @@ estimate_hash_bucketsize(Query *root, Var *var) avgfreq = (1.0 - stats->stanullfrac) / ndistinct; /* - * Adjust ndistinct to account for restriction clauses. Observe we are - * assuming that the data distribution is affected uniformly by the - * restriction clauses! + * Adjust ndistinct to account for restriction clauses. Observe we + * are assuming that the data distribution is affected uniformly by + * the restriction clauses! * * XXX Possibly better way, but much more expensive: multiply by - * selectivity of rel's restriction clauses that mention the target Var. + * selectivity of rel's restriction clauses that mention the target + * Var. */ ndistinct *= rel->rows / rel->tuples; @@ -929,7 +931,8 @@ estimate_hash_bucketsize(Query *root, Var *var) } /* - * Adjust estimated bucketsize upward to account for skewed distribution. + * Adjust estimated bucketsize upward to account for skewed + * distribution. */ if (avgfreq > 0.0 && mcvfreq > avgfreq) estfract *= mcvfreq / avgfreq; @@ -1084,19 +1087,20 @@ cost_qual_eval_walker(Node *node, Cost *total) static Selectivity approx_selectivity(Query *root, List *quals) { - Selectivity total = 1.0; + Selectivity total = 1.0; List *l; foreach(l, quals) { Node *qual = (Node *) lfirst(l); - Selectivity selec; + Selectivity selec; /* * RestrictInfo nodes contain a this_selec field reserved for this * routine's use, so that it's not necessary to evaluate the qual - * clause's selectivity more than once. If the clause's selectivity - * hasn't been computed yet, the field will contain -1. + * clause's selectivity more than once. If the clause's + * selectivity hasn't been computed yet, the field will contain + * -1. */ if (qual && IsA(qual, RestrictInfo)) { @@ -1254,7 +1258,7 @@ set_joinrel_size_estimates(Query *root, RelOptInfo *rel, * NB: this works best on base relations because it prefers to look at * real Vars. It will fail to make use of pg_statistic info when applied * to a subquery relation, even if the subquery outputs are simple vars - * that we could have gotten info for. Is it worth trying to be smarter + * that we could have gotten info for. Is it worth trying to be smarter * about subqueries? */ static void @@ -1266,15 +1270,15 @@ set_rel_width(Query *root, RelOptInfo *rel) foreach(tllist, rel->targetlist) { TargetEntry *tle = (TargetEntry *) lfirst(tllist); - int32 item_width; + int32 item_width; /* * If it's a Var, try to get statistical info from pg_statistic. */ if (tle->expr && IsA(tle->expr, Var)) { - Var *var = (Var *) tle->expr; - Oid relid; + Var *var = (Var *) tle->expr; + Oid relid; relid = getrelid(var->varno, root->rtable); if (relid != InvalidOid) @@ -1287,6 +1291,7 @@ set_rel_width(Query *root, RelOptInfo *rel) } } } + /* * Not a Var, or can't find statistics for it. Estimate using * just the type info. diff --git a/src/backend/optimizer/path/indxpath.c b/src/backend/optimizer/path/indxpath.c index f30097ec28..71e6c3faf5 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.111 2001/08/21 16:36:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/indxpath.c,v 1.112 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -288,7 +288,6 @@ match_index_orclauses(RelOptInfo *rel, if (restriction_is_or_clause(restrictinfo)) { - /* * Add this index to the subclause index list for each * subclause that it matches. @@ -444,9 +443,10 @@ extract_or_indexqual_conditions(RelOptInfo *rel, Oid *classes = index->classlist; /* - * Extract relevant indexclauses in indexkey order. This is essentially - * just like group_clauses_by_indexkey() except that the input and - * output are lists of bare clauses, not of RestrictInfo nodes. + * Extract relevant indexclauses in indexkey order. This is + * essentially just like group_clauses_by_indexkey() except that the + * input and output are lists of bare clauses, not of RestrictInfo + * nodes. */ do { @@ -459,7 +459,7 @@ extract_or_indexqual_conditions(RelOptInfo *rel, { foreach(item, orsubclause->args) { - Expr *subsubclause = (Expr *) lfirst(item); + Expr *subsubclause = (Expr *) lfirst(item); if (match_clause_to_indexkey(rel, index, curIndxKey, curClass, @@ -470,9 +470,7 @@ extract_or_indexqual_conditions(RelOptInfo *rel, else if (match_clause_to_indexkey(rel, index, curIndxKey, curClass, orsubclause, false)) - { clausegroup = makeList1(orsubclause); - } /* * If we found no clauses for this indexkey in the OR subclause @@ -492,8 +490,8 @@ extract_or_indexqual_conditions(RelOptInfo *rel, } /* - * If still no clauses match this key, we're done; we don't want to - * look at keys to its right. + * If still no clauses match this key, we're done; we don't want + * to look at keys to its right. */ if (clausegroup == NIL) break; @@ -744,7 +742,6 @@ match_clause_to_indexkey(RelOptInfo *rel, if (!join) { - /* * Not considering joins, so check for clauses of the form: * (indexkey operator constant) or (constant operator indexkey). @@ -782,7 +779,6 @@ match_clause_to_indexkey(RelOptInfo *rel, } else { - /* * Check for an indexqual that could be handled by a nestloop * join. We need the index key to be compared against an @@ -921,7 +917,6 @@ indexable_operator(Expr *clause, Oid opclass, bool indexkey_on_left) { if (new_op != expr_op) { - /* * OK, we found a binary-compatible operator of the same name; * now does it match the index? @@ -1144,7 +1139,7 @@ static const StrategyNumber * and a "simple clause" restriction. * * We have two strategies for determining whether one simple clause - * implies another. A simple and general way is to see if they are + * implies another. A simple and general way is to see if they are * equal(); this works for any kind of expression. (Actually, there * is an implied assumption that the functions in the expression are * cachable, ie dependent only on their input arguments --- but this @@ -1187,8 +1182,8 @@ pred_test_simple_clause(Expr *predicate, Node *clause) return true; /* - * Can't do anything more unless they are both binary opclauses with - * a Var on the left and a Const on the right. + * Can't do anything more unless they are both binary opclauses with a + * Var on the left and a Const on the right. */ if (!is_opclause((Node *) predicate)) return false; @@ -1223,8 +1218,8 @@ pred_test_simple_clause(Expr *predicate, Node *clause) /* * 1. Find a "btree" strategy number for the pred_op * - * The following assumes that any given operator will only be in a - * single btree operator class. This is true at least for all the + * The following assumes that any given operator will only be in a single + * btree operator class. This is true at least for all the * pre-defined operator classes. If it isn't true, then whichever * operator class happens to be returned first for the given operator * will be used to find the associated strategy numbers for the test. @@ -1237,7 +1232,7 @@ pred_test_simple_clause(Expr *predicate, Node *clause) relation = heap_openr(AccessMethodOperatorRelationName, AccessShareLock); scan = heap_beginscan(relation, false, SnapshotNow, 1, entry); - + while (HeapTupleIsValid(tuple = heap_getnext(scan, 0))) { aform = (Form_pg_amop) GETSTRUCT(tuple); @@ -1246,7 +1241,11 @@ pred_test_simple_clause(Expr *predicate, Node *clause) /* Get the predicate operator's btree strategy number (1 to 5) */ pred_strategy = (StrategyNumber) aform->amopstrategy; Assert(pred_strategy >= 1 && pred_strategy <= 5); - /* Remember which operator class this strategy number came from */ + + /* + * Remember which operator class this strategy number came + * from + */ opclass_id = aform->amopclaid; break; } @@ -1457,8 +1456,8 @@ index_innerjoin(Query *root, RelOptInfo *rel, IndexOptInfo *index, /* * Note that we are making a pathnode for a single-scan indexscan; - * therefore, both indexinfo and indexqual should be single-element - * lists. + * therefore, both indexinfo and indexqual should be + * single-element lists. */ pathnode->indexinfo = makeList1(index); pathnode->indexqual = makeList1(indexquals); @@ -1516,7 +1515,6 @@ match_index_to_operand(int indexkey, RelOptInfo *rel, IndexOptInfo *index) { - /* * Ignore any RelabelType node above the indexkey. This is needed to * be able to apply indexscanning in binary-compatible-operator cases. @@ -1528,7 +1526,6 @@ match_index_to_operand(int indexkey, if (index->indproc == InvalidOid) { - /* * Simple index. */ @@ -1860,7 +1857,6 @@ expand_indexqual_conditions(List *indexquals) 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 @@ -2065,17 +2061,17 @@ prefix_quals(Var *leftop, Oid expr_op, /* * Given a leftop and a rightop, and a inet-class sup/sub operator, * generate suitable indexqual condition(s). expr_op is the original - * operator. + * operator. */ static List * network_prefix_quals(Var *leftop, Oid expr_op, Datum rightop) { - bool is_eq; - char *opr1name; - Datum opr1right; - Datum opr2right; - Oid opr1oid; - Oid opr2oid; + bool is_eq; + char *opr1name; + Datum opr1right; + Datum opr2right; + Oid opr1oid; + Oid opr2oid; List *result; Oid datatype; Oper *op; @@ -2084,30 +2080,30 @@ network_prefix_quals(Var *leftop, Oid expr_op, Datum rightop) switch (expr_op) { case OID_INET_SUB_OP: - datatype = INETOID; - is_eq = false; + datatype = INETOID; + is_eq = false; break; case OID_INET_SUBEQ_OP: - datatype = INETOID; - is_eq = true; + datatype = INETOID; + is_eq = true; break; case OID_CIDR_SUB_OP: - datatype = CIDROID; - is_eq = false; + datatype = CIDROID; + is_eq = false; break; case OID_CIDR_SUBEQ_OP: - datatype = CIDROID; - is_eq = true; + datatype = CIDROID; + is_eq = true; break; default: elog(ERROR, "network_prefix_quals: unexpected operator %u", expr_op); return NIL; - } + } /* - * create clause "key >= network_scan_first( rightop )", or ">" - * if the operator disallows equality. + * create clause "key >= network_scan_first( rightop )", or ">" if the + * operator disallows equality. */ opr1name = is_eq ? ">=" : ">"; @@ -2116,11 +2112,11 @@ network_prefix_quals(Var *leftop, Oid expr_op, Datum rightop) elog(ERROR, "network_prefix_quals: no %s operator for type %u", opr1name, datatype); - opr1right = network_scan_first( rightop ); + opr1right = network_scan_first(rightop); op = makeOper(opr1oid, InvalidOid, BOOLOID); - expr = make_opclause(op, leftop, - (Var *) makeConst(datatype, -1, opr1right, + expr = make_opclause(op, leftop, + (Var *) makeConst(datatype, -1, opr1right, false, false, false, false)); result = makeList1(expr); @@ -2131,11 +2127,11 @@ network_prefix_quals(Var *leftop, Oid expr_op, Datum rightop) elog(ERROR, "network_prefix_quals: no <= operator for type %u", datatype); - opr2right = network_scan_last( rightop ); + opr2right = network_scan_last(rightop); op = makeOper(opr2oid, InvalidOid, BOOLOID); - expr = make_opclause(op, leftop, - (Var *) makeConst(datatype, -1, opr2right, + expr = make_opclause(op, leftop, + (Var *) makeConst(datatype, -1, opr2right, false, false, false, false)); result = lappend(result, expr); diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index 5a0734224f..15bb56757d 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.65 2001/06/05 05:26:04 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/joinpath.c,v 1.66 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -38,7 +38,6 @@ static void match_unsorted_inner(Query *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, List *restrictlist, List *mergeclause_list, JoinType jointype); - #endif static void hash_inner_and_outer(Query *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, @@ -297,9 +296,9 @@ match_unsorted_outer(Query *root, /* * Nestloop only supports inner and left 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.) + * 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) { @@ -316,7 +315,7 @@ match_unsorted_outer(Query *root, default: elog(ERROR, "match_unsorted_outer: unexpected join type %d", (int) jointype); - nestjoinOK = false; /* keep compiler quiet */ + nestjoinOK = false; /* keep compiler quiet */ useallclauses = false; break; } @@ -350,12 +349,11 @@ match_unsorted_outer(Query *root, if (nestjoinOK) { - /* * Always consider a nestloop join with this outer and * cheapest-total-cost inner. Consider nestloops using the - * cheapest-startup-cost inner as well, and the best - * innerjoin indexpath. + * cheapest-startup-cost inner as well, and the best innerjoin + * indexpath. */ add_path(joinrel, (Path *) create_nestloop_path(root, @@ -494,7 +492,6 @@ match_unsorted_outer(Query *root, /* Found a cheap (or even-cheaper) sorted path */ if (innerpath != cheapest_total_inner) { - /* * Avoid rebuilding clause list if we already made * one; saves memory in big join trees... @@ -526,6 +523,7 @@ match_unsorted_outer(Query *root, } cheapest_startup_inner = innerpath; } + /* * Don't consider truncated sortkeys if we need all clauses. */ @@ -576,7 +574,7 @@ match_unsorted_inner(Query *root, default: elog(ERROR, "match_unsorted_inner: unexpected join type %d", (int) jointype); - useallclauses = false; /* keep compiler quiet */ + useallclauses = false; /* keep compiler quiet */ break; } @@ -673,7 +671,6 @@ match_unsorted_inner(Query *root, } } } - #endif /* diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c index 8c805e0e3e..745a1eb0b5 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.54 2001/10/18 16:11:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/joinrels.c,v 1.55 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -69,7 +69,6 @@ make_rels_by_joins(Query *root, int level, List **joinrels) if (old_rel->joininfo != NIL) { - /* * Note that if all available join clauses for this rel * require more than one other rel, we will fail to make any @@ -84,7 +83,6 @@ make_rels_by_joins(Query *root, int level, List **joinrels) } else { - /* * Oops, we have a relation that is not joined to any other * relation. Cartesian product time. @@ -195,7 +193,6 @@ make_rels_by_joins(Query *root, int level, List **joinrels) */ if (result_rels == NIL) { - /* * This loop is just like the first one, except we always call * make_rels_by_clauseless_joins(). diff --git a/src/backend/optimizer/path/orindxpath.c b/src/backend/optimizer/path/orindxpath.c index 889a3afee1..b713dc8ad8 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.44 2001/06/05 17:13:52 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/orindxpath.c,v 1.45 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -175,7 +175,7 @@ best_or_subclause_indices(Query *root, pathnode->indexinfo = lappend(pathnode->indexinfo, best_indexinfo); pathnode->indexqual = lappend(pathnode->indexqual, best_indexqual); - if (slist == subclauses) /* first scan? */ + if (slist == subclauses)/* first scan? */ pathnode->path.startup_cost = best_startup_cost; pathnode->path.total_cost += best_total_cost; @@ -202,7 +202,7 @@ best_or_subclause_index(Query *root, RelOptInfo *rel, Expr *subclause, List *indices, - IndexOptInfo **retIndexInfo, /* return value */ + IndexOptInfo **retIndexInfo, /* return value */ List **retIndexQual, /* return value */ Cost *retStartupCost, /* return value */ Cost *retTotalCost) /* return value */ diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c index 9e964290e6..c7e13f2850 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.33 2001/10/18 16:11:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/path/pathkeys.c,v 1.34 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -109,7 +109,6 @@ add_equijoined_keys(Query *root, RestrictInfo *restrictinfo) if (item1here || item2here) { - /* * If find both in same equivalence set, no need to do any * more @@ -318,7 +317,7 @@ compare_pathkeys(List *keys1, List *keys2) if (key1 == NIL && key2 == NIL) return PATHKEYS_EQUAL; if (key1 != NIL) - return PATHKEYS_BETTER1;/* key1 is longer */ + return PATHKEYS_BETTER1; /* key1 is longer */ return PATHKEYS_BETTER2; /* key2 is longer */ } @@ -368,7 +367,7 @@ compare_noncanonical_pathkeys(List *keys1, List *keys2) if (key1 == NIL && key2 == NIL) return PATHKEYS_EQUAL; if (key1 != NIL) - return PATHKEYS_BETTER1;/* key1 is longer */ + return PATHKEYS_BETTER1; /* key1 is longer */ return PATHKEYS_BETTER2; /* key2 is longer */ } @@ -382,8 +381,8 @@ pathkeys_contained_in(List *keys1, List *keys2) { switch (compare_pathkeys(keys1, keys2)) { - case PATHKEYS_EQUAL: - case PATHKEYS_BETTER2: + case PATHKEYS_EQUAL: + case PATHKEYS_BETTER2: return true; default: break; @@ -400,8 +399,8 @@ noncanonical_pathkeys_contained_in(List *keys1, List *keys2) { switch (compare_noncanonical_pathkeys(keys1, keys2)) { - case PATHKEYS_EQUAL: - case PATHKEYS_BETTER2: + case PATHKEYS_EQUAL: + case PATHKEYS_BETTER2: return true; default: break; @@ -632,7 +631,6 @@ build_join_pathkeys(Query *root, RelOptInfo *joinrel, List *outer_pathkeys) { - /* * This used to be quite a complex bit of code, but now that all * pathkey sublists start out life canonicalized, we don't have to do diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index 8756fcc020..30ddd8437c 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.109 2001/09/21 04:06:04 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/createplan.c,v 1.110 2001/10/25 05:49:32 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -57,14 +57,14 @@ static HashJoin *create_hashjoin_plan(HashPath *best_path, List *tlist, Plan *outer_plan, List *outer_tlist, Plan *inner_plan, List *inner_tlist); static void fix_indxqual_references(List *indexquals, IndexPath *index_path, - List **fixed_indexquals, - List **recheck_indexquals); + List **fixed_indexquals, + List **recheck_indexquals); static void fix_indxqual_sublist(List *indexqual, int baserelid, - IndexOptInfo *index, - List **fixed_quals, List **recheck_quals); + IndexOptInfo *index, + List **fixed_quals, List **recheck_quals); static Node *fix_indxqual_operand(Node *node, int baserelid, - IndexOptInfo *index, - Oid *opclass); + IndexOptInfo *index, + Oid *opclass); static List *switch_outer(List *clauses); static void copy_path_costsize(Plan *dest, Path *src); static void copy_plan_costsize(Plan *dest, Plan *src); @@ -410,9 +410,9 @@ create_indexscan_plan(Query *root, /* * The qpqual list must contain all restrictions not automatically - * handled by the index. Normally the predicates in the indxqual - * are checked fully by the index, but if the index is "lossy" for - * a particular operator (as signaled by the amopreqcheck flag in + * handled by the index. Normally the predicates in the indxqual are + * checked fully by the index, but if the index is "lossy" for a + * particular operator (as signaled by the amopreqcheck flag in * pg_amop), then we need to double-check that predicate in qpqual, * because the index may return more tuples than match the predicate. * @@ -453,19 +453,19 @@ create_indexscan_plan(Query *root, /* * The executor needs a copy with the indexkey on the left of each - * clause and with index attr numbers substituted for table ones. - * This pass also looks for "lossy" operators. + * clause and with index attr numbers substituted for table ones. This + * pass also looks for "lossy" operators. */ fix_indxqual_references(indxqual, best_path, &fixed_indxqual, &recheck_indxqual); /* - * If there were any "lossy" operators, need to add back the appropriate - * qual clauses to the qpqual. When there is just one indexscan being - * performed (ie, we have simple AND semantics), we can just add the - * lossy clauses themselves to qpqual. If we have OR-of-ANDs, we'd - * better add the entire original indexqual to make sure that the - * semantics are correct. + * If there were any "lossy" operators, need to add back the + * appropriate qual clauses to the qpqual. When there is just one + * indexscan being performed (ie, we have simple AND semantics), we + * can just add the lossy clauses themselves to qpqual. If we have + * OR-of-ANDs, we'd better add the entire original indexqual to make + * sure that the semantics are correct. */ if (recheck_indxqual != NIL) { @@ -589,7 +589,6 @@ create_nestloop_plan(NestPath *best_path, 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 @@ -657,7 +656,6 @@ create_nestloop_plan(NestPath *best_path, } else if (IsA_Join(inner_plan)) { - /* * Materialize the inner join for speed reasons. * @@ -900,7 +898,7 @@ create_hashjoin_plan(HashPath *best_path, * left. (Someday the executor might not need this, but for now it does.) * * If the indexable operator is marked 'amopreqcheck' in pg_amop, then * the index is "lossy" for this operator: it may return more tuples than - * actually satisfy the operator condition. For each such operator, we + * actually satisfy the operator condition. For each such operator, we * must add (the original form of) the indexqual clause to the "qpquals" * of the indexscan node, where the operator will be re-evaluated to * ensure it passes. @@ -922,7 +920,7 @@ create_hashjoin_plan(HashPath *best_path, */ static void fix_indxqual_references(List *indexquals, IndexPath *index_path, - List **fixed_indexquals, List **recheck_indexquals) + List **fixed_indexquals, List **recheck_indexquals) { List *fixed_quals = NIL; List *recheck_quals = NIL; @@ -992,7 +990,7 @@ fix_indxqual_sublist(List *indexqual, int baserelid, IndexOptInfo *index, /* * Check to see if the indexkey is on the right; if so, commute - * the clause. The indexkey should be the side that refers to + * the clause. The indexkey should be the side that refers to * (only) the base relation. */ leftvarnos = pull_varnos((Node *) lfirst(newclause->args)); @@ -1022,8 +1020,8 @@ fix_indxqual_sublist(List *indexqual, int baserelid, IndexOptInfo *index, fixed_qual = lappend(fixed_qual, newclause); /* - * Finally, check to see if index is lossy for this operator. - * If so, add (a copy of) original form of clause to recheck list. + * Finally, check to see if index is lossy for this operator. If + * so, add (a copy of) original form of clause to recheck list. */ if (op_requires_recheck(newopno, opclass)) recheck_qual = lappend(recheck_qual, @@ -1038,7 +1036,6 @@ static Node * fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index, Oid *opclass) { - /* * Remove any binary-compatible relabeling of the indexkey */ @@ -1088,7 +1085,7 @@ fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index, * the returned varattno must be 1. */ Assert(index->indproc != InvalidOid); - Assert(is_funcclause(node)); /* not a very thorough check, but easy */ + Assert(is_funcclause(node)); /* not a very thorough check, but easy */ /* classlist[0] is the only class of a functional index */ *opclass = index->classlist[0]; @@ -1119,7 +1116,6 @@ switch_outer(List *clauses) Assert(op && IsA(op, Var)); if (var_is_outer(op)) { - /* * Duplicate just enough of the structure to allow commuting * the clause without changing the original list. Could use @@ -1899,5 +1895,4 @@ generate_fjoin(List *tlist) return newTlist; return tlist; /* do nothing for now - ay 10/94 */ } - #endif diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index ff2e13ec97..4c7e281866 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.64 2001/10/18 16:11:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/initsplan.c,v 1.65 2001/10/25 05:49:33 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -46,7 +46,7 @@ static void add_join_info_to_rels(Query *root, RestrictInfo *restrictinfo, Relids join_relids); static void add_vars_to_targetlist(Query *root, List *vars); static bool qual_is_redundant(Query *root, RestrictInfo *restrictinfo, - List *restrictlist); + List *restrictlist); static void check_mergejoinable(RestrictInfo *restrictinfo); static void check_hashjoinable(RestrictInfo *restrictinfo); @@ -312,10 +312,10 @@ mark_baserels_for_outer_join(Query *root, Relids rels, Relids outerrels) /* * Presently the executor cannot support FOR UPDATE marking of - * rels appearing on the nullable side of an outer join. - * (It's somewhat unclear what that would mean, anyway: what should - * we mark when a result row is generated from no element of the - * nullable relation?) So, complain if target rel is FOR UPDATE. + * rels appearing on the nullable side of an outer join. (It's + * somewhat unclear what that would mean, anyway: what should we + * mark when a result row is generated from no element of the + * nullable relation?) So, complain if target rel is FOR UPDATE. * It's sufficient to make this check once per rel, so do it only * if rel wasn't already known nullable. */ @@ -411,9 +411,9 @@ distribute_qual_to_rels(Query *root, Node *clause, * outerjoinset list of each baserel will show exactly those outer * joins that are below the qual in the join tree. * - * If the qual came from implied-equality deduction, we can evaluate - * the qual at its natural semantic level. - * + * If the qual came from implied-equality deduction, we can evaluate the + * qual at its natural semantic level. + * */ if (isdeduced) { @@ -488,12 +488,13 @@ distribute_qual_to_rels(Query *root, Node *clause, /* * 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.) + * 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)) @@ -537,7 +538,6 @@ distribute_qual_to_rels(Query *root, Node *clause, } else { - /* * 'clause' references no rels, and therefore we have no place to * attach it. Shouldn't get here if callers are working properly. @@ -551,8 +551,8 @@ distribute_qual_to_rels(Query *root, Node *clause, * the two sides represent equivalent PathKeyItems for path keys: any * path that is sorted by one side will also be sorted by the other * (as soon as the two rels are joined, that is). Record the key - * equivalence for future use. (We can skip this for a deduced clause, - * since the keys are already known equivalent in that case.) + * equivalence for future use. (We can skip this for a deduced + * clause, since the keys are already known equivalent in that case.) */ if (can_be_equijoin && restrictinfo->mergejoinoperator != InvalidOid && !isdeduced) @@ -681,7 +681,6 @@ process_implied_equality(Query *root, Node *item1, Node *item2, eq_operator = compatible_oper("=", ltype, rtype, true); if (!HeapTupleIsValid(eq_operator)) { - /* * Would it be safe to just not add the equality to the query if * we have no suitable equality operator for the combination of @@ -735,12 +734,12 @@ qual_is_redundant(Query *root, RestrictInfo *restrictinfo, List *restrictlist) { - List *oldquals; - List *olditem; - Node *newleft; - Node *newright; - List *equalvars; - bool someadded; + List *oldquals; + List *olditem; + Node *newleft; + Node *newright; + List *equalvars; + bool someadded; /* * Set cached pathkeys. NB: it is okay to do this now because this @@ -752,6 +751,7 @@ qual_is_redundant(Query *root, /* If different, say "not redundant" (should never happen) */ if (restrictinfo->left_pathkey != restrictinfo->right_pathkey) return false; + /* * Scan existing quals to find those referencing same pathkeys. * Usually there will be few, if any, so build a list of just the @@ -772,24 +772,26 @@ qual_is_redundant(Query *root, } if (oldquals == NIL) return false; + /* * Now, we want to develop a list of Vars that are known equal to the - * left side of the new qual. We traverse the old-quals list repeatedly - * to transitively expand the Vars list. If at any point we find we - * can reach the right-side Var of the new qual, we are done. We give - * up when we can't expand the equalvars list any more. + * left side of the new qual. We traverse the old-quals list + * repeatedly to transitively expand the Vars list. If at any point + * we find we can reach the right-side Var of the new qual, we are + * done. We give up when we can't expand the equalvars list any more. */ newleft = (Node *) get_leftop(restrictinfo->clause); newright = (Node *) get_rightop(restrictinfo->clause); equalvars = makeList1(newleft); - do { + do + { someadded = false; foreach(olditem, oldquals) { RestrictInfo *oldrinfo = (RestrictInfo *) lfirst(olditem); - Node *oldleft = (Node *) get_leftop(oldrinfo->clause); - Node *oldright = (Node *) get_rightop(oldrinfo->clause); - Node *newguy = NULL; + Node *oldleft = (Node *) get_leftop(oldrinfo->clause); + Node *oldright = (Node *) get_rightop(oldrinfo->clause); + Node *newguy = NULL; if (member(oldleft, equalvars)) newguy = oldright; @@ -801,6 +803,7 @@ qual_is_redundant(Query *root, return true; /* we proved new clause is redundant */ equalvars = lcons(newguy, equalvars); someadded = true; + /* * Remove this qual from list, since we don't need it anymore. * Note this doesn't break the foreach() loop, since lremove diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index b5a77ea623..57c9b963c7 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.66 2001/06/05 05:26:04 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planmain.c,v 1.67 2001/10/25 05:49:33 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -137,7 +137,6 @@ query_planner(Query *root, */ if (constant_quals || IsA(subplan, Append)) { - /* * The result node will also be responsible for evaluating the * originally requested tlist. @@ -148,7 +147,6 @@ query_planner(Query *root, } else { - /* * Replace the toplevel plan node's flattened target list with the * targetlist given by my caller, so that expressions are diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 48e41686e9..d870b2786f 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.109 2001/10/18 16:11:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.110 2001/10/25 05:49:33 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -210,7 +210,7 @@ subquery_planner(Query *parse, double tuple_fraction) * grouping_planner. */ if (parse->resultRelation && - (lst = expand_inherted_rtentry(parse, parse->resultRelation, false)) + (lst = expand_inherted_rtentry(parse, parse->resultRelation, false)) != NIL) plan = inheritance_planner(parse, lst); else @@ -277,8 +277,8 @@ pull_up_subqueries(Query *parse, Node *jtnode) * Is this a subquery RTE, and if so, is the subquery simple * enough to pull up? (If not, do nothing at this node.) * - * Note: even if the subquery itself is simple enough, we can't - * pull it up if there is a reference to its whole tuple result. + * Note: even if the subquery itself is simple enough, we can't pull + * it up if there is a reference to its whole tuple result. */ if (subquery && is_simple_subquery(subquery) && !contain_whole_tuple_var((Node *) parse, varno, 0)) @@ -370,12 +370,13 @@ pull_up_subqueries(Query *parse, Node *jtnode) /* * At the moment, we can't pull up subqueries that are inside the - * nullable side of an outer join, because substituting their target - * list entries for upper Var references wouldn't do the right thing - * (the entries wouldn't go to NULL when they're supposed to). - * Suppressing the pullup is an ugly, performance-losing hack, but - * I see no alternative for now. Find a better way to handle this - * when we redesign query trees --- tgl 4/30/01. + * nullable side of an outer join, because substituting their + * target list entries for upper Var references wouldn't do the + * right thing (the entries wouldn't go to NULL when they're + * supposed to). Suppressing the pullup is an ugly, + * performance-losing hack, but I see no alternative for now. + * Find a better way to handle this when we redesign query trees + * --- tgl 4/30/01. */ switch (j->jointype) { @@ -392,6 +393,7 @@ pull_up_subqueries(Query *parse, Node *jtnode) j->rarg = pull_up_subqueries(parse, j->rarg); break; case JOIN_UNION: + /* * This is where we fail if upper levels of planner * haven't rewritten UNION JOIN as an Append ... @@ -418,7 +420,6 @@ pull_up_subqueries(Query *parse, Node *jtnode) static bool is_simple_subquery(Query *subquery) { - /* * Let's just make sure it's a valid subselect ... */ @@ -545,7 +546,6 @@ preprocess_jointree(Query *parse, Node *jtnode) /* Now, is it a FromExpr? */ if (child && IsA(child, FromExpr)) { - /* * Yes, so do we want to merge it into parent? Always do * so if child has just one element (since that doesn't @@ -596,7 +596,6 @@ preprocess_jointree(Query *parse, Node *jtnode) static Node * preprocess_expression(Query *parse, Node *expr, int kind) { - /* * Simplify constant expressions. * @@ -632,7 +631,6 @@ preprocess_expression(Query *parse, Node *expr, int kind) if (kind != EXPRKIND_WHERE && (parse->groupClause != NIL || parse->hasAggs)) { - /* * Check for ungrouped variables passed to subplans. Note we * do NOT do this for subplans in WHERE (or JOIN/ON); it's @@ -776,7 +774,6 @@ grouping_planner(Query *parse, double tuple_fraction) if (parse->setOperations) { - /* * Construct the plan for set operations. The result will not * need any work except perhaps a top-level sort and/or LIMIT. @@ -946,12 +943,12 @@ grouping_planner(Query *parse, double tuple_fraction) if (parse->limitCount != NULL) { /* - * A LIMIT clause limits the absolute number of tuples returned. - * However, if it's not a constant LIMIT then we have to punt; - * for lack of a better idea, assume 10% of the plan's result - * is wanted. + * A LIMIT clause limits the absolute number of tuples + * returned. However, if it's not a constant LIMIT then we + * have to punt; for lack of a better idea, assume 10% of the + * plan's result is wanted. */ - double limit_fraction = 0.0; + double limit_fraction = 0.0; if (IsA(parse->limitCount, Const)) { @@ -959,9 +956,9 @@ grouping_planner(Query *parse, double tuple_fraction) int32 count = DatumGetInt32(limitc->constvalue); /* - * A NULL-constant LIMIT represents "LIMIT ALL", which - * we treat the same as no limit (ie, expect to - * retrieve all the tuples). + * A NULL-constant LIMIT represents "LIMIT ALL", which we + * treat the same as no limit (ie, expect to retrieve all + * the tuples). */ if (!limitc->constisnull && count > 0) { @@ -996,9 +993,10 @@ grouping_planner(Query *parse, double tuple_fraction) { /* * If we have absolute limits from both caller and LIMIT, - * use the smaller value; if one is fractional and the other - * absolute, treat the fraction as a fraction of the absolute - * value; else we can multiply the two fractions together. + * use the smaller value; if one is fractional and the + * other absolute, treat the fraction as a fraction of the + * absolute value; else we can multiply the two fractions + * together. */ if (tuple_fraction >= 1.0) { @@ -1040,7 +1038,6 @@ grouping_planner(Query *parse, double tuple_fraction) if (parse->groupClause) { - /* * In GROUP BY mode, we have the little problem that we don't * really know how many input tuples will be needed to make a @@ -1069,7 +1066,6 @@ grouping_planner(Query *parse, double tuple_fraction) } else if (parse->hasAggs) { - /* * Ungrouped aggregate will certainly want all the input * tuples. @@ -1078,7 +1074,6 @@ grouping_planner(Query *parse, double tuple_fraction) } else if (parse->distinctClause) { - /* * SELECT DISTINCT, like GROUP, will absorb an unpredictable * number of input tuples per output tuple. Handle the same @@ -1147,7 +1142,6 @@ grouping_planner(Query *parse, double tuple_fraction) } else { - /* * We will need to do an explicit sort by the GROUP BY clause. * make_groupplan will do the work, but set current_pathkeys @@ -1346,7 +1340,6 @@ make_groupplan(Query *parse, if (!is_presorted) { - /* * The Sort node always just takes a copy of the subplan's tlist * plus ordering information. (This might seem inefficient if the diff --git a/src/backend/optimizer/prep/prepkeyset.c b/src/backend/optimizer/prep/prepkeyset.c index 180637d099..6ff40fdb08 100644 --- a/src/backend/optimizer/prep/prepkeyset.c +++ b/src/backend/optimizer/prep/prepkeyset.c @@ -216,5 +216,4 @@ inspectOpNode(Expr *expr) secondExpr = lsecond(expr->args); return (firstExpr && secondExpr && nodeTag(firstExpr) == T_Var && nodeTag(secondExpr) == T_Const); } - #endif /* ENABLE_KEY_SET_QUERY */ diff --git a/src/backend/optimizer/prep/prepqual.c b/src/backend/optimizer/prep/prepqual.c index 2dc92deca1..a7773040d7 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.29 2001/03/22 03:59:38 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepqual.c,v 1.30 2001/10/25 05:49:33 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -157,7 +157,6 @@ canonicalize_qual(Expr *qual, bool removeAndFlag) */ if (cnfok) { - /* * Normalize into conjunctive normal form, and clean up the * result. @@ -166,7 +165,6 @@ canonicalize_qual(Expr *qual, bool removeAndFlag) } else if (dnfok) { - /* * Normalize into disjunctive normal form, and clean up the * result. @@ -260,7 +258,6 @@ dnfify(Expr *qual) return newqual; } - #endif /*-------------------- @@ -539,7 +536,6 @@ push_nots(Expr *qual) } else if (not_clause((Node *) qual)) { - /* * Another 'not' cancels this 'not', so eliminate the 'not' and * stop negating this branch. But search the subexpression for @@ -549,7 +545,6 @@ push_nots(Expr *qual) } else { - /* * We don't know how to negate anything else, place a 'not' at * this level. @@ -959,7 +954,6 @@ count_bool_nodes(Expr *qual, } else if (contain_subplans((Node *) qual)) { - /* * charge extra for subexpressions containing sub-SELECTs, to * discourage us from rearranging them in a way that might diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index 737f624b5a..2e335b808b 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.43 2001/09/06 02:07:42 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/preptlist.c,v 1.44 2001/10/25 05:49:33 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -49,7 +49,6 @@ preprocess_targetlist(List *tlist, Index result_relation, List *range_table) { - /* * Sanity check: if there is a result relation, it'd better be a real * relation not a subquery. Else parser or rewriter messed up. @@ -175,7 +174,6 @@ expand_targetlist(List *tlist, int command_type, if (new_tle == NULL) { - /* * Didn't find a matching tlist entry, so make one. * @@ -203,7 +201,8 @@ expand_targetlist(List *tlist, int command_type, /* * Set attributes are represented as OIDs no * matter what the set element type is, and - * the element type's default is irrelevant too. + * the element type's default is irrelevant + * too. */ hasdefault = false; typedefault = (Datum) 0; @@ -335,7 +334,6 @@ process_matched_tle(TargetEntry *src_tle, if (prior_tle == NULL) { - /* * Normal case where this is the first assignment to the * attribute. diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c index dbbe004aef..6949217dec 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.66 2001/08/14 17:12:57 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/prep/prepunion.c,v 1.67 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -275,7 +275,7 @@ generate_nonunion_plan(SetOperationStmt *op, Query *parse, * * The tlist for an Append plan isn't important as far as the Append is * concerned, but we must make it look real anyway for the benefit of - * the next plan level up. In fact, it has to be real enough that the + * the next plan level up. In fact, it has to be real enough that the * flag column is shown as a variable not a constant, else setrefs.c * will get confused. */ @@ -358,7 +358,7 @@ recurse_union_children(Node *setOp, Query *parse, * * colTypes: column datatypes for non-junk columns * flag: -1 if no flag column needed, 0 or 1 to create a const flag column, - * 2 to create a variable flag column + * 2 to create a variable flag column * hack_constants: true to copy up constants (see comments in code) * input_tlist: targetlist of this node's input node * refnames_tlist: targetlist to take column names from @@ -538,7 +538,7 @@ find_all_inheritors(Oid parentrel) * If not, return NIL. * * When dup_parent is false, the initially given RT index is part of the - * returned list (if any). When dup_parent is true, the given RT index + * returned list (if any). When dup_parent is true, the given RT index * is *not* in the returned list; a duplicate RTE will be made for the * parent table. * @@ -571,6 +571,7 @@ expand_inherted_rtentry(Query *parse, Index rti, bool dup_parent) return NIL; /* Scan for all members of inheritance set */ inhOIDs = find_all_inheritors(parentOID); + /* * Check that there's at least one descendant, else treat as no-child * case. This could happen despite above has_subclass() check, if @@ -582,7 +583,7 @@ expand_inherted_rtentry(Query *parse, Index rti, bool dup_parent) if (dup_parent) inhRTIs = NIL; else - inhRTIs = makeListi1(rti); /* include original RTE in result */ + inhRTIs = makeListi1(rti); /* include original RTE in result */ foreach(l, inhOIDs) { @@ -728,10 +729,10 @@ adjust_inherited_attrs_mutator(Node *node, /* * BUT: although we don't need to recurse into subplans, we do need to * make sure that they are copied, not just referenced as - * expression_tree_mutator will do by default. Otherwise we'll have the - * same subplan node referenced from each arm of the inheritance APPEND - * plan, which will cause trouble in the executor. This is a kluge - * that should go away when we redesign querytrees. + * expression_tree_mutator will do by default. Otherwise we'll have + * the same subplan node referenced from each arm of the inheritance + * APPEND plan, which will cause trouble in the executor. This is a + * kluge that should go away when we redesign querytrees. */ if (is_subplan(node)) { diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 0bf06c5286..c92581082b 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.88 2001/07/31 20:16:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.89 2001/10/25 05:49:34 momjian Exp $ * * HISTORY * AUTHOR DATE MAJOR EVENT @@ -354,7 +354,6 @@ make_ands_explicit(List *andclauses) List * make_ands_implicit(Expr *clause) { - /* * NB: because the parser sets the qual field to NULL in a query that * has no WHERE clause, we must consider a NULL input clause as TRUE, @@ -526,7 +525,6 @@ void check_subplans_for_ungrouped_vars(Node *clause, Query *query) { - /* * No special setup needed; context for walker is just the Query * pointer @@ -555,7 +553,6 @@ check_subplans_for_ungrouped_vars_walker(Node *node, */ if (is_subplan(node)) { - /* * The args list of the subplan node represents attributes from * outside passed into the sublink. @@ -686,7 +683,6 @@ contain_noncachable_functions_walker(Node *node, void *context) bool is_pseudo_constant_clause(Node *clause) { - /* * We could implement this check in one recursive scan. But since the * check for noncachable functions is both moderately expensive and @@ -746,7 +742,7 @@ pull_constant_clauses(List *quals, List **constantQual) static bool sortgroupref_is_present(Index sortgroupref, List *clauselist) { - List *clause; + List *clause; foreach(clause, clauselist) { @@ -765,20 +761,21 @@ sortgroupref_is_present(Index sortgroupref, List *clauselist) bool has_distinct_on_clause(Query *query) { - List *targetList; + List *targetList; /* Is there a DISTINCT clause at all? */ if (query->distinctClause == NIL) return false; + /* - * If the DISTINCT list contains all the nonjunk targetlist items, - * and nothing else (ie, no junk tlist items), then it's a simple + * If the DISTINCT list contains all the nonjunk targetlist items, and + * nothing else (ie, no junk tlist items), then it's a simple * DISTINCT, else it's DISTINCT ON. We do not require the lists to be * in the same order (since the parser may have adjusted the DISTINCT - * clause ordering to agree with ORDER BY). Furthermore, a non-DISTINCT - * junk tlist item that is in the sortClause is also evidence of - * DISTINCT ON, since we don't allow ORDER BY on junk tlist items when - * plain DISTINCT is used. + * clause ordering to agree with ORDER BY). Furthermore, a + * non-DISTINCT junk tlist item that is in the sortClause is also + * evidence of DISTINCT ON, since we don't allow ORDER BY on junk + * tlist items when plain DISTINCT is used. * * This code assumes that the DISTINCT list is valid, ie, all its entries * match some entry of the tlist. @@ -1155,7 +1152,6 @@ eval_const_expressions_mutator(Node *node, void *context) } if (IsA(node, RelabelType)) { - /* * If we can simplify the input to a constant, then we don't need * the RelabelType node anymore: just change the type field of the @@ -1272,7 +1268,6 @@ eval_const_expressions_mutator(Node *node, void *context) } if (IsA(node, Iter)) { - /* * The argument of an Iter is normally a function call. We must * not try to eliminate the function, but we can try to simplify @@ -1423,7 +1418,6 @@ simplify_op_or_func(Expr *expr, List *args) */ if (proisstrict && has_null_input) { - /* * It's strict and has NULL input, so must produce NULL output. * Return a NULL constant of the right type. @@ -1871,7 +1865,6 @@ expression_tree_mutator(Node *node, Node *(*mutator) (), void *context) { - /* * The mutator has already decided not to modify the current node, but * we must call the mutator for any sub-nodes. @@ -1933,7 +1926,6 @@ expression_tree_mutator(Node *node, } else { - /* * for other Expr node types, just transform args * list, linking to original oper node (OK?) @@ -2026,8 +2018,8 @@ expression_tree_mutator(Node *node, break; case T_NullTest: { - NullTest *ntest = (NullTest *) node; - NullTest *newnode; + NullTest *ntest = (NullTest *) node; + NullTest *newnode; FLATCOPY(newnode, ntest, NullTest); MUTATE(newnode->arg, ntest->arg, Node *); @@ -2046,7 +2038,6 @@ expression_tree_mutator(Node *node, break; case T_SubLink: { - /* * A "bare" SubLink (note we will not come here if we * found a SUBPLAN_EXPR node above it). Transform the @@ -2062,7 +2053,6 @@ expression_tree_mutator(Node *node, break; case T_List: { - /* * We assume the mutator isn't interested in the list * nodes per se, so just invoke it on each list element. @@ -2083,7 +2073,6 @@ expression_tree_mutator(Node *node, break; case T_TargetEntry: { - /* * We mutate the expression, but not the resdom, by * default. diff --git a/src/backend/optimizer/util/joininfo.c b/src/backend/optimizer/util/joininfo.c index ec98dbcb24..f12c9b70ba 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.29 2001/03/22 03:59:39 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/joininfo.c,v 1.30 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -59,7 +59,7 @@ joininfo_member(List *join_relids, List *joininfo_list) * Returns a joininfo node. * */ -JoinInfo * +JoinInfo * find_joininfo_node(RelOptInfo *this_rel, Relids join_relids) { JoinInfo *joininfo = joininfo_member(join_relids, diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c index 1377fc06a4..c86ee45008 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.75 2001/07/16 05:06:58 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/pathnode.c,v 1.76 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -325,7 +325,7 @@ create_seqscan_path(Query *root, RelOptInfo *rel) * * Returns the new path node. */ -IndexPath * +IndexPath * create_index_path(Query *root, RelOptInfo *rel, IndexOptInfo *index, @@ -363,8 +363,8 @@ create_index_path(Query *root, pathnode->rows = rel->rows; /* - * Not sure if this is necessary, but it should help if the - * statistics are too far off + * Not sure if this is necessary, but it should help if the statistics + * are too far off */ if (index->indpred && index->tuples < pathnode->rows) pathnode->rows = index->tuples; diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c index 6d609853aa..86ebb09ff6 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.68 2001/08/21 16:36:03 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/plancat.c,v 1.69 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -115,8 +115,8 @@ find_secondary_indexes(Oid relationObjectId) info = makeNode(IndexOptInfo); /* - * Need to make these arrays large enough to be sure there is - * room for a terminating 0 at the end of each one. + * Need to make these arrays large enough to be sure there is room + * for a terminating 0 at the end of each one. */ info->classlist = (Oid *) palloc(sizeof(Oid) * (INDEX_MAX_KEYS + 1)); info->indexkeys = (int *) palloc(sizeof(int) * (INDEX_MAX_KEYS + 1)); @@ -125,7 +125,7 @@ find_secondary_indexes(Oid relationObjectId) /* Extract info from the pg_index tuple */ info->indexoid = index->indexrelid; info->indproc = index->indproc; /* functional index ?? */ - if (VARSIZE(&index->indpred) > VARHDRSZ) /* partial index ?? */ + if (VARSIZE(&index->indpred) > VARHDRSZ) /* partial index ?? */ { char *predString; @@ -210,7 +210,7 @@ find_secondary_indexes(Oid relationObjectId) * This code executes registered procedures stored in the * operator relation, by calling the function manager. * - * varRelid is either 0 or a rangetable index. See clause_selectivity() + * varRelid is either 0 or a rangetable index. See clause_selectivity() * for details about its meaning. */ Selectivity @@ -223,8 +223,8 @@ restriction_selectivity(Query *root, float8 result; /* - * if the oprrest procedure is missing for whatever reason, - * use a selectivity of 0.5 + * if the oprrest procedure is missing for whatever reason, use a + * selectivity of 0.5 */ if (!oprrest) return (Selectivity) 0.5; @@ -257,8 +257,8 @@ join_selectivity(Query *root, float8 result; /* - * if the oprjoin procedure is missing for whatever reason, - * use a selectivity of 0.5 + * if the oprjoin procedure is missing for whatever reason, use a + * selectivity of 0.5 */ if (!oprjoin) return (Selectivity) 0.5; @@ -365,10 +365,10 @@ has_unique_index(RelOptInfo *rel, AttrNumber attno) IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist); /* - * Note: ignore functional and partial indexes, since they - * don't allow us to conclude that all attr values are distinct. - * Also, a multicolumn unique index doesn't allow us to conclude - * that just the specified attr is unique. + * Note: ignore functional and partial indexes, since they don't + * allow us to conclude that all attr values are distinct. Also, a + * multicolumn unique index doesn't allow us to conclude that just + * the specified attr is unique. */ if (index->unique && index->nkeys == 1 && diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3b85f321df..457826f5d3 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.34 2001/10/18 16:11:42 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/relnode.c,v 1.35 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -26,9 +26,9 @@ static RelOptInfo *make_base_rel(Query *root, int relid); static List *new_join_tlist(List *tlist, int first_resdomno); static List *build_joinrel_restrictlist(Query *root, - RelOptInfo *joinrel, - RelOptInfo *outer_rel, - RelOptInfo *inner_rel); + RelOptInfo *joinrel, + RelOptInfo *outer_rel, + RelOptInfo *inner_rel); static void build_joinrel_joinlist(RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel); @@ -154,7 +154,7 @@ make_base_rel(Query *root, int relid) if (relationObjectId != InvalidOid) { /* Plain relation --- retrieve statistics from the system catalogs */ - bool indexed; + bool indexed; get_relation_info(relationObjectId, &indexed, &rel->pages, &rel->tuples); @@ -270,7 +270,6 @@ build_join_rel(Query *root, if (joinrel) { - /* * Yes, so we only need to figure the restrictlist for this * particular pair of component relations. @@ -437,9 +436,9 @@ build_joinrel_restrictlist(Query *root, RelOptInfo *outer_rel, RelOptInfo *inner_rel) { - List *result = NIL; - List *rlist; - List *item; + List *result = NIL; + List *rlist; + List *item; /* * Collect all the clauses that syntactically belong at this level. @@ -453,9 +452,9 @@ build_joinrel_restrictlist(Query *root, * Eliminate duplicate and redundant clauses. * * We must eliminate duplicates, since we will see many of the same - * clauses arriving from both input relations. Also, if a clause is - * a mergejoinable clause, it's possible that it is redundant with - * previous clauses (see optimizer/README for discussion). We detect + * clauses arriving from both input relations. Also, if a clause is a + * mergejoinable clause, it's possible that it is redundant with + * previous clauses (see optimizer/README for discussion). We detect * that case and omit the redundant clause from the result list. * * We can detect redundant mergejoinable clauses very cheaply by using @@ -463,8 +462,9 @@ build_joinrel_restrictlist(Query *root, * 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 equality between any set member on the left and - * any member on the right; by transitivity, all the rest are then equal. + * 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. */ foreach(item, rlist) { @@ -477,8 +477,8 @@ build_joinrel_restrictlist(Query *root, /* check for redundant merge clauses */ if (rinfo->mergejoinoperator != InvalidOid) { - bool redundant = false; - List *olditem; + bool redundant = false; + List *olditem; cache_mergeclause_pathkeys(root, rinfo); diff --git a/src/backend/optimizer/util/tlist.c b/src/backend/optimizer/util/tlist.c index 9d5d6c080e..0d30586fce 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.50 2001/03/22 03:59:40 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/tlist.c,v 1.51 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -60,7 +60,6 @@ matching_tlist_expr(Node *node, List *targetlist) return (Node *) NULL; } - #endif /* diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 9b620c80f5..2521ffb2b6 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.32 2001/05/09 23:13:35 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/optimizer/util/var.c,v 1.33 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -41,7 +41,7 @@ typedef struct static bool pull_varnos_walker(Node *node, pull_varnos_context *context); static bool contain_var_reference_walker(Node *node, - contain_var_reference_context *context); + contain_var_reference_context *context); static bool contain_var_clause_walker(Node *node, void *context); static bool pull_var_clause_walker(Node *node, pull_var_clause_context *context); @@ -55,7 +55,7 @@ static bool pull_var_clause_walker(Node *node, * * NOTE: this is used on not-yet-planned expressions. It may therefore find * bare SubLinks, and if so it needs to recurse into them to look for uplevel - * references to the desired rtable level! But when we find a completed + * references to the desired rtable level! But when we find a completed * SubPlan, we only need to look at the parameters passed to the subplan. */ List * @@ -96,7 +96,6 @@ pull_varnos_walker(Node *node, pull_varnos_context *context) } if (is_subplan(node)) { - /* * Already-planned subquery. Examine the args list (parameters to * be passed to subquery), as well as the "oper" list which is @@ -137,7 +136,7 @@ pull_varnos_walker(Node *node, pull_varnos_context *context) * * NOTE: this is used on not-yet-planned expressions. It may therefore find * bare SubLinks, and if so it needs to recurse into them to look for uplevel - * references to the desired rtable entry! But when we find a completed + * references to the desired rtable entry! But when we find a completed * SubPlan, we only need to look at the parameters passed to the subplan. */ bool @@ -180,7 +179,6 @@ contain_var_reference_walker(Node *node, } if (is_subplan(node)) { - /* * Already-planned subquery. Examine the args list (parameters to * be passed to subquery), as well as the "oper" list which is diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 6e89abefe8..9f95300e35 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.203 2001/10/23 17:39:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.204 2001/10/25 05:49:34 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -77,15 +77,15 @@ static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt); static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt); static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt); 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 transformIndexConstraints(ParseState *pstate, - CreateStmtContext *cxt); + CreateStmtContext *cxt); static void transformFKConstraints(ParseState *pstate, - CreateStmtContext *cxt); + CreateStmtContext *cxt); static Node *transformTypeRefs(ParseState *pstate, Node *stmt); static void transformTypeRefsList(ParseState *pstate, List *l); @@ -97,7 +97,7 @@ static void transformColumnType(ParseState *pstate, ColumnDef *column); static void transformFkeyCheckAttrs(FkConstraint *fkconstraint, Oid *pktypoid); static void transformFkeyGetPrimaryKey(FkConstraint *fkconstraint, Oid *pktypoid); static bool relationHasPrimaryKey(char *relname); -static Oid transformFkeyGetColType(CreateStmtContext *cxt, char *colname); +static Oid transformFkeyGetColType(CreateStmtContext *cxt, char *colname); static void release_pstate_resources(ParseState *pstate); static FromExpr *makeFromExpr(List *fromlist, Node *quals); @@ -170,7 +170,6 @@ transformStmt(ParseState *pstate, Node *parseTree) switch (nodeTag(parseTree)) { - /* * Non-optimizable statements */ @@ -197,8 +196,8 @@ transformStmt(ParseState *pstate, Node *parseTree) * insert these into the actual query tree. - thomas * 2000-03-08 * - * Outer loop is over targetlist to make it easier to - * skip junk targetlist entries. + * Outer loop is over targetlist to make it easier to skip + * junk targetlist entries. */ if (n->aliases != NIL) { @@ -214,14 +213,15 @@ transformStmt(ParseState *pstate, Node *parseTree) Assert(IsA(te, TargetEntry)); rd = te->resdom; Assert(IsA(rd, Resdom)); - if (rd->resjunk) /* junk columns don't get aliases */ + if (rd->resjunk) /* junk columns don't get + * aliases */ continue; id = (Ident *) lfirst(aliaslist); Assert(IsA(id, Ident)); rd->resname = pstrdup(id->name); aliaslist = lnext(aliaslist); if (aliaslist == NIL) - break; /* done assigning aliases */ + break; /* done assigning aliases */ } if (aliaslist != NIL) @@ -466,7 +466,6 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt) } else { - /* * For INSERT ... VALUES, transform the given list of values to * form a targetlist for the INSERT. @@ -548,7 +547,7 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt) te = makeTargetEntry(makeResdom(attrno, thisatt->atttypid, thisatt->atttypmod, - pstrdup(NameStr(thisatt->attname)), + pstrdup(NameStr(thisatt->attname)), false), stringToNode(defval[ndef].adbin)); qry->targetList = lappend(qry->targetList, te); @@ -828,16 +827,16 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, CreateSeqStmt *sequence; /* - * Create appropriate constraints for SERIAL. We do - * this in full, rather than shortcutting, so that we - * will detect any conflicting constraints the user - * wrote (like a different DEFAULT). + * Create appropriate constraints for SERIAL. We do this in full, + * rather than shortcutting, so that we will detect any + * conflicting constraints the user wrote (like a different + * DEFAULT). */ sname = makeObjectName(cxt->relname, column->colname, "seq"); /* - * Create an expression tree representing the function - * call nextval('"sequencename"') + * Create an expression tree representing the function call + * nextval('"sequencename"') */ qstring = palloc(strlen(sname) + 2 + 1); sprintf(qstring, "\"%s\"", sname); @@ -860,7 +859,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, constraint = makeNode(Constraint); constraint->contype = CONSTR_UNIQUE; - constraint->name = NULL; /* assign later */ + constraint->name = NULL; /* assign later */ column->constraints = lappend(column->constraints, constraint); constraint = makeNode(Constraint); @@ -868,9 +867,9 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, column->constraints = lappend(column->constraints, constraint); /* - * Build a CREATE SEQUENCE command to create the - * sequence object, and add it to the list of things - * to be done before this CREATE/ALTER TABLE. + * Build a CREATE SEQUENCE command to create the sequence object, + * and add it to the list of things to be done before this + * CREATE/ALTER TABLE. */ sequence = makeNode(CreateSeqStmt); sequence->seqname = pstrdup(sname); @@ -878,7 +877,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, sequence->options = NIL; elog(NOTICE, "%s will create implicit sequence '%s' for SERIAL column '%s.%s'", - cxt->stmtType, sequence->seqname, cxt->relname, column->colname); + cxt->stmtType, sequence->seqname, cxt->relname, column->colname); cxt->blist = lappend(cxt->blist, sequence); } @@ -893,10 +892,9 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt, constraint = lfirst(clist); /* - * If this column constraint is a FOREIGN KEY - * constraint, then we fill in the current attributes - * name and throw it into the list of FK constraints - * to be processed later. + * If this column constraint is a FOREIGN KEY constraint, then we + * fill in the current attributes name and throw it into the list + * of FK constraints to be processed later. */ if (IsA(constraint, FkConstraint)) { @@ -1041,9 +1039,9 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) List *indexlist = NIL; /* - * Run through the constraints that need to generate an index. - * For PRIMARY KEY, mark each column as NOT NULL and create an index. - * For UNIQUE, create an index as for PRIMARY KEY, but do not insist on + * Run through the constraints that need to generate an index. For + * PRIMARY KEY, mark each column as NOT NULL and create an index. For + * UNIQUE, create an index as for PRIMARY KEY, but do not insist on * NOT NULL. */ foreach(listptr, cxt->ixconstraints) @@ -1083,8 +1081,8 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) index->whereClause = NULL; /* - * Make sure referenced keys exist. If we are making a - * PRIMARY KEY index, also make sure they are NOT NULL. + * Make sure referenced keys exist. If we are making a PRIMARY + * KEY index, also make sure they are NOT NULL. */ foreach(keys, constraint->keys) { @@ -1112,9 +1110,9 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) else if (SystemAttributeByName(key->name, cxt->hasoids) != NULL) { /* - * column will be a system column in the new table, - * so accept it. System columns can't ever be null, - * so no need to worry about PRIMARY/NOT NULL constraint. + * column will be a system column in the new table, so + * accept it. System columns can't ever be null, so no + * need to worry about PRIMARY/NOT NULL constraint. */ found = true; } @@ -1181,6 +1179,7 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) if (HeapTupleIsValid(atttuple)) { found = true; + /* * We require pre-existing column to be already marked * NOT NULL. @@ -1275,8 +1274,8 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) * Finally, select unique names for all not-previously-named indices, * and display notice messages. * - * XXX in ALTER TABLE case, we fail to consider name collisions - * against pre-existing indexes. + * XXX in ALTER TABLE case, we fail to consider name collisions against + * pre-existing indexes. */ foreach(indexlist, cxt->alist) { @@ -1307,9 +1306,9 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) List *fk_attr; List *pk_attr; Ident *id; - Oid pktypoid[INDEX_MAX_KEYS]; - Oid fktypoid[INDEX_MAX_KEYS]; - int i; + Oid pktypoid[INDEX_MAX_KEYS]; + Oid fktypoid[INDEX_MAX_KEYS]; + int i; if (cxt->fkconstraints == NIL) return; @@ -1320,7 +1319,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) foreach(fkclist, cxt->fkconstraints) { FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist); - int attnum; + int attnum; List *fkattrs; /* @@ -1329,12 +1328,12 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) if (fkconstraint->constr_name == NULL) fkconstraint->constr_name = "<unnamed>"; - for (attnum=0; attnum<INDEX_MAX_KEYS; attnum++) + for (attnum = 0; attnum < INDEX_MAX_KEYS; attnum++) pktypoid[attnum] = fktypoid[attnum] = InvalidOid; /* - * Look up the referencing attributes to make sure they exist - * (or will exist) in this table, and remember their type OIDs. + * Look up the referencing attributes to make sure they exist (or + * will exist) in this table, and remember their type OIDs. */ attnum = 0; foreach(fkattrs, fkconstraint->fk_attrs) @@ -1361,7 +1360,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) /* Use the to-be-created primary key */ List *attr; - attnum=0; + attnum = 0; foreach(attr, cxt->pkey->indexParams) { IndexElem *ielem = lfirst(attr); @@ -1376,7 +1375,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) elog(ERROR, "Can only have %d keys in a foreign key", INDEX_MAX_KEYS); pktypoid[attnum++] = transformFkeyGetColType(cxt, - ielem->name); + ielem->name); } } else @@ -1410,7 +1409,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) if (length(ind->indexParams) != length(fkconstraint->pk_attrs)) continue; - attnum=0; + attnum = 0; foreach(pkattrs, fkconstraint->pk_attrs) { Ident *pkattr = lfirst(pkattrs); @@ -1433,14 +1432,17 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) elog(ERROR, "Can only have %d keys in a foreign key", INDEX_MAX_KEYS); pktypoid[attnum++] = transformFkeyGetColType(cxt, - pkattr->name); + pkattr->name); } if (found) break; } if (!found) { - /* In ALTER TABLE case, such an index may already exist */ + /* + * In ALTER TABLE case, such an index may already + * exist + */ if (OidIsValid(cxt->relOid)) transformFkeyCheckAttrs(fkconstraint, pktypoid); else @@ -1454,12 +1456,13 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) for (i = 0; i < INDEX_MAX_KEYS && fktypoid[i] != 0; i++) { /* - * fktypoid[i] is the foreign key table's i'th element's type oid - * pktypoid[i] is the primary key table's i'th element's type oid - * We let oper() do our work for us, including elog(ERROR) if the - * types don't compare with = + * fktypoid[i] is the foreign key table's i'th element's type + * oid pktypoid[i] is the primary key table's i'th element's + * type oid We let oper() do our work for us, including + * elog(ERROR) if the types don't compare with = */ - Operator o=oper("=", fktypoid[i], pktypoid[i], false); + Operator o = oper("=", fktypoid[i], pktypoid[i], false); + ReleaseSysCache(o); } @@ -1492,7 +1495,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) fk_trigger->args = lappend(fk_trigger->args, makeString(cxt->relname)); fk_trigger->args = lappend(fk_trigger->args, - makeString(fkconstraint->pktable_name)); + makeString(fkconstraint->pktable_name)); fk_trigger->args = lappend(fk_trigger->args, makeString(fkconstraint->match_type)); fk_attr = fkconstraint->fk_attrs; @@ -1519,8 +1522,8 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) fkactions = lappend(fkactions, (Node *) fk_trigger); /* - * Build a CREATE CONSTRAINT TRIGGER statement for the ON - * DELETE action fired on the PK table !!! + * Build a CREATE CONSTRAINT TRIGGER statement for the ON DELETE + * action fired on the PK table !!! */ fk_trigger = (CreateTrigStmt *) makeNode(CreateTrigStmt); fk_trigger->trigname = fkconstraint->constr_name; @@ -1569,7 +1572,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) fk_trigger->args = lappend(fk_trigger->args, makeString(cxt->relname)); fk_trigger->args = lappend(fk_trigger->args, - makeString(fkconstraint->pktable_name)); + makeString(fkconstraint->pktable_name)); fk_trigger->args = lappend(fk_trigger->args, makeString(fkconstraint->match_type)); fk_attr = fkconstraint->fk_attrs; @@ -1591,8 +1594,8 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) fkactions = lappend(fkactions, (Node *) fk_trigger); /* - * Build a CREATE CONSTRAINT TRIGGER statement for the ON - * UPDATE action fired on the PK table !!! + * Build a CREATE CONSTRAINT TRIGGER statement for the ON UPDATE + * action fired on the PK table !!! */ fk_trigger = (CreateTrigStmt *) makeNode(CreateTrigStmt); fk_trigger->trigname = fkconstraint->constr_name; @@ -1641,7 +1644,7 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) fk_trigger->args = lappend(fk_trigger->args, makeString(cxt->relname)); fk_trigger->args = lappend(fk_trigger->args, - makeString(fkconstraint->pktable_name)); + makeString(fkconstraint->pktable_name)); fk_trigger->args = lappend(fk_trigger->args, makeString(fkconstraint->match_type)); fk_attr = fkconstraint->fk_attrs; @@ -1664,9 +1667,9 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt) } /* - * Attach completed list of extra actions to cxt->alist. We cannot - * do this earlier, because we assume above that cxt->alist still - * holds only IndexStmts. + * Attach completed list of extra actions to cxt->alist. We cannot do + * this earlier, because we assume above that cxt->alist still holds + * only IndexStmts. */ cxt->alist = nconc(cxt->alist, fkactions); } @@ -1688,11 +1691,11 @@ transformIndexStmt(ParseState *pstate, IndexStmt *stmt) if (stmt->whereClause) { /* - * Put the parent table into the rtable so that the WHERE clause can - * refer to its fields without qualification. Note that this only - * works if the parent table already exists --- so we can't easily - * support predicates on indexes created implicitly by CREATE TABLE. - * Fortunately, that's not necessary. + * Put the parent table into the rtable so that the WHERE clause + * can refer to its fields without qualification. Note that this + * only works if the parent table already exists --- so we can't + * easily support predicates on indexes created implicitly by + * CREATE TABLE. Fortunately, that's not necessary. */ rte = addRangeTableEntry(pstate, stmt->relname, NULL, false, true); @@ -1849,8 +1852,8 @@ transformRuleStmt(ParseState *pstate, RuleStmt *stmt) /* * We cannot support utility-statement actions (eg NOTIFY) - * with nonempty rule WHERE conditions, because there's no - * way to make the utility action execute conditionally. + * with nonempty rule WHERE conditions, because there's no way + * to make the utility action execute conditionally. */ if (top_subqry->commandType == CMD_UTILITY && stmt->whereClause != NULL) @@ -2041,7 +2044,8 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt) * The tree of set operations is converted into the setOperations field of * the top-level Query. */ -static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt) +static Query * +transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt) { Query *qry = makeNode(Query); SelectStmt *leftmostSelect; @@ -2481,7 +2485,6 @@ transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt) if (resnode->resjunk) { - /* * Resjunk nodes need no additional processing, but be sure * they have names and resnos that do not match any target @@ -2518,7 +2521,7 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt) /* * The only subtypes that currently require parse transformation - * handling are 'A'dd column and Add 'C'onstraint. These largely + * handling are 'A'dd column and Add 'C'onstraint. These largely * re-use code from CREATE TABLE. */ switch (stmt->subtype) @@ -2532,8 +2535,8 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt) PointerGetDatum(stmt->relname), 0, 0, 0); cxt.hasoids = SearchSysCacheExists(ATTNUM, - ObjectIdGetDatum(cxt.relOid), - Int16GetDatum(ObjectIdAttributeNumber), + ObjectIdGetDatum(cxt.relOid), + Int16GetDatum(ObjectIdAttributeNumber), 0, 0); cxt.columns = NIL; cxt.ckconstraints = NIL; @@ -2564,8 +2567,8 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt) PointerGetDatum(stmt->relname), 0, 0, 0); cxt.hasoids = SearchSysCacheExists(ATTNUM, - ObjectIdGetDatum(cxt.relOid), - Int16GetDatum(ObjectIdAttributeNumber), + ObjectIdGetDatum(cxt.relOid), + Int16GetDatum(ObjectIdAttributeNumber), 0, 0); cxt.columns = NIL; cxt.ckconstraints = NIL; @@ -2612,48 +2615,46 @@ transformTypeRefs(ParseState *pstate, Node *stmt) switch (nodeTag(stmt)) { case T_ProcedureStmt: - { - ProcedureStmt *ps = (ProcedureStmt *) stmt; + { + ProcedureStmt *ps = (ProcedureStmt *) stmt; - transformTypeRefsList(pstate, ps->argTypes); - transformTypeRef(pstate, (TypeName *) ps->returnType); - transformTypeRefsList(pstate, ps->withClause); - } - break; + transformTypeRefsList(pstate, ps->argTypes); + transformTypeRef(pstate, (TypeName *) ps->returnType); + transformTypeRefsList(pstate, ps->withClause); + } + break; case T_CommentStmt: - { - CommentStmt *cs = (CommentStmt *) stmt; + { + CommentStmt *cs = (CommentStmt *) stmt; - transformTypeRefsList(pstate, cs->objlist); - } - break; + transformTypeRefsList(pstate, cs->objlist); + } + break; case T_RemoveFuncStmt: - { - RemoveFuncStmt *rs = (RemoveFuncStmt *) stmt; + { + RemoveFuncStmt *rs = (RemoveFuncStmt *) stmt; - transformTypeRefsList(pstate, rs->args); - } - break; + transformTypeRefsList(pstate, rs->args); + } + break; case T_DefineStmt: - { - DefineStmt *ds = (DefineStmt *) stmt; - List *ele; - - foreach(ele, ds->definition) { - DefElem *de = (DefElem *) lfirst(ele); + DefineStmt *ds = (DefineStmt *) stmt; + List *ele; - if (de->arg != NULL - && IsA(de->arg, TypeName)) + foreach(ele, ds->definition) { - transformTypeRef(pstate, (TypeName *) de->arg); + DefElem *de = (DefElem *) lfirst(ele); + + if (de->arg != NULL + && IsA(de->arg, TypeName)) + transformTypeRef(pstate, (TypeName *) de->arg); } } - } - break; + break; default: elog(ERROR, "Unsupported type %d in transformTypeRefs", @@ -2674,7 +2675,7 @@ transformTypeRefsList(ParseState *pstate, List *l) foreach(ele, l) { - Node *elem = lfirst(ele); + Node *elem = lfirst(ele); if (elem && IsA(elem, TypeName)) transformTypeRef(pstate, (TypeName *) elem); @@ -2687,16 +2688,16 @@ transformTypeRefsList(ParseState *pstate, List *l) static void transformTypeRef(ParseState *pstate, TypeName *tn) { - Attr *att; - Node *n; - Var *v; - char *tyn; + Attr *att; + Node *n; + Var *v; + char *tyn; if (tn->attrname == NULL) return; att = makeAttr(tn->name, tn->attrname); n = transformExpr(pstate, (Node *) att, EXPR_COLUMN_FIRST); - if (! IsA(n, Var)) + if (!IsA(n, Var)) elog(ERROR, "unsupported expression in %%TYPE"); v = (Var *) n; tyn = typeidTypeName(v->vartype); @@ -2841,7 +2842,7 @@ transformFkeyCheckAttrs(FkConstraint *fkconstraint, Oid *pktypoid) { /* go through the fkconstraint->pk_attrs list */ List *attrl; - int attnum = 0; + int attnum = 0; foreach(attrl, fkconstraint->pk_attrs) { @@ -2893,7 +2894,7 @@ transformFkeyGetPrimaryKey(FkConstraint *fkconstraint, Oid *pktypoid) HeapTuple indexTuple = NULL; Form_pg_index indexStruct = NULL; int i; - int attnum=0; + int attnum = 0; /* * Open the referenced table @@ -3022,7 +3023,7 @@ transformFkeyGetColType(CreateStmtContext *cxt, char *colname) if (strcmp(col->colname, colname) == 0) { - char *buff = TypeNameToInternalName(col->typename); + char *buff = TypeNameToInternalName(col->typename); result = typenameTypeId(buff); if (!OidIsValid(result)) @@ -3231,7 +3232,6 @@ transformColumnType(ParseState *pstate, ColumnDef *column) */ if (typeTypeRelid(ctype) != InvalidOid) { - /* * (Eventually add in here that the set can only contain one * element.) diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c index 3c621ddc69..d6ad0a07ea 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.45 2001/08/09 18:28:17 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_agg.c,v 1.46 2001/10/25 05:49:36 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -240,7 +240,6 @@ ParseAgg(ParseState *pstate, char *aggname, Oid basetype, void agg_error(char *caller, char *aggname, Oid basetypeID) { - /* * basetypeID that is Invalid (zero) means aggregate over all types. * (count) diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c index e8ba26295e..61904439e7 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.82 2001/08/09 18:28:17 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_clause.c,v 1.83 2001/10/25 05:49:37 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -179,7 +179,7 @@ interpretInhOption(InhOption inhOpt) { switch (inhOpt) { - case INH_NO: + case INH_NO: return false; case INH_YES: return true; @@ -288,9 +288,9 @@ transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars) result = transformExpr(pstate, result, EXPR_COLUMN_FIRST); /* - * We expect the result to yield bool directly, otherwise complain. - * We could try coerce_to_boolean() here, but it seems likely that an - * "=" operator that doesn't return bool is wrong anyway. + * We expect the result to yield bool directly, otherwise complain. We + * could try coerce_to_boolean() here, but it seems likely that an "=" + * operator that doesn't return bool is wrong anyway. */ if (exprType(result) != BOOLOID) elog(ERROR, "JOIN/USING clause must return type boolean, not type %s", @@ -328,7 +328,7 @@ transformJoinOnClause(ParseState *pstate, JoinExpr *j, /* This part is just like transformWhereClause() */ result = transformExpr(pstate, j->quals, EXPR_COLUMN_FIRST); - if (! coerce_to_boolean(pstate, &result)) + if (!coerce_to_boolean(pstate, &result)) elog(ERROR, "JOIN/ON clause must return type boolean, not type %s", format_type_be(exprType(result))); @@ -608,7 +608,6 @@ transformFromClauseItem(ParseState *pstate, Node *n, List **containedRels) if (j->using) { - /* * JOIN/USING (or NATURAL JOIN, as transformed above). * Transform the list into an explicit ON-condition, and @@ -734,7 +733,6 @@ transformFromClauseItem(ParseState *pstate, Node *n, List **containedRels) */ if (j->alias) { - /* * If a column alias list is specified, substitute the alias * names into my output-column list @@ -775,7 +773,7 @@ transformWhereClause(ParseState *pstate, Node *clause) qual = transformExpr(pstate, clause, EXPR_COLUMN_FIRST); - if (! coerce_to_boolean(pstate, &qual)) + if (!coerce_to_boolean(pstate, &qual)) elog(ERROR, "WHERE clause must return type boolean, not type %s", format_type_be(exprType(qual))); @@ -840,13 +838,12 @@ findTargetlistEntry(ParseState *pstate, Node *node, List *tlist, int clause) * an expression. *---------- */ - if (IsA(node, Ident) && ((Ident *) node)->indirection == NIL) + if (IsA(node, Ident) &&((Ident *) node)->indirection == NIL) { char *name = ((Ident *) node)->name; if (clause == GROUP_CLAUSE) { - /* * In GROUP BY, we must prefer a match against a FROM-clause * column to one against the targetlist. Look to see if there diff --git a/src/backend/parser/parse_coerce.c b/src/backend/parser/parse_coerce.c index e1e218f27e..e81edb3efc 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.63 2001/10/04 17:52:24 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_coerce.c,v 2.64 2001/10/25 05:49:39 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -47,7 +47,6 @@ coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, } else if (inputTypeId == UNKNOWNOID && IsA(node, Const)) { - /* * Input is a string constant with previously undetermined type. * Apply the target type's typinput function to it to produce a @@ -90,7 +89,6 @@ coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, } else if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId)) { - /* * We don't really need to do a conversion, but we do need to * attach a RelabelType node so that the expression will be seen @@ -118,7 +116,6 @@ coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, } else { - /* * Otherwise, find the appropriate type conversion function * (caller should have determined that there is one), and generate @@ -240,7 +237,7 @@ can_coerce_type(int nargs, Oid *input_typeids, Oid *func_typeids) oid_array[0] = inputTypeId; ftup = SearchSysCache(PROCNAME, - PointerGetDatum(typeidTypeName(targetTypeId)), + PointerGetDatum(typeidTypeName(targetTypeId)), Int32GetDatum(1), PointerGetDatum(oid_array), 0); @@ -324,7 +321,7 @@ coerce_type_typmod(ParseState *pstate, Node *node, * (AND, OR, NOT, etc). * * If successful, update *pnode to be the transformed argument (if any - * transformation is needed), and return TRUE. If fail, return FALSE. + * transformation is needed), and return TRUE. If fail, return FALSE. * (The caller must check for FALSE and emit a suitable error message.) */ bool @@ -336,7 +333,7 @@ coerce_to_boolean(ParseState *pstate, Node **pnode) if (inputTypeId == BOOLOID) return true; /* no work */ targetTypeId = BOOLOID; - if (! can_coerce_type(1, &inputTypeId, &targetTypeId)) + if (!can_coerce_type(1, &inputTypeId, &targetTypeId)) return false; /* fail, but let caller choose error msg */ *pnode = coerce_type(pstate, *pnode, inputTypeId, targetTypeId, -1); return true; @@ -384,7 +381,6 @@ select_common_type(List *typeids, const char *context) } else if (TypeCategory(ntype) != pcategory) { - /* * both types in different categories? then not much * hope... @@ -396,7 +392,6 @@ select_common_type(List *typeids, const char *context) && !IsPreferredType(pcategory, ptype) && can_coerce_type(1, &ptype, &ntype)) { - /* * new one is preferred and can convert? then take it... */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index 5db1ab867f..333333b040 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.103 2001/10/08 21:46:59 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_expr.c,v 1.104 2001/10/25 05:49:39 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -40,11 +40,11 @@ bool Transform_null_equals = false; static Node *parser_typecast_constant(Value *expr, TypeName *typename); static Node *parser_typecast_expression(ParseState *pstate, - Node *expr, TypeName *typename); + Node *expr, TypeName *typename); static Node *transformAttr(ParseState *pstate, Attr *att, int precedence); static Node *transformIdent(ParseState *pstate, Ident *ident, int precedence); static Node *transformIndirection(ParseState *pstate, Node *basenode, - List *indirection); + List *indirection); /* @@ -159,16 +159,18 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) case OP: { /* - * Special-case "foo = NULL" and "NULL = foo" for - * compatibility with standards-broken products - * (like Microsoft's). Turn these into IS NULL exprs. + * Special-case "foo = NULL" and "NULL = foo" + * for compatibility with standards-broken + * products (like Microsoft's). Turn these + * into IS NULL exprs. */ if (Transform_null_equals && strcmp(a->opname, "=") == 0 && (exprIsNullConstant(a->lexpr) || exprIsNullConstant(a->rexpr))) { - NullTest *n = makeNode(NullTest); + NullTest *n = makeNode(NullTest); + n->nulltesttype = IS_NULL; if (exprIsNullConstant(a->lexpr)) @@ -183,11 +185,11 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) else { Node *lexpr = transformExpr(pstate, - a->lexpr, - precedence); + a->lexpr, + precedence); Node *rexpr = transformExpr(pstate, - a->rexpr, - precedence); + a->rexpr, + precedence); result = (Node *) make_op(a->opname, lexpr, @@ -205,12 +207,12 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) precedence); Expr *expr = makeNode(Expr); - if (! coerce_to_boolean(pstate, &lexpr)) + if (!coerce_to_boolean(pstate, &lexpr)) elog(ERROR, "left-hand side of AND is type '%s', not '%s'", format_type_be(exprType(lexpr)), format_type_be(BOOLOID)); - if (! coerce_to_boolean(pstate, &rexpr)) + if (!coerce_to_boolean(pstate, &rexpr)) elog(ERROR, "right-hand side of AND is type '%s', not '%s'", format_type_be(exprType(rexpr)), format_type_be(BOOLOID)); @@ -231,12 +233,12 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) precedence); Expr *expr = makeNode(Expr); - if (! coerce_to_boolean(pstate, &lexpr)) + if (!coerce_to_boolean(pstate, &lexpr)) elog(ERROR, "left-hand side of OR is type '%s', not '%s'", format_type_be(exprType(lexpr)), format_type_be(BOOLOID)); - if (! coerce_to_boolean(pstate, &rexpr)) + if (!coerce_to_boolean(pstate, &rexpr)) elog(ERROR, "right-hand side of OR is type '%s', not '%s'", format_type_be(exprType(rexpr)), format_type_be(BOOLOID)); @@ -254,7 +256,7 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) precedence); Expr *expr = makeNode(Expr); - if (! coerce_to_boolean(pstate, &rexpr)) + if (!coerce_to_boolean(pstate, &rexpr)) elog(ERROR, "argument to NOT is type '%s', not '%s'", format_type_be(exprType(rexpr)), format_type_be(BOOLOID)); @@ -315,7 +317,6 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) if (sublink->subLinkType == EXISTS_SUBLINK) { - /* * EXISTS needs no lefthand or combining operator. * These fields should be NIL already, but make sure. @@ -456,7 +457,7 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) } neww->expr = transformExpr(pstate, warg, precedence); - if (! coerce_to_boolean(pstate, &neww->expr)) + if (!coerce_to_boolean(pstate, &neww->expr)) elog(ERROR, "WHEN clause must have a boolean result"); /* @@ -541,11 +542,11 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) case T_BooleanTest: { - BooleanTest *b = (BooleanTest *) expr; + BooleanTest *b = (BooleanTest *) expr; b->arg = transformExpr(pstate, b->arg, precedence); - if (! coerce_to_boolean(pstate, &b->arg)) + if (!coerce_to_boolean(pstate, &b->arg)) { const char *clausename; @@ -572,7 +573,7 @@ transformExpr(ParseState *pstate, Node *expr, int precedence) default: elog(ERROR, "transformExpr: unexpected booltesttype %d", (int) b->booltesttype); - clausename = NULL; /* keep compiler quiet */ + clausename = NULL; /* keep compiler quiet */ } elog(ERROR, "Argument of %s must be boolean", @@ -645,7 +646,7 @@ transformIdent(ParseState *pstate, Ident *ident, int precedence) * appear */ if (ident->indirection == NIL && - refnameRangeOrJoinEntry(pstate, ident->name, &sublevels_up) != NULL) + refnameRangeOrJoinEntry(pstate, ident->name, &sublevels_up) != NULL) { ident->isRel = TRUE; result = (Node *) ident; @@ -1023,7 +1024,6 @@ TypeNameToInternalName(TypeName *typename) Assert(typename->attrname == NULL); if (typename->arrayBounds != NIL) { - /* * By convention, the name of an array type is the name of its * element type with "_" prepended. diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c index fc85ca8952..f6d94e5c55 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.111 2001/10/04 22:06:46 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_func.c,v 1.112 2001/10/25 05:49:39 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -106,16 +106,16 @@ ParseNestedFuncOrColumn(ParseState *pstate, Attr *attr, int precedence) } /* - * parse function + * parse function * - * This code is confusing because the database can accept - * relation.column, column.function, or relation.column.function. + * This code is confusing because the database can accept + * relation.column, column.function, or relation.column.function. * In these cases, funcname is the last parameter, and fargs are - * the rest. + * the rest. * - * It can also be called as func(col) or func(col,col). - * In this case, Funcname is the part before parens, and fargs - * are the part in parens. + * It can also be called as func(col) or func(col,col). + * In this case, Funcname is the part before parens, and fargs + * are the part in parens. * * FYI, projection is choosing column from a table. * @@ -146,10 +146,10 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, Expr *expr; /* - * Most of the rest of the parser just assumes that functions do - * not have more than FUNC_MAX_ARGS parameters. We have to test - * here to protect against array overruns, etc. Of course, this - * may not be a function, but the test doesn't hurt. + * Most of the rest of the parser just assumes that functions do not + * have more than FUNC_MAX_ARGS parameters. We have to test here to + * protect against array overruns, etc. Of course, this may not be a + * function, but the test doesn't hurt. */ if (nargs > FUNC_MAX_ARGS) elog(ERROR, "Cannot pass more than %d arguments to a function", @@ -165,15 +165,15 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, /* * test for relation.column * - * check for projection methods: if function takes one argument, and - * that argument is a relation, param, or PQ function returning a - * complex * type, then the function could be a projection. + * check for projection methods: if function takes one argument, and that + * argument is a relation, param, or PQ function returning a complex * + * type, then the function could be a projection. */ /* We only have one parameter, and it's not got aggregate decoration */ if (nargs == 1 && !must_be_agg) { /* Is it a plain Relation name from the parser? */ - if (IsA(first_arg, Ident) && ((Ident *) first_arg)->isRel) + if (IsA(first_arg, Ident) &&((Ident *) first_arg)->isRel) { Ident *ident = (Ident *) first_arg; @@ -188,7 +188,6 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, } else if (ISCOMPLEX(exprType(first_arg))) { - /* * Attempt to handle projection of a complex argument. If * ParseComplexProjection can't handle the projection, we have @@ -231,7 +230,7 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, if (nargs != 1) elog(ERROR, "Aggregate functions may only have one parameter"); /* Agg's argument can't be a relation name, either */ - if (IsA(first_arg, Ident) && ((Ident *) first_arg)->isRel) + if (IsA(first_arg, Ident) &&((Ident *) first_arg)->isRel) elog(ERROR, "Aggregate functions cannot be applied to relation names"); could_be_agg = true; } @@ -239,7 +238,7 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, { /* Try to parse as an aggregate if above-mentioned checks are OK */ could_be_agg = (nargs == 1) && - !(IsA(first_arg, Ident) && ((Ident *) first_arg)->isRel); + !(IsA(first_arg, Ident) &&((Ident *) first_arg)->isRel); } if (could_be_agg) @@ -295,7 +294,6 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, if (must_be_agg) { - /* * No matching agg, but we had '*' or DISTINCT, so a plain * function could not have been meant. @@ -318,7 +316,7 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, { Node *arg = lfirst(i); - if (IsA(arg, Ident) && ((Ident *) arg)->isRel) + if (IsA(arg, Ident) &&((Ident *) arg)->isRel) { RangeTblEntry *rte; int vnum; @@ -339,9 +337,8 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, rte = (RangeTblEntry *) rteorjoin; else if (IsA(rteorjoin, JoinExpr)) { - /* - * The relation name refers to a join. We can't support + * The relation name refers to a join. We can't support * functions on join tuples (since we don't have a named * type for the join tuples), so error out. */ @@ -360,8 +357,8 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, else { /* - * There are multiple arguments, so it must be a function - * call. + * There are multiple arguments, so it must be a + * function call. */ elog(ERROR, "Cannot pass result of join %s to a function", refname); @@ -378,24 +375,26 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, vnum = RTERangeTablePosn(pstate, rte, &sublevels_up); /* - * The parameter to be passed to the function is the whole tuple - * from the relation. We build a special VarNode to reflect - * this -- it has varno set to the correct range table entry, - * but has varattno == 0 to signal that the whole tuple is the - * argument. Also, it has typmod set to sizeof(Pointer) to - * signal that the runtime representation will be a pointer - * not an Oid. + * The parameter to be passed to the function is the whole + * tuple from the relation. We build a special VarNode to + * reflect this -- it has varno set to the correct range table + * entry, but has varattno == 0 to signal that the whole tuple + * is the argument. Also, it has typmod set to + * sizeof(Pointer) to signal that the runtime representation + * will be a pointer not an Oid. */ if (rte->relname == NULL) { /* - * RTE is a subselect; must fail for lack of a specific type + * RTE is a subselect; must fail for lack of a specific + * type */ if (nargs == 1) { /* - * Here, we probably have an unrecognized attribute of a - * sub-select; again can't tell if it was x.f or f(x) + * Here, we probably have an unrecognized attribute of + * a sub-select; again can't tell if it was x.f or + * f(x) */ elog(ERROR, "No such attribute or function %s.%s", refname, funcname); @@ -449,14 +448,14 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, } else { - FuncDetailCode fdresult; + FuncDetailCode fdresult; /* * func_get_detail looks up the function in the catalogs, does - * disambiguation for polymorphic functions, handles inheritance, and - * returns the funcid and type and set or singleton status of the - * function's return value. it also returns the true argument types - * to the function. + * disambiguation for polymorphic functions, handles inheritance, + * and returns the funcid and type and set or singleton status of + * the function's return value. it also returns the true argument + * types to the function. */ fdresult = func_get_detail(funcname, fargs, nargs, oid_array, &funcid, &rettype, &retset, @@ -464,8 +463,8 @@ ParseFuncOrColumn(ParseState *pstate, char *funcname, List *fargs, if (fdresult == FUNCDETAIL_COERCION) { /* - * We can do it as a trivial coercion. - * coerce_type can handle these cases, so why duplicate code... + * We can do it as a trivial coercion. coerce_type can handle + * these cases, so why duplicate code... */ return coerce_type(pstate, lfirst(fargs), oid_array[0], rettype, -1); @@ -1019,7 +1018,6 @@ func_select_candidate(int nargs, } else { - /* * Remember conflict, but keep going (might find * STRING) @@ -1101,7 +1099,7 @@ func_select_candidate(int nargs, * (exact match) is as quick as possible. * * If an exact match isn't found: - * 1) check for possible interpretation as a trivial type coercion + * 1) check for possible interpretation as a trivial type coercion * 2) get a vector of all possible input arg type arrays constructed * from the superclasses of the original input arg types * 3) get a list of all possible argument type arrays to the function @@ -1145,23 +1143,24 @@ func_get_detail(char *funcname, * that this is really a type-coercion request: a single-argument * function call where the function name is a type name. If so, * and if we can do the coercion trivially (no run-time function - * call needed), then go ahead and treat the "function call" as - * a coercion. This interpretation needs to be given higher - * priority than interpretations involving a type coercion followed - * by a function call, otherwise we can produce surprising results. - * For example, we want "text(varchar)" to be interpreted as a - * trivial coercion, not as "text(name(varchar))" which the code - * below this point is entirely capable of selecting. + * call needed), then go ahead and treat the "function call" as a + * coercion. This interpretation needs to be given higher + * priority than interpretations involving a type coercion + * followed by a function call, otherwise we can produce + * surprising results. For example, we want "text(varchar)" to be + * interpreted as a trivial coercion, not as "text(name(varchar))" + * which the code below this point is entirely capable of + * selecting. * - * "Trivial" coercions are ones that involve binary-compatible - * types and ones that are coercing a previously-unknown-type - * literal constant to a specific type. + * "Trivial" coercions are ones that involve binary-compatible types + * and ones that are coercing a previously-unknown-type literal + * constant to a specific type. * * NB: it's important that this code stays in sync with what * coerce_type can do, because the caller will try to apply * coerce_type if we return FUNCDETAIL_COERCION. If we return - * that result for something coerce_type can't handle, we'll - * cause infinite recursion between this module and coerce_type! + * that result for something coerce_type can't handle, we'll cause + * infinite recursion between this module and coerce_type! */ if (nargs == 1) { @@ -1627,7 +1626,6 @@ ParseComplexProjection(ParseState *pstate, } case T_Var: { - /* * The argument is a set, so this is either a projection * or a function call on this set. diff --git a/src/backend/parser/parse_node.c b/src/backend/parser/parse_node.c index 8625af7b96..d03c6b6403 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.55 2001/08/09 18:28:18 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_node.c,v 1.56 2001/10/25 05:49:39 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -235,7 +235,7 @@ make_var(ParseState *pstate, RangeTblEntry *rte, int attrno) * forceSlice If true, treat subscript as array slice in all cases * assignFrom NULL for array fetch, else transformed expression for source. */ -ArrayRef * +ArrayRef * transformArraySubscripts(ParseState *pstate, Node *arrayBase, Oid arrayType, @@ -467,7 +467,7 @@ make_const(Value *value) case T_String: val = DirectFunctionCall1(textin, CStringGetDatum(strVal(value))); - typeid = UNKNOWNOID;/* will be coerced later */ + typeid = UNKNOWNOID; /* will be coerced later */ typelen = -1; /* variable len */ typebyval = false; break; diff --git a/src/backend/parser/parse_oper.c b/src/backend/parser/parse_oper.c index 8fb8856658..15a39dc84b 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.50 2001/08/09 18:28:18 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_oper.c,v 1.51 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -481,7 +481,6 @@ oper_select_candidate(int nargs, } else { - /* * Remember conflict, but keep going (might find * STRING) @@ -835,7 +834,6 @@ right_oper(char *op, Oid arg) unary_op_error(op, arg, FALSE); else { - /* * We must run oper_select_candidate even if only one * candidate, otherwise we may falsely return a @@ -892,7 +890,6 @@ left_oper(char *op, Oid arg) unary_op_error(op, arg, TRUE); else { - /* * We must run oper_select_candidate even if only one * candidate, otherwise we may falsely return a @@ -957,11 +954,11 @@ unary_op_error(char *op, Oid arg, bool is_left_op) { if (is_left_op) elog(ERROR, "Unable to identify a prefix operator '%s' for type '%s'" - "\n\tYou may need to add parentheses or an explicit cast", + "\n\tYou may need to add parentheses or an explicit cast", op, format_type_be(arg)); else elog(ERROR, "Unable to identify a postfix operator '%s' for type '%s'" - "\n\tYou may need to add parentheses or an explicit cast", + "\n\tYou may need to add parentheses or an explicit cast", op, format_type_be(arg)); } } diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 10861bf273..388ddf1d1f 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.58 2001/10/23 17:39:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_relation.c,v 1.59 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -967,7 +967,7 @@ specialAttNum(char *a) { Form_pg_attribute sysatt; - sysatt = SystemAttributeByName(a, true /* "oid" will be accepted */); + sysatt = SystemAttributeByName(a, true /* "oid" will be accepted */ ); if (sysatt != NULL) return sysatt->attnum; return InvalidAttrNumber; diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c index 801dde811c..b4375d67d8 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.74 2001/10/08 21:48:51 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_target.c,v 1.75 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,7 +27,7 @@ static List *ExpandAllTables(ParseState *pstate); static char *FigureColname(Node *node); -static int FigureColnameInternal(Node *node, char **name); +static int FigureColnameInternal(Node *node, char **name); /* @@ -57,8 +57,8 @@ transformTargetEntry(ParseState *pstate, if (expr == NULL) expr = transformExpr(pstate, node, EXPR_COLUMN_FIRST); - if (IsA(expr, Ident) && ((Ident *)expr)->isRel) - elog(ERROR,"You can't use relation names alone in the target list, try relation.*."); + if (IsA(expr, Ident) &&((Ident *) expr)->isRel) + elog(ERROR, "You can't use relation names alone in the target list, try relation.*."); type_id = exprType(expr); type_mod = exprTypmod(expr); @@ -104,7 +104,6 @@ transformTargetList(ParseState *pstate, List *targetlist) if (att->relname != NULL && strcmp(att->relname, "*") == 0) { - /* * Target item is a single '*', expand all tables (eg. * SELECT * FROM emp) @@ -115,7 +114,6 @@ transformTargetList(ParseState *pstate, List *targetlist) else if (att->attrs != NIL && strcmp(strVal(lfirst(att->attrs)), "*") == 0) { - /* * Target item is relation.*, expand that table (eg. * SELECT emp.*, dname FROM emp, dept) @@ -221,7 +219,6 @@ updateTargetListEntry(ParseState *pstate, if (pstate->p_is_insert) { - /* * The command is INSERT INTO table (arraycol[subscripts]) ... * so there is not really a source array value to work with. @@ -234,7 +231,6 @@ updateTargetListEntry(ParseState *pstate, } else { - /* * Build a Var for the array to be updated. */ @@ -253,7 +249,6 @@ updateTargetListEntry(ParseState *pstate, } else { - /* * For normal non-subscripted target column, do type checking and * coercion. But accept InvalidOid, which indicates the source is @@ -347,7 +342,6 @@ checkInsertTargets(ParseState *pstate, List *cols, List **attrnos) if (cols == NIL) { - /* * Generate default column list for INSERT. */ @@ -373,7 +367,6 @@ checkInsertTargets(ParseState *pstate, List *cols, List **attrnos) } else { - /* * Do initial validation of user-supplied INSERT column list. */ @@ -461,7 +454,7 @@ ExpandAllTables(ParseState *pstate) static char * FigureColname(Node *node) { - char *name = NULL; + char *name = NULL; FigureColnameInternal(node, &name); if (name != NULL) @@ -473,7 +466,7 @@ FigureColname(Node *node) static int FigureColnameInternal(Node *node, char **name) { - int strength = 0; + int strength = 0; if (node == NULL) return strength; @@ -506,7 +499,7 @@ FigureColnameInternal(Node *node, char **name) return 1; } break; - case T_TypeCast: + case T_TypeCast: strength = FigureColnameInternal(((TypeCast *) node)->arg, name); if (strength <= 1) diff --git a/src/backend/parser/parse_type.c b/src/backend/parser/parse_type.c index ed010a46ed..732974a96f 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.36 2001/10/09 04:15:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parse_type.c,v 1.37 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -139,7 +139,6 @@ typeTypElem(Type typ) return typtup->typelem; } - #endif #ifdef NOT_USED @@ -153,7 +152,6 @@ typeInfunc(Type typ) return typtup->typinput; } - #endif #ifdef NOT_USED @@ -167,7 +165,6 @@ typeOutfunc(Type typ) return typtup->typoutput; } - #endif /* Given a type structure and a string, returns the internal form of @@ -207,7 +204,6 @@ typeidOutfunc(Oid type_id) ReleaseSysCache(typeTuple); return outfunc; } - #endif /* return a type name, given a typeid */ @@ -279,12 +275,12 @@ typenameTypeId(char *s) void parseTypeString(const char *str, Oid *type_id, int32 *typmod) { - char *buf; - List *raw_parsetree_list; + char *buf; + List *raw_parsetree_list; SelectStmt *stmt; - ResTarget *restarget; - A_Const *aconst; - TypeName *typename; + ResTarget *restarget; + A_Const *aconst; + TypeName *typename; buf = (char *) palloc(strlen(str) + 16); sprintf(buf, "SELECT (NULL::%s)", str); diff --git a/src/backend/parser/parser.c b/src/backend/parser/parser.c index 11f1fa6df3..7808705b37 100644 --- a/src/backend/parser/parser.c +++ b/src/backend/parser/parser.c @@ -14,7 +14,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/parser.c,v 1.49 2001/03/22 03:59:42 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/parser.c,v 1.50 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,7 +30,6 @@ #if defined(FLEX_SCANNER) extern void DeleteBuffer(void); - #endif /* FLEX_SCANNER */ char *parseString; /* the char* which holds the string to be diff --git a/src/backend/parser/scansup.c b/src/backend/parser/scansup.c index 66baed8840..3ee00fed6c 100644 --- a/src/backend/parser/scansup.c +++ b/src/backend/parser/scansup.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/parser/scansup.c,v 1.20 2001/01/24 19:43:03 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/parser/scansup.c,v 1.21 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -50,7 +50,6 @@ scanstr(char *s) { if (s[i] == '\'') { - /* * Note: if scanner is working right, unescaped quotes can * only appear in pairs, so there should be another character. diff --git a/src/backend/port/beos/sem.c b/src/backend/port/beos/sem.c index 3b829817ee..6609f1dde0 100644 --- a/src/backend/port/beos/sem.c +++ b/src/backend/port/beos/sem.c @@ -121,7 +121,6 @@ semctl(int semId, int semNum, int flag, union semun semun) TRACEDBGP("->semctl nmbre %d", Address[0]); for (i = 0; i < Address[0]; i++) { - /* * Make sure to have ownership of the semaphore (if created by * another team) @@ -294,7 +293,6 @@ semop(int semId, struct sembuf * sops, int nsops) /* For each sem in the pool, check the operation to perform */ if (sops[i].sem_op < 0) { - /* * Try acuiring the semaphore till we are not inteerupted by a * signal diff --git a/src/backend/port/beos/shm.c b/src/backend/port/beos/shm.c index 56e44d3853..7903ce74ad 100644 --- a/src/backend/port/beos/shm.c +++ b/src/backend/port/beos/shm.c @@ -48,7 +48,6 @@ shmat(int memId, int m1, int m2) if (ainfo.team == teinfo.team) { - /* * the area is already in our address space, just return the * address @@ -57,7 +56,6 @@ shmat(int memId, int m1, int m2) } else { - /* * the area is not in our address space, clone it before and * return the address diff --git a/src/backend/port/beos/support.c b/src/backend/port/beos/support.c index 936c151e86..996615e6fa 100644 --- a/src/backend/port/beos/support.c +++ b/src/backend/port/beos/support.c @@ -116,19 +116,17 @@ beos_dl_open(char *filename) } void -beos_dl_sym(image_id im,char* symname,void** fptr) +beos_dl_sym(image_id im, char *symname, void **fptr) { /* Send command '3' (get symbol) to the support server */ write_port(beos_dl_port_in, 3, symname, strlen(symname) + 1); - write_port(beos_dl_port_in, im, NULL,0); + write_port(beos_dl_port_in, im, NULL, 0); /* Read sym address */ - read_port(beos_dl_port_out, (int32*)(fptr), NULL, 0); + read_port(beos_dl_port_out, (int32 *) (fptr), NULL, 0); - if (fptr==NULL) - { + if (fptr == NULL) elog(NOTICE, "loading symbol '%s' failed ", symname); - } } status_t @@ -149,7 +147,6 @@ beos_startup(int argc, char **argv) { if (strlen(argv[0]) >= 10 && !strcmp(argv[0] + strlen(argv[0]) - 10, "postmaster")) { - /* * We are in the postmaster, create the protection semaphore for * shared mem remapping @@ -180,13 +177,13 @@ beos_startup(int argc, char **argv) * server */ read_port(port_in, &opcode, datas, 4000); - + switch (opcode) { image_id addon; image_info info_im; area_info info_ar; - void * fpt; + void *fpt; /* Load Add-On */ case 1: @@ -226,32 +223,32 @@ beos_startup(int argc, char **argv) break; /* Cleanup and exit */ case 3: - + /* read image Id on the input port */ - read_port(port_in, &addon,NULL,0); + read_port(port_in, &addon, NULL, 0); /* Loading symbol */ - fpt=NULL; - - - if (get_image_symbol(addon, datas, B_SYMBOL_TYPE_TEXT, &fpt) == B_OK); - { + fpt = NULL; + + if (get_image_symbol(addon, datas, B_SYMBOL_TYPE_TEXT, &fpt) == B_OK); + { /* - * Sometime the loader return B_OK for an inexistant function - * with an invalid address !!! Check that the return address - * is in the image range - */ + * Sometime the loader return B_OK for an + * inexistant function with an invalid address !!! + * Check that the return address is in the image + * range + */ get_image_info(addon, &info_im); if ((fpt < info_im.text) ||(fpt >= (info_im.text +info_im.text_size))) - fpt=NULL; + fpt = NULL; } /* Send back fptr of data segment */ - write_port(port_out, (int32)(fpt),NULL,0); + write_port(port_out, (int32) (fpt), NULL, 0); break; - + default: /* Free system resources */ delete_port(port_in); diff --git a/src/backend/port/darwin/sem.c b/src/backend/port/darwin/sem.c index 83fc1bf118..abb52c0b90 100644 --- a/src/backend/port/darwin/sem.c +++ b/src/backend/port/darwin/sem.c @@ -10,7 +10,7 @@ * - this required changing sem_info from containig an array of sem_t to an array of sem_t* * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/darwin/Attic/sem.c,v 1.4 2001/09/07 00:27:29 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/darwin/Attic/sem.c,v 1.5 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -47,10 +47,9 @@ struct sem_set_info key_t key; int nsems; sem_t *sem[SEMMAX]; /* array of POSIX semaphores */ - struct sem semV[SEMMAX]; /* array of System V semaphore - * structures */ - struct pending_ops pendingOps[SEMMAX]; /* array of pending - * operations */ + struct sem semV[SEMMAX]; /* array of System V semaphore structures */ + struct pending_ops pendingOps[SEMMAX]; /* array of pending + * operations */ }; struct sem_info @@ -58,7 +57,7 @@ struct sem_info sem_t *sem; int nsets; /* there are actually nsets of these: */ - struct sem_set_info set[1]; /* VARIABLE LENGTH ARRAY */ + struct sem_set_info set[1]; /* VARIABLE LENGTH ARRAY */ }; static struct sem_info *SemInfo = (struct sem_info *) - 1; @@ -171,7 +170,7 @@ semget(key_t key, int nsems, int semflg) shm_unlink(SHM_INFO_NAME); /* The size may only be set once. Ignore errors. */ nsets = PROC_SEM_MAP_ENTRIES(MaxBackends); - sem_info_size = sizeof(struct sem_info) + (nsets-1) * sizeof(struct sem_set_info); + sem_info_size = sizeof(struct sem_info) + (nsets - 1) * sizeof(struct sem_set_info); ftruncate(fd, sem_info_size); SemInfo = mmap(NULL, sem_info_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); @@ -260,13 +259,13 @@ semget(key_t key, int nsems, int semflg) /* Currently sem_init always returns -1. */ #ifdef NOT_USED - if( sem_init( &SemInfo->set[semid].sem[semnum], 1, 0 ) == -1 ) { - int semnum1; + if (sem_init(&SemInfo->set[semid].sem[semnum], 1, 0) == -1) + { + int semnum1; - for( semnum1 = 0; semnum1 < semnum; semnum1++ ) { - sem_close( SemInfo->set[semid].sem[semnum1] ); - } - sem_post( SemInfo->sem ); + for (semnum1 = 0; semnum1 < semnum; semnum1++) + sem_close(SemInfo->set[semid].sem[semnum1]); + sem_post(SemInfo->sem); return -1; } #endif diff --git a/src/backend/port/dynloader/aix.c b/src/backend/port/dynloader/aix.c index 44ae28d67d..46ef63a766 100644 --- a/src/backend/port/dynloader/aix.c +++ b/src/backend/port/dynloader/aix.c @@ -537,7 +537,6 @@ readExports(ModulePtr mp) symname = ls->l_offset + lhp->l_stoff + ldbuf; else { - /* * The l_name member is not zero terminated, we must copy the * first SYMNMLEN chars and make sure we have a zero byte at @@ -608,5 +607,4 @@ findMain(void) free(buf); return ret; } - #endif /* HAVE_DLOPEN */ diff --git a/src/backend/port/dynloader/aix.h b/src/backend/port/dynloader/aix.h index a0320727f3..203e56264a 100644 --- a/src/backend/port/dynloader/aix.h +++ b/src/backend/port/dynloader/aix.h @@ -1,5 +1,5 @@ /* - * $Id: aix.h,v 1.6 2001/05/14 21:45:53 petere Exp $ + * $Id: aix.h,v 1.7 2001/10/25 05:49:40 momjian Exp $ * * @(#)dlfcn.h 1.4 revision of 95/04/25 09:36:52 * This is an unpublished work copyright (c) 1992 HELIOS Software GmbH @@ -51,9 +51,7 @@ extern "C" #ifdef __cplusplus } - #endif - #endif /* HAVE_DLOPEN */ #include "utils/dynamic_loader.h" @@ -62,5 +60,4 @@ extern "C" #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/beos.c b/src/backend/port/dynloader/beos.c index 0a0f5fbef8..f91ffe1804 100644 --- a/src/backend/port/dynloader/beos.c +++ b/src/backend/port/dynloader/beos.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/dynloader/Attic/beos.c,v 1.8 2001/08/07 16:56:17 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/dynloader/Attic/beos.c,v 1.9 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -49,7 +49,7 @@ pg_dlsym(void *handle, char *funcname) /* Checking that "Handle" is valid */ if ((handle) && ((*(int *) (handle)) >= 0)) { - beos_dl_sym(*((int *) (handle)),funcname,(void **) &fpt); + beos_dl_sym(*((int *) (handle)), funcname, (void **) &fpt); return fpt; } elog(NOTICE, "add-on not loaded correctly"); diff --git a/src/backend/port/dynloader/beos.h b/src/backend/port/dynloader/beos.h index bec6743dca..dadf5f71b1 100644 --- a/src/backend/port/dynloader/beos.h +++ b/src/backend/port/dynloader/beos.h @@ -7,12 +7,11 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: beos.h,v 1.4 2001/01/24 19:43:04 momjian Exp $ + * $Id: beos.h,v 1.5 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ #ifndef PORT_PROTOS_H #define PORT_PROTOS_H - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/bsdi.c b/src/backend/port/dynloader/bsdi.c index bfa7ec9e77..c16af323a1 100644 --- a/src/backend/port/dynloader/bsdi.c +++ b/src/backend/port/dynloader/bsdi.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/dynloader/bsdi.c,v 1.15 2001/05/30 18:32:29 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/dynloader/bsdi.c,v 1.16 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -94,5 +94,4 @@ pg_dlerror() { return dld_strerror(dld_errno); } - -#endif /* not HAVE_DLOPEN */ +#endif /* not HAVE_DLOPEN */ diff --git a/src/backend/port/dynloader/bsdi.h b/src/backend/port/dynloader/bsdi.h index 2ea466317c..7d38de8277 100644 --- a/src/backend/port/dynloader/bsdi.h +++ b/src/backend/port/dynloader/bsdi.h @@ -24,7 +24,7 @@ #define pg_dlclose dlclose #define pg_dlerror dlerror -#else /* not HAVE_DLOPEN */ +#else /* not HAVE_DLOPEN */ #define pg_dlsym(handle, funcname) ((PGFunction) dld_get_func((funcname))) #define pg_dlclose(handle) \ @@ -32,7 +32,5 @@ do { \ dld_unlink_by_file(handle, 1); \ free(handle); \ } while (0) - -#endif /* not HAVE_DLOPEN */ - +#endif /* not HAVE_DLOPEN */ #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/dgux.h b/src/backend/port/dynloader/dgux.h index 15fb78a90b..8246906702 100644 --- a/src/backend/port/dynloader/dgux.h +++ b/src/backend/port/dynloader/dgux.h @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: dgux.h,v 1.10 2001/05/14 21:45:53 petere Exp $ + * $Id: dgux.h,v 1.11 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,5 +27,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/freebsd.c b/src/backend/port/dynloader/freebsd.c index c2a2e31f27..74f0b005e5 100644 --- a/src/backend/port/dynloader/freebsd.c +++ b/src/backend/port/dynloader/freebsd.c @@ -34,7 +34,6 @@ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)dl.c 5.4 (Berkeley) 2/23/91"; - #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> diff --git a/src/backend/port/dynloader/freebsd.h b/src/backend/port/dynloader/freebsd.h index ce5069f876..c7e36525ac 100644 --- a/src/backend/port/dynloader/freebsd.h +++ b/src/backend/port/dynloader/freebsd.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: freebsd.h,v 1.10 2001/05/15 16:55:27 petere Exp $ + * $Id: freebsd.h,v 1.11 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -43,5 +43,4 @@ char *BSD44_derived_dlerror(void); void *BSD44_derived_dlopen(const char *filename, int num); void *BSD44_derived_dlsym(void *handle, const char *name); void BSD44_derived_dlclose(void *handle); - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/hpux.c b/src/backend/port/dynloader/hpux.c index 967967e026..7cc539b14a 100644 --- a/src/backend/port/dynloader/hpux.c +++ b/src/backend/port/dynloader/hpux.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/dynloader/hpux.c,v 1.18 2001/03/22 03:59:43 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/dynloader/hpux.c,v 1.19 2001/10/25 05:49:40 momjian Exp $ * * NOTES * all functions are defined here -- it's impossible to trace the @@ -28,7 +28,6 @@ void * pg_dlopen(char *filename) { - /* * Use BIND_IMMEDIATE so that undefined symbols cause a failure return * from shl_load(), rather than an abort() later on when we attempt to diff --git a/src/backend/port/dynloader/irix5.h b/src/backend/port/dynloader/irix5.h index a4a5d134b6..f5e53bfc1b 100644 --- a/src/backend/port/dynloader/irix5.h +++ b/src/backend/port/dynloader/irix5.h @@ -30,5 +30,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/linux.c b/src/backend/port/dynloader/linux.c index 7de38938cf..796f22d3f2 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.18 2001/01/24 19:43:04 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/dynloader/linux.c,v 1.19 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -107,5 +107,4 @@ pg_dlerror() return dld_strerror(dld_errno); #endif } - #endif diff --git a/src/backend/port/dynloader/linux.h b/src/backend/port/dynloader/linux.h index 290771cfc0..2077a6a676 100644 --- a/src/backend/port/dynloader/linux.h +++ b/src/backend/port/dynloader/linux.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: linux.h,v 1.13 2001/10/25 01:29:37 momjian Exp $ + * $Id: linux.h,v 1.14 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -31,16 +31,13 @@ do { \ dld_unlink_by_file(handle, 1); \ free(handle); \ } while (0) - #endif -#else /* HAVE_DLOPEN */ +#else /* HAVE_DLOPEN */ #define pg_dlopen(f) dlopen((f), RTLD_LAZY | RTLD_GLOBAL) #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - -#endif /* HAVE_DLOPEN */ - +#endif /* HAVE_DLOPEN */ #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/netbsd.c b/src/backend/port/dynloader/netbsd.c index f2fd6666a2..dc28e3e9c4 100644 --- a/src/backend/port/dynloader/netbsd.c +++ b/src/backend/port/dynloader/netbsd.c @@ -34,7 +34,6 @@ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)dl.c 5.4 (Berkeley) 2/23/91"; - #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> diff --git a/src/backend/port/dynloader/netbsd.h b/src/backend/port/dynloader/netbsd.h index a1b48fa830..85cdfa3a85 100644 --- a/src/backend/port/dynloader/netbsd.h +++ b/src/backend/port/dynloader/netbsd.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: netbsd.h,v 1.5 2001/05/15 16:55:27 petere Exp $ + * $Id: netbsd.h,v 1.6 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -43,5 +43,4 @@ char *BSD44_derived_dlerror(void); void *BSD44_derived_dlopen(const char *filename, int num); void *BSD44_derived_dlsym(void *handle, const char *name); void BSD44_derived_dlclose(void *handle); - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/nextstep.h b/src/backend/port/dynloader/nextstep.h index d86c2c5cea..510243a1ac 100644 --- a/src/backend/port/dynloader/nextstep.h +++ b/src/backend/port/dynloader/nextstep.h @@ -22,5 +22,4 @@ char *next_dlerror(void); #define pg_dlerror next_dlerror /* port.c */ - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/openbsd.c b/src/backend/port/dynloader/openbsd.c index f2fd6666a2..dc28e3e9c4 100644 --- a/src/backend/port/dynloader/openbsd.c +++ b/src/backend/port/dynloader/openbsd.c @@ -34,7 +34,6 @@ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)dl.c 5.4 (Berkeley) 2/23/91"; - #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> diff --git a/src/backend/port/dynloader/openbsd.h b/src/backend/port/dynloader/openbsd.h index 557003a5a0..899f213011 100644 --- a/src/backend/port/dynloader/openbsd.h +++ b/src/backend/port/dynloader/openbsd.h @@ -5,7 +5,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: openbsd.h,v 1.6 2001/06/20 18:33:31 petere Exp $ + * $Id: openbsd.h,v 1.7 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -41,5 +41,4 @@ char *BSD44_derived_dlerror(void); void *BSD44_derived_dlopen(const char *filename, int num); void *BSD44_derived_dlsym(void *handle, const char *name); void BSD44_derived_dlclose(void *handle); - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/osf.h b/src/backend/port/dynloader/osf.h index 61961b02d6..e24ae4f85d 100644 --- a/src/backend/port/dynloader/osf.h +++ b/src/backend/port/dynloader/osf.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: osf.h,v 1.3 2001/05/14 21:45:53 petere Exp $ + * $Id: osf.h,v 1.4 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -32,5 +32,4 @@ #define pg_dlsym(h, f) ((PGFunction) dlsym(h, f)) #define pg_dlclose(h) dlclose(h) #define pg_dlerror() dlerror() - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/sco.h b/src/backend/port/dynloader/sco.h index 70ead4fa8d..577706d27e 100644 --- a/src/backend/port/dynloader/sco.h +++ b/src/backend/port/dynloader/sco.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: sco.h,v 1.8 2001/05/14 21:45:53 petere Exp $ + * $Id: sco.h,v 1.9 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -32,5 +32,4 @@ #define pg_dlerror dlerror /* port.c */ - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/solaris.h b/src/backend/port/dynloader/solaris.h index e4b81f435f..ca920923c4 100644 --- a/src/backend/port/dynloader/solaris.h +++ b/src/backend/port/dynloader/solaris.h @@ -1,4 +1,4 @@ -/* $Header: /cvsroot/pgsql/src/backend/port/dynloader/solaris.h,v 1.4 2001/05/14 21:45:53 petere Exp $ */ +/* $Header: /cvsroot/pgsql/src/backend/port/dynloader/solaris.h,v 1.5 2001/10/25 05:49:40 momjian Exp $ */ #ifndef DYNLOADER_SOLARIS_H #define DYNLOADER_SOLARIS_H @@ -10,5 +10,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* DYNLOADER_SOLARIS_H */ diff --git a/src/backend/port/dynloader/sunos4.h b/src/backend/port/dynloader/sunos4.h index 49040c1dea..fee5f00a3b 100644 --- a/src/backend/port/dynloader/sunos4.h +++ b/src/backend/port/dynloader/sunos4.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: sunos4.h,v 1.8 2001/05/14 21:45:53 petere Exp $ + * $Id: sunos4.h,v 1.9 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,5 +30,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/svr4.h b/src/backend/port/dynloader/svr4.h index 96c39ea2ec..af3d6d54f9 100644 --- a/src/backend/port/dynloader/svr4.h +++ b/src/backend/port/dynloader/svr4.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: svr4.h,v 1.8 2001/05/14 21:45:53 petere Exp $ + * $Id: svr4.h,v 1.9 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,5 +30,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* DYNLOADER_H */ diff --git a/src/backend/port/dynloader/ultrix4.h b/src/backend/port/dynloader/ultrix4.h index 817398d7f4..68504d0ac2 100644 --- a/src/backend/port/dynloader/ultrix4.h +++ b/src/backend/port/dynloader/ultrix4.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: ultrix4.h,v 1.7 2001/01/24 19:43:04 momjian Exp $ + * $Id: ultrix4.h,v 1.8 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -55,9 +55,9 @@ typedef struct ScnInfo typedef enum { - DL_NEEDRELOC, /* still need relocation */ - DL_RELOCATED, /* no relocation necessary */ - DL_INPROG /* relocation in progress */ + DL_NEEDRELOC, /* still need relocation */ + DL_RELOCATED, /* no relocation necessary */ + DL_INPROG /* relocation in progress */ } dlRStatus; typedef struct JmpTbl @@ -120,5 +120,4 @@ extern char *dl_error( /* void */ ); extern char **dl_undefinedSymbols( /* int *count */ ); extern void dl_printAllSymbols( /* void *handle */ ); extern void dl_setLibraries( /* char *libs */ ); - #endif /* _DL_HEADER_ */ diff --git a/src/backend/port/dynloader/univel.h b/src/backend/port/dynloader/univel.h index 83f0e2c82a..694d87c3fa 100644 --- a/src/backend/port/dynloader/univel.h +++ b/src/backend/port/dynloader/univel.h @@ -30,5 +30,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/unixware.h b/src/backend/port/dynloader/unixware.h index 5c1b04cc69..0d0b80721d 100644 --- a/src/backend/port/dynloader/unixware.h +++ b/src/backend/port/dynloader/unixware.h @@ -30,5 +30,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/dynloader/win.h b/src/backend/port/dynloader/win.h index d0d33189b7..0bc8cdb062 100644 --- a/src/backend/port/dynloader/win.h +++ b/src/backend/port/dynloader/win.h @@ -30,5 +30,4 @@ #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror - #endif /* PORT_PROTOS_H */ diff --git a/src/backend/port/inet_aton.c b/src/backend/port/inet_aton.c index 81f20da967..8f7c4e255a 100644 --- a/src/backend/port/inet_aton.c +++ b/src/backend/port/inet_aton.c @@ -1,4 +1,4 @@ -/* $Id: inet_aton.c,v 1.19 2001/08/24 14:07:49 petere Exp $ +/* $Id: inet_aton.c,v 1.20 2001/10/25 05:49:40 momjian Exp $ * * This inet_aton() function was taken from the GNU C library and * incorporated into Postgres for those systems which do not have this @@ -67,7 +67,6 @@ inet_aton(const char *cp, struct in_addr * addr) for (;;) { - /* * Collect number up to ``.''. Values are specified as for C: * 0x=hex, 0=octal, other=decimal. @@ -100,7 +99,6 @@ inet_aton(const char *cp, struct in_addr * addr) } if (*cp == '.') { - /* * Internet format: a.b.c.d a.b.c (with c treated as * 16-bits) a.b (with b treated as 24 bits) diff --git a/src/backend/port/isinf.c b/src/backend/port/isinf.c index f589f47816..f660b8a443 100644 --- a/src/backend/port/isinf.c +++ b/src/backend/port/isinf.c @@ -1,4 +1,4 @@ -/* $Id: isinf.c,v 1.16 2001/08/24 14:07:49 petere Exp $ */ +/* $Id: isinf.c,v 1.17 2001/10/25 05:49:40 momjian Exp $ */ #include "c.h" @@ -42,7 +42,6 @@ double x; #else int fpclass = fp_class_d(x); - #endif if (fpclass == FP_POS_INF) @@ -64,7 +63,6 @@ isinf(double x) return -1; return 0; } - #endif #endif @@ -80,5 +78,4 @@ isinf(double x) return -1; return 0; } - #endif diff --git a/src/backend/port/nextstep/port.c b/src/backend/port/nextstep/port.c index 6ef1b126f4..8f6deeb44f 100644 --- a/src/backend/port/nextstep/port.c +++ b/src/backend/port/nextstep/port.c @@ -55,5 +55,4 @@ getcwd(char *buf, size_t size) { return getwd(buf); } - #endif diff --git a/src/backend/port/qnx4/ipc.h b/src/backend/port/qnx4/ipc.h index 3f1206d31f..291347de35 100644 --- a/src/backend/port/qnx4/ipc.h +++ b/src/backend/port/qnx4/ipc.h @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/ipc.h,v 1.3 2001/03/18 18:32:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/ipc.h,v 1.4 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,5 +27,4 @@ /* Control Commands. */ #define IPC_RMID 0 /* remove identifier */ #define IPC_STAT 1 /* get shm status */ - #endif /* _SYS_IPC_H */ diff --git a/src/backend/port/qnx4/sem.c b/src/backend/port/qnx4/sem.c index a25ba759ee..ed70d45229 100644 --- a/src/backend/port/qnx4/sem.c +++ b/src/backend/port/qnx4/sem.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/sem.c,v 1.7 2001/09/07 00:27:29 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/sem.c,v 1.8 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -48,10 +48,9 @@ struct sem_set_info key_t key; int nsems; sem_t sem[SEMMAX]; /* array of POSIX semaphores */ - struct sem semV[SEMMAX]; /* array of System V semaphore - * structures */ - struct pending_ops pendingOps[SEMMAX]; /* array of pending - * operations */ + struct sem semV[SEMMAX]; /* array of System V semaphore structures */ + struct pending_ops pendingOps[SEMMAX]; /* array of pending + * operations */ }; struct sem_info @@ -59,21 +58,21 @@ struct sem_info sem_t sem; int nsets; /* there are actually nsets of these: */ - struct sem_set_info set[1]; /* VARIABLE LENGTH ARRAY */ + struct sem_set_info set[1]; /* VARIABLE LENGTH ARRAY */ }; static struct sem_info *SemInfo = (struct sem_info *) - 1; /* ---------------------------------------------------------------- * semclean - remove the shared memory file on exit - * only called by the process which created the shm file + * only called by the process which created the shm file * ---------------------------------------------------------------- */ static void -semclean( void ) +semclean(void) { - remove( "/dev/shmem/" SHM_INFO_NAME ); + remove("/dev/shmem/" SHM_INFO_NAME); } int @@ -175,30 +174,31 @@ semget(key_t key, int nsems, int semflg) return fd; /* The size may only be set once. Ignore errors. */ nsets = PROC_SEM_MAP_ENTRIES(MaxBackends); - sem_info_size = sizeof(struct sem_info) + (nsets-1) * sizeof(struct sem_set_info); + sem_info_size = sizeof(struct sem_info) + (nsets - 1) * sizeof(struct sem_set_info); ltrunc(fd, sem_info_size, SEEK_SET); - if ( fstat( fd, &statbuf ) ) /* would be strange : the only doc'ed */ - { /* error is EBADF */ - close( fd ); + if (fstat(fd, &statbuf))/* would be strange : the only doc'ed */ + { /* error is EBADF */ + close(fd); + return -1; + } + + /* + * size is rounded by proc to the next __PAGESIZE + */ + if (statbuf.st_size != + (((sem_info_size / __PAGESIZE) + 1) * __PAGESIZE)) + { + fprintf(stderr, + "Found a pre-existing shared memory block for the semaphore memory\n" + "of a different size (%ld instead %ld). Make sure that all executables\n" + "are from the same release or remove the file \"/dev/shmem/%s\"\n" + "left by a previous version.\n", + (long) statbuf.st_size, + (long) sem_info_size, + SHM_INFO_NAME); + errno = EACCES; return -1; } - /* - * size is rounded by proc to the next __PAGESIZE - */ - if ( statbuf.st_size != - (((sem_info_size/__PAGESIZE)+1) * __PAGESIZE) ) - { - fprintf( stderr, - "Found a pre-existing shared memory block for the semaphore memory\n" - "of a different size (%ld instead %ld). Make sure that all executables\n" - "are from the same release or remove the file \"/dev/shmem/%s\"\n" - "left by a previous version.\n", - (long) statbuf.st_size, - (long) sem_info_size, - SHM_INFO_NAME); - errno = EACCES; - return -1; - } SemInfo = mmap(NULL, sem_info_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (SemInfo == MAP_FAILED) @@ -212,7 +212,7 @@ semget(key_t key, int nsems, int semflg) SemInfo->set[semid].key = -1; /* create semaphore for locking */ sem_init(&SemInfo->sem, 1, 1); - on_proc_exit( semclean, 0 ); + on_proc_exit(semclean, 0); } } @@ -269,13 +269,13 @@ semget(key_t key, int nsems, int semflg) sem_init(&SemInfo->set[semid].sem[semnum], 1, 0); /* Currently sem_init always returns -1. */ #ifdef NOT_USED - if( sem_init( &SemInfo->set[semid].sem[semnum], 1, 0 ) == -1 ) { - int semnum1; + if (sem_init(&SemInfo->set[semid].sem[semnum], 1, 0) == -1) + { + int semnum1; - for( semnum1 = 0; semnum1 < semnum; semnum1++ ) { - sem_destroy( &SemInfo->set[semid].sem[semnum1] ); - } - sem_post( &SemInfo->sem ); + for (semnum1 = 0; semnum1 < semnum; semnum1++) + sem_destroy(&SemInfo->set[semid].sem[semnum1]); + sem_post(&SemInfo->sem); return -1; } #endif diff --git a/src/backend/port/qnx4/sem.h b/src/backend/port/qnx4/sem.h index c9fd18a05a..3ac7f6ff17 100644 --- a/src/backend/port/qnx4/sem.h +++ b/src/backend/port/qnx4/sem.h @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/sem.h,v 1.3 2000/04/12 17:15:30 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/sem.h,v 1.4 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -63,7 +63,5 @@ extern "C" #ifdef __cplusplus } - #endif - #endif /* _SYS_SEM_H */ diff --git a/src/backend/port/qnx4/shm.c b/src/backend/port/qnx4/shm.c index 466c4b4b40..cf42be4d85 100644 --- a/src/backend/port/qnx4/shm.c +++ b/src/backend/port/qnx4/shm.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/shm.c,v 1.6 2001/08/24 14:07:49 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/shm.c,v 1.7 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -48,8 +48,8 @@ static int shm_getinfobyaddr(const void *addr, struct shm_info * info); static char * keytoname(key_t key, char *name) { - sprintf( name,"PgShm%x", key ); - return name; + sprintf(name, "PgShm%x", key); + return name; } static int @@ -182,51 +182,53 @@ shmctl(int shmid, int cmd, struct shmid_ds * buf) { struct shm_info info; char name[NAME_MAX + 1]; - int result; - int fd; - struct stat statbuf; + int result; + int fd; + struct stat statbuf; - - switch( cmd ) - { - case IPC_RMID : - if (shm_getinfo(shmid, &info) == -1) - { - errno = EACCES; - return -1; - } - close( info.shmid ); - keytoname(info.key, name); - return shm_unlink( name ); - - case IPC_STAT : - /* - * we have to open it first. stat() does no prefix tracking - * -> the call would go to fsys instead of proc - */ - keytoname(shmid, name); - fd = shm_open( name, 0, MODE ); - if ( fd >= 0 ) - { - result = fstat( fd, &statbuf ); - /* - * if the file exists, subtract 2 from linkcount : - * one for our own open and one for the dir entry - */ - if ( ! result ) - buf->shm_nattch = statbuf.st_nlink-2; - close( fd ); - return result; - } - else + + switch (cmd) { - /* - * if there's no entry for this key it doesn't matter - * the next shmget() would get a different shm anyway - */ - buf->shm_nattch = 0; - return 0; - } + case IPC_RMID: + if (shm_getinfo(shmid, &info) == -1) + { + errno = EACCES; + return -1; + } + close(info.shmid); + keytoname(info.key, name); + return shm_unlink(name); + + case IPC_STAT: + + /* + * we have to open it first. stat() does no prefix tracking -> + * the call would go to fsys instead of proc + */ + keytoname(shmid, name); + fd = shm_open(name, 0, MODE); + if (fd >= 0) + { + result = fstat(fd, &statbuf); + + /* + * if the file exists, subtract 2 from linkcount : one for + * our own open and one for the dir entry + */ + if (!result) + buf->shm_nattch = statbuf.st_nlink - 2; + close(fd); + return result; + } + else + { + /* + * if there's no entry for this key it doesn't matter the + * next shmget() would get a different shm anyway + */ + buf->shm_nattch = 0; + return 0; + } } errno = EINVAL; return -1; @@ -258,13 +260,13 @@ shmget(key_t key, size_t size, int flags) info.key = key; info.size = size; info.addr = NULL; - if (shm_putinfo(&info) == -1) { - close( info.shmid ); - if ( (oflag & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL) ) { - shm_unlink( name ); - } + if (shm_putinfo(&info) == -1) + { + close(info.shmid); + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) + shm_unlink(name); return -1; - } + } } /* The size may only be set once. Ignore errors. */ diff --git a/src/backend/port/qnx4/shm.h b/src/backend/port/qnx4/shm.h index 40fc9caa26..47d8a37658 100644 --- a/src/backend/port/qnx4/shm.h +++ b/src/backend/port/qnx4/shm.h @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/shm.h,v 1.3 2001/03/18 18:32:02 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/shm.h,v 1.4 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -38,7 +38,5 @@ extern "C" #ifdef __cplusplus } - #endif - #endif /* _SYS_SHM_H */ diff --git a/src/backend/port/qnx4/tstsem.c b/src/backend/port/qnx4/tstsem.c index 571a6def25..bd35e5706c 100644 --- a/src/backend/port/qnx4/tstsem.c +++ b/src/backend/port/qnx4/tstsem.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/tstsem.c,v 1.5 2001/08/24 14:07:49 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/port/qnx4/Attic/tstsem.c,v 1.6 2001/10/25 05:49:40 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -40,9 +40,9 @@ sig_handler(int sig_no) printf("semval = %d\n", i); } -void on_proc_exit( void (*function)(), Datum arg ) +void on_proc_exit(void (*function) (), Datum arg) { - atexit( function ); + atexit(function); } int main(int argc, char **argv) diff --git a/src/backend/port/snprintf.c b/src/backend/port/snprintf.c index bfd7705a2a..047e94fcfa 100644 --- a/src/backend/port/snprintf.c +++ b/src/backend/port/snprintf.c @@ -50,7 +50,6 @@ typedef unsigned long long ulong_long; #else typedef long long_long; typedef unsigned long ulong_long; - #endif /* @@ -75,7 +74,7 @@ typedef unsigned long ulong_long; * causing nast effects. **************************************************************/ -/*static char _id[] = "$Id: snprintf.c,v 1.30 2001/02/10 02:31:26 tgl Exp $";*/ +/*static char _id[] = "$Id: snprintf.c,v 1.31 2001/10/25 05:49:40 momjian Exp $";*/ static char *end; static int SnprfOverflow; diff --git a/src/backend/port/strcasecmp.c b/src/backend/port/strcasecmp.c index 32c21cb7c8..5bb34f8549 100644 --- a/src/backend/port/strcasecmp.c +++ b/src/backend/port/strcasecmp.c @@ -1,4 +1,4 @@ -/* $Id: strcasecmp.c,v 1.7 2001/01/24 19:43:03 momjian Exp $ */ +/* $Id: strcasecmp.c,v 1.8 2001/10/25 05:49:40 momjian Exp $ */ /* * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group @@ -15,7 +15,6 @@ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strcasecmp.c 5.5 (Berkeley) 11/24/87"; - #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> diff --git a/src/backend/port/strtol.c b/src/backend/port/strtol.c index 4e72275529..e6a7fb6d7b 100644 --- a/src/backend/port/strtol.c +++ b/src/backend/port/strtol.c @@ -34,7 +34,6 @@ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strtol.c 5.4 (Berkeley) 2/23/91"; - #endif /* LIBC_SCCS and not lint */ #include <limits.h> diff --git a/src/backend/port/strtoul.c b/src/backend/port/strtoul.c index 0359791bd3..9481ccc4a0 100644 --- a/src/backend/port/strtoul.c +++ b/src/backend/port/strtoul.c @@ -33,7 +33,6 @@ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strtoul.c 8.1 (Berkeley) 6/4/93"; - #endif /* LIBC_SCCS and not lint */ #include <limits.h> diff --git a/src/backend/port/sunos4/float.h b/src/backend/port/sunos4/float.h index 5c138211c9..438deaf6ad 100644 --- a/src/backend/port/sunos4/float.h +++ b/src/backend/port/sunos4/float.h @@ -7,7 +7,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: float.h,v 1.6 2001/01/24 19:43:04 momjian Exp $ + * $Id: float.h,v 1.7 2001/10/25 05:49:40 momjian Exp $ * * NOTES * These come straight out of ANSI X3.159-1989 (p.18) and @@ -27,5 +27,4 @@ #define DBL_DIG 15 #define DBL_MIN 2.2250738585072014e-308 #define DBL_MAX 1.7976931348623157e+308 - #endif /* FLOAT_H */ diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c index 6aae169202..b77c129ddf 100644 --- a/src/backend/postmaster/pgstat.c +++ b/src/backend/postmaster/pgstat.c @@ -16,7 +16,7 @@ * * Copyright (c) 2001, PostgreSQL Global Development Group * - * $Header: /cvsroot/pgsql/src/backend/postmaster/pgstat.c,v 1.13 2001/10/22 19:41:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/postmaster/pgstat.c,v 1.14 2001/10/25 05:49:40 momjian Exp $ * ---------- */ #include "postgres.h" @@ -53,70 +53,70 @@ * GUC parameters * ---------- */ -bool pgstat_collect_startcollector = true; -bool pgstat_collect_resetonpmstart = true; -bool pgstat_collect_querystring = false; -bool pgstat_collect_tuplelevel = false; -bool pgstat_collect_blocklevel = false; +bool pgstat_collect_startcollector = true; +bool pgstat_collect_resetonpmstart = true; +bool pgstat_collect_querystring = false; +bool pgstat_collect_tuplelevel = false; +bool pgstat_collect_blocklevel = false; /* ---------- * Local data * ---------- */ -static int pgStatSock = -1; -static int pgStatPipe[2]; -static struct sockaddr_in pgStatAddr; -static int pgStatPmPipe[2] = { -1, -1 }; +static int pgStatSock = -1; +static int pgStatPipe[2]; +static struct sockaddr_in pgStatAddr; +static int pgStatPmPipe[2] = {-1, -1}; -static int pgStatRunning = 0; -static int pgStatPid; +static int pgStatRunning = 0; +static int pgStatPid; -static long pgStatNumMessages = 0; +static long pgStatNumMessages = 0; -static bool pgStatRunningInCollector = FALSE; -static int pgStatTabstatAlloc = 0; -static int pgStatTabstatUsed = 0; -static PgStat_MsgTabstat **pgStatTabstatMessages = NULL; -static int pgStatXactCommit = 0; -static int pgStatXactRollback = 0; +static bool pgStatRunningInCollector = FALSE; +static int pgStatTabstatAlloc = 0; +static int pgStatTabstatUsed = 0; +static PgStat_MsgTabstat **pgStatTabstatMessages = NULL; +static int pgStatXactCommit = 0; +static int pgStatXactRollback = 0; -static TransactionId pgStatDBHashXact = InvalidTransactionId; -static HTAB *pgStatDBHash = NULL; -static HTAB *pgStatBeDead = NULL; -static PgStat_StatBeEntry *pgStatBeTable = NULL; -static int pgStatNumBackends = 0; +static TransactionId pgStatDBHashXact = InvalidTransactionId; +static HTAB *pgStatDBHash = NULL; +static HTAB *pgStatBeDead = NULL; +static PgStat_StatBeEntry *pgStatBeTable = NULL; +static int pgStatNumBackends = 0; -static char pgStat_tmpfname[MAXPGPATH]; -static char pgStat_fname[MAXPGPATH]; +static char pgStat_tmpfname[MAXPGPATH]; +static char pgStat_fname[MAXPGPATH]; /* ---------- * Local function forward declarations * ---------- */ -static void pgstat_main(void); -static void pgstat_recvbuffer(void); -static void pgstat_die(SIGNAL_ARGS); - -static int pgstat_add_backend(PgStat_MsgHdr *msg); -static void pgstat_sub_backend(int procpid); -static void pgstat_drop_database(Oid databaseid); -static void pgstat_write_statsfile(void); -static void pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, - PgStat_StatBeEntry **betab, - int *numbackends); - -static void pgstat_setheader(PgStat_MsgHdr *hdr, int mtype); -static void pgstat_send(void *msg, int len); - -static void pgstat_recv_bestart(PgStat_MsgBestart *msg, int len); -static void pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len); -static void pgstat_recv_activity(PgStat_MsgActivity *msg, int len); -static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len); -static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len); -static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len); -static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len); +static void pgstat_main(void); +static void pgstat_recvbuffer(void); +static void pgstat_die(SIGNAL_ARGS); + +static int pgstat_add_backend(PgStat_MsgHdr *msg); +static void pgstat_sub_backend(int procpid); +static void pgstat_drop_database(Oid databaseid); +static void pgstat_write_statsfile(void); +static void pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, + PgStat_StatBeEntry **betab, + int *numbackends); + +static void pgstat_setheader(PgStat_MsgHdr *hdr, int mtype); +static void pgstat_send(void *msg, int len); + +static void pgstat_recv_bestart(PgStat_MsgBestart *msg, int len); +static void pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len); +static void pgstat_recv_activity(PgStat_MsgActivity *msg, int len); +static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len); +static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len); +static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len); +static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len); /* ------------------------------------------------------------ @@ -141,21 +141,20 @@ pgstat_init(void) * Force start of collector daemon if something to collect */ if (pgstat_collect_querystring || pgstat_collect_tuplelevel || - pgstat_collect_blocklevel) + pgstat_collect_blocklevel) pgstat_collect_startcollector = true; /* * Initialize the filenames for the status reports. */ - snprintf(pgStat_tmpfname, MAXPGPATH, - PGSTAT_STAT_TMPFILE, DataDir, getpid()); - snprintf(pgStat_fname, MAXPGPATH, - PGSTAT_STAT_FILENAME, DataDir); + snprintf(pgStat_tmpfname, MAXPGPATH, + PGSTAT_STAT_TMPFILE, DataDir, getpid()); + snprintf(pgStat_fname, MAXPGPATH, + PGSTAT_STAT_FILENAME, DataDir); /* - * If we don't have to start a collector or should reset the - * collected statistics on postmaster start, simply remove the - * file. + * If we don't have to start a collector or should reset the collected + * statistics on postmaster start, simply remove the file. */ if (!pgstat_collect_startcollector || pgstat_collect_resetonpmstart) unlink(pgStat_fname); @@ -176,21 +175,21 @@ pgstat_init(void) } /* - * Bind it to a kernel assigned port on localhost and - * get the assigned port via getsockname(). + * Bind it to a kernel assigned port on localhost and get the assigned + * port via getsockname(). */ - pgStatAddr.sin_family = AF_INET; - pgStatAddr.sin_port = htons(0); + pgStatAddr.sin_family = AF_INET; + pgStatAddr.sin_port = htons(0); inet_aton("127.0.0.1", &(pgStatAddr.sin_addr)); alen = sizeof(pgStatAddr); - if (bind(pgStatSock, (struct sockaddr *)&pgStatAddr, alen) < 0) + if (bind(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0) { perror("PGSTAT: bind(2)"); close(pgStatSock); pgStatSock = -1; return -1; } - if (getsockname(pgStatSock, (struct sockaddr *)&pgStatAddr, &alen) < 0) + if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0) { perror("PGSTAT: getsockname(2)"); close(pgStatSock); @@ -199,12 +198,12 @@ pgstat_init(void) } /* - * Connect the socket to its own address. This saves a few cycles - * by not having to respecify the target address on every send. - * This also provides a kernel-level check that only packets from - * this same address will be received. + * Connect the socket to its own address. This saves a few cycles by + * not having to respecify the target address on every send. This also + * provides a kernel-level check that only packets from this same + * address will be received. */ - if (connect(pgStatSock, (struct sockaddr *)&pgStatAddr, alen) < 0) + if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0) { perror("PGSTAT: connect(2)"); close(pgStatSock); @@ -262,8 +261,8 @@ pgstat_start(void) */ if (pgStatSock < 0) { - fprintf(stderr, - "PGSTAT: suppress collector startup due to missing socket\n"); + fprintf(stderr, + "PGSTAT: suppress collector startup due to missing socket\n"); return 0; } @@ -279,7 +278,7 @@ pgstat_start(void) beos_before_backend_startup(); #endif - switch ((pgStatPid = (int)fork())) + switch ((pgStatPid = (int) fork())) { case -1: #ifdef __BEOS__ @@ -367,15 +366,15 @@ pgstat_close_sockets(void) void pgstat_beterm(int pid) { - PgStat_MsgBeterm msg; + PgStat_MsgBeterm msg; if (!pgstat_collect_startcollector || pgStatSock < 0) return; - msg.m_hdr.m_type = PGSTAT_MTYPE_BETERM; - msg.m_hdr.m_backendid = 0; - msg.m_hdr.m_procpid = pid; - msg.m_hdr.m_databaseid = 0; + msg.m_hdr.m_type = PGSTAT_MTYPE_BETERM; + msg.m_hdr.m_backendid = 0; + msg.m_hdr.m_procpid = pid; + msg.m_hdr.m_databaseid = 0; pgstat_send(&msg, sizeof(msg)); } @@ -383,7 +382,7 @@ pgstat_beterm(int pid) /* ------------------------------------------------------------ * Public functions used by backends follow - *------------------------------------------------------------ + *------------------------------------------------------------ */ @@ -397,7 +396,7 @@ pgstat_beterm(int pid) void pgstat_bestart(void) { - PgStat_MsgBestart msg; + PgStat_MsgBestart msg; if (!pgstat_collect_startcollector || pgStatSock < 0) return; @@ -418,8 +417,8 @@ pgstat_bestart(void) void pgstat_report_activity(char *what) { - PgStat_MsgActivity msg; - int len; + PgStat_MsgActivity msg; + int len; if (!pgstat_collect_querystring || pgStatSock < 0) return; @@ -427,10 +426,10 @@ pgstat_report_activity(char *what) len = strlen(what); if (len >= PGSTAT_ACTIVITY_SIZE) len = PGSTAT_ACTIVITY_SIZE - 1; - + memcpy(msg.m_what, what, len); msg.m_what[len] = '\0'; - len += offsetof(PgStat_MsgActivity, m_what) + 1; + len += offsetof(PgStat_MsgActivity, m_what) +1; pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ACTIVITY); pgstat_send(&msg, len); @@ -447,33 +446,33 @@ pgstat_report_activity(char *what) void pgstat_report_tabstat(void) { - int i; - int n; - int len; + int i; + int n; + int len; if (!pgstat_collect_querystring && !pgstat_collect_tuplelevel && - !pgstat_collect_blocklevel) + !pgstat_collect_blocklevel) return; if (pgStatSock < 0) return; /* - * For each message buffer used during the last query - * set the header fields and send it out. + * For each message buffer used during the last query set the header + * fields and send it out. */ for (i = 0; i < pgStatTabstatUsed; i++) { n = pgStatTabstatMessages[i]->m_nentries; len = offsetof(PgStat_MsgTabstat, m_entry[n]); - pgStatTabstatMessages[i]->m_xact_commit = pgStatXactCommit; + pgStatTabstatMessages[i]->m_xact_commit = pgStatXactCommit; pgStatTabstatMessages[i]->m_xact_rollback = pgStatXactRollback; - pgStatXactCommit = 0; + pgStatXactCommit = 0; pgStatXactRollback = 0; - pgstat_setheader(&pgStatTabstatMessages[i]->m_hdr, - PGSTAT_MTYPE_TABSTAT); + pgstat_setheader(&pgStatTabstatMessages[i]->m_hdr, + PGSTAT_MTYPE_TABSTAT); pgstat_send(pgStatTabstatMessages[i], len); } @@ -490,28 +489,28 @@ pgstat_report_tabstat(void) int pgstat_vacuum_tabstat(void) { - Relation dbrel; - HeapScanDesc dbscan; - HeapTuple dbtup; - Oid *dbidlist; - int dbidalloc; - int dbidused; - HASH_SEQ_STATUS hstat; - PgStat_StatDBEntry *dbentry; - PgStat_StatTabEntry *tabentry; - HeapTuple reltup; - int nobjects = 0; - PgStat_MsgTabpurge msg; - int len; - int i; + Relation dbrel; + HeapScanDesc dbscan; + HeapTuple dbtup; + Oid *dbidlist; + int dbidalloc; + int dbidused; + HASH_SEQ_STATUS hstat; + PgStat_StatDBEntry *dbentry; + PgStat_StatTabEntry *tabentry; + HeapTuple reltup; + int nobjects = 0; + PgStat_MsgTabpurge msg; + int len; + int i; if (pgStatSock < 0) return 0; /* - * We don't vacuum inside of transaction blocks, because - * a possible later rollback might reactivate objects we - * didn't find because of earlier destruction in the xact. + * We don't vacuum inside of transaction blocks, because a possible + * later rollback might reactivate objects we didn't find because of + * earlier destruction in the xact. */ if (IsTransactionBlock()) return 0; @@ -522,7 +521,7 @@ pgstat_vacuum_tabstat(void) */ if (!TransactionIdEquals(pgStatDBHashXact, GetCurrentTransactionId())) { - pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, + pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, &pgStatBeTable, &pgStatNumBackends); pgStatDBHashXact = GetCurrentTransactionId(); } @@ -530,9 +529,9 @@ pgstat_vacuum_tabstat(void) /* * Lookup our own database entry */ - dbentry = (PgStat_StatDBEntry *)hash_search(pgStatDBHash, - (void *) &MyDatabaseId, - HASH_FIND, NULL); + dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash, + (void *) &MyDatabaseId, + HASH_FIND, NULL); if (dbentry == NULL) return -1; @@ -547,17 +546,16 @@ pgstat_vacuum_tabstat(void) /* * Check for all tables if they still exist. */ - hash_seq_init(&hstat, dbentry->tables); + hash_seq_init(&hstat, dbentry->tables); while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL) { /* - * Check if this relation is still alive by - * looking up it's pg_class tuple in the - * system catalog cache. + * Check if this relation is still alive by looking up it's + * pg_class tuple in the system catalog cache. */ reltup = SearchSysCache(RELOID, - ObjectIdGetDatum(tabentry->tableid), - 0, 0, 0); + ObjectIdGetDatum(tabentry->tableid), + 0, 0, 0); if (HeapTupleIsValid(reltup)) { ReleaseSysCache(reltup); @@ -600,7 +598,7 @@ pgstat_vacuum_tabstat(void) */ dbidalloc = 256; dbidused = 0; - dbidlist = (Oid *)palloc(sizeof(Oid) * dbidalloc); + dbidlist = (Oid *) palloc(sizeof(Oid) * dbidalloc); dbrel = heap_openr(DatabaseRelationName, AccessShareLock); dbscan = heap_beginscan(dbrel, 0, SnapshotNow, 0, NULL); @@ -609,8 +607,8 @@ pgstat_vacuum_tabstat(void) if (dbidused >= dbidalloc) { dbidalloc *= 2; - dbidlist = (Oid *)repalloc((char *)dbidlist, - sizeof(Oid) * dbidalloc); + dbidlist = (Oid *) repalloc((char *) dbidlist, + sizeof(Oid) * dbidalloc); } dbidlist[dbidused++] = dbtup->t_data->t_oid; } @@ -618,13 +616,13 @@ pgstat_vacuum_tabstat(void) heap_close(dbrel, AccessShareLock); /* - * Search the database hash table for dead databases and - * tell the collector to drop them as well. + * Search the database hash table for dead databases and tell the + * collector to drop them as well. */ hash_seq_init(&hstat, pgStatDBHash); while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL) { - Oid dbid = dbentry->databaseid; + Oid dbid = dbentry->databaseid; for (i = 0; i < dbidused; i++) { @@ -645,7 +643,7 @@ pgstat_vacuum_tabstat(void) /* * Free the dbid list. */ - pfree((char *)dbidlist); + pfree((char *) dbidlist); /* * Tell the caller how many removeable objects we found @@ -666,7 +664,7 @@ pgstat_vacuum_tabstat(void) static void pgstat_drop_database(Oid databaseid) { - PgStat_MsgDropdb msg; + PgStat_MsgDropdb msg; if (pgStatSock < 0) return; @@ -687,7 +685,7 @@ pgstat_drop_database(Oid databaseid) void pgstat_reset_counters(void) { - PgStat_MsgResetcounter msg; + PgStat_MsgResetcounter msg; if (pgStatSock < 0) return; @@ -709,7 +707,7 @@ pgstat_reset_counters(void) void pgstat_ping(void) { - PgStat_MsgDummy msg; + PgStat_MsgDummy msg; if (pgStatSock < 0) return; @@ -731,18 +729,18 @@ pgstat_ping(void) void pgstat_initstats(PgStat_Info *stats, Relation rel) { - PgStat_TableEntry *useent = NULL; - Oid rel_id = rel->rd_id; - int mb; - int i; + PgStat_TableEntry *useent = NULL; + Oid rel_id = rel->rd_id; + int mb; + int i; /* * Initialize data not to count at all. */ - stats->tabentry = NULL; - stats->no_stats = FALSE; - stats->heap_scan_counted = FALSE; - stats->index_scan_counted = FALSE; + stats->tabentry = NULL; + stats->no_stats = FALSE; + stats->heap_scan_counted = FALSE; + stats->index_scan_counted = FALSE; if (!pgstat_collect_startcollector || pgStatSock < 0) { @@ -757,7 +755,7 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) { pgStatTabstatAlloc = 4; pgStatTabstatMessages = (PgStat_MsgTabstat **) - malloc(sizeof(PgStat_MsgTabstat *) * pgStatTabstatAlloc); + malloc(sizeof(PgStat_MsgTabstat *) * pgStatTabstatAlloc); if (pgStatTabstatMessages == NULL) { perror("PGSTATBE: malloc(2)"); @@ -766,7 +764,7 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) for (i = 0; i < pgStatTabstatAlloc; i++) { pgStatTabstatMessages[i] = (PgStat_MsgTabstat *) - malloc(sizeof(PgStat_MsgTabstat)); + malloc(sizeof(PgStat_MsgTabstat)); if (pgStatTabstatMessages[i] == NULL) { perror("PGSTATBE: malloc(2)"); @@ -784,14 +782,14 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) { if (pgStatTabstatMessages[mb]->m_entry[i].t_id == rel_id) { - stats->tabentry = (void *)&(pgStatTabstatMessages[mb]->m_entry[i]); + stats->tabentry = (void *) &(pgStatTabstatMessages[mb]->m_entry[i]); return; } } if (pgStatTabstatMessages[mb]->m_nentries >= PGSTAT_NUM_TABENTRIES) continue; - + /* * Not found, but found a message buffer with an empty slot * instead. Fine, let's use this one. @@ -800,7 +798,7 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) useent = &pgStatTabstatMessages[mb]->m_entry[i]; memset(useent, 0, sizeof(PgStat_TableEntry)); useent->t_id = rel_id; - stats->tabentry = (void *)useent; + stats->tabentry = (void *) useent; return; } @@ -811,7 +809,7 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) { pgStatTabstatAlloc += 4; pgStatTabstatMessages = (PgStat_MsgTabstat **) - realloc(pgStatTabstatMessages, + realloc(pgStatTabstatMessages, sizeof(PgStat_MsgTabstat *) * pgStatTabstatAlloc); if (pgStatTabstatMessages == NULL) { @@ -822,7 +820,7 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) for (i = pgStatTabstatUsed; i < pgStatTabstatAlloc; i++) { pgStatTabstatMessages[i] = (PgStat_MsgTabstat *) - malloc(sizeof(PgStat_MsgTabstat)); + malloc(sizeof(PgStat_MsgTabstat)); if (pgStatTabstatMessages[i] == NULL) { pgStatTabstatAlloc -= 4; @@ -840,7 +838,7 @@ pgstat_initstats(PgStat_Info *stats, Relation rel) useent = &pgStatTabstatMessages[mb]->m_entry[0]; memset(useent, 0, sizeof(PgStat_TableEntry)); useent->t_id = rel_id; - stats->tabentry = (void *)useent; + stats->tabentry = (void *) useent; return; } @@ -855,15 +853,15 @@ void pgstat_count_xact_commit(void) { if (!pgstat_collect_querystring && !pgstat_collect_tuplelevel && - !pgstat_collect_blocklevel) + !pgstat_collect_blocklevel) return; pgStatXactCommit++; /* - * If there was no relation activity yet, just make - * one existing message buffer used without slots, - * causing the next report to tell new xact-counters. + * If there was no relation activity yet, just make one existing + * message buffer used without slots, causing the next report to tell + * new xact-counters. */ if (pgStatTabstatAlloc > 0) { @@ -886,15 +884,15 @@ void pgstat_count_xact_rollback(void) { if (!pgstat_collect_querystring && !pgstat_collect_tuplelevel && - !pgstat_collect_blocklevel) + !pgstat_collect_blocklevel) return; pgStatXactRollback++; /* - * If there was no relation activity yet, just make - * one existing message buffer used without slots, - * causing the next report to tell new xact-counters. + * If there was no relation activity yet, just make one existing + * message buffer used without slots, causing the next report to tell + * new xact-counters. */ if (pgStatTabstatAlloc > 0) { @@ -919,16 +917,16 @@ pgstat_count_xact_rollback(void) PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid) { - PgStat_StatDBEntry *dbentry; + PgStat_StatDBEntry *dbentry; /* * If not done for this transaction, read the statistics collector - * stats file into some hash tables. Be careful with the read_statsfile() - * call below! + * stats file into some hash tables. Be careful with the + * read_statsfile() call below! */ if (!TransactionIdEquals(pgStatDBHashXact, GetCurrentTransactionId())) { - pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, + pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, &pgStatBeTable, &pgStatNumBackends); pgStatDBHashXact = GetCurrentTransactionId(); } @@ -958,17 +956,17 @@ pgstat_fetch_stat_dbentry(Oid dbid) PgStat_StatTabEntry * pgstat_fetch_stat_tabentry(Oid relid) { - PgStat_StatDBEntry *dbentry; - PgStat_StatTabEntry *tabentry; + PgStat_StatDBEntry *dbentry; + PgStat_StatTabEntry *tabentry; /* * If not done for this transaction, read the statistics collector - * stats file into some hash tables. Be careful with the read_statsfile() - * call below! + * stats file into some hash tables. Be careful with the + * read_statsfile() call below! */ if (!TransactionIdEquals(pgStatDBHashXact, GetCurrentTransactionId())) { - pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, + pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, &pgStatBeTable, &pgStatNumBackends); pgStatDBHashXact = GetCurrentTransactionId(); } @@ -1011,7 +1009,7 @@ pgstat_fetch_stat_beentry(int beid) { if (!TransactionIdEquals(pgStatDBHashXact, GetCurrentTransactionId())) { - pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, + pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, &pgStatBeTable, &pgStatNumBackends); pgStatDBHashXact = GetCurrentTransactionId(); } @@ -1035,7 +1033,7 @@ pgstat_fetch_stat_numbackends(void) { if (!TransactionIdEquals(pgStatDBHashXact, GetCurrentTransactionId())) { - pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, + pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId, &pgStatBeTable, &pgStatNumBackends); pgStatDBHashXact = GetCurrentTransactionId(); } @@ -1060,11 +1058,11 @@ pgstat_fetch_stat_numbackends(void) static void pgstat_setheader(PgStat_MsgHdr *hdr, int mtype) { - hdr->m_type = mtype; - hdr->m_backendid = MyBackendId; - hdr->m_procpid = MyProcPid; - hdr->m_databaseid = MyDatabaseId; - hdr->m_userid = GetSessionUserId(); + hdr->m_type = mtype; + hdr->m_backendid = MyBackendId; + hdr->m_procpid = MyProcPid; + hdr->m_databaseid = MyDatabaseId; + hdr->m_userid = GetSessionUserId(); } @@ -1080,7 +1078,7 @@ pgstat_send(void *msg, int len) if (pgStatSock < 0) return; - ((PgStat_MsgHdr *)msg)->m_size = len; + ((PgStat_MsgHdr *) msg)->m_size = len; send(pgStatSock, msg, len, 0); /* We deliberately ignore any error from send() */ @@ -1089,7 +1087,7 @@ pgstat_send(void *msg, int len) /* ------------------------------------------------------------ * Local functions implementing the statistics collector itself follow - *------------------------------------------------------------ + *------------------------------------------------------------ */ @@ -1104,21 +1102,20 @@ static void pgstat_main(void) { PgStat_Msg msg; - fd_set rfds; - int readPipe; - int pmPipe = pgStatPmPipe[0]; - int maxfd; - int nready; - int len = 0; - struct timeval timeout; - struct timeval next_statwrite; - bool need_statwrite; - HASHCTL hash_ctl; - - /* - * Close the writing end of the postmaster pipe, so we'll see - * it closing when the postmaster terminates and can terminate - * as well. + fd_set rfds; + int readPipe; + int pmPipe = pgStatPmPipe[0]; + int maxfd; + int nready; + int len = 0; + struct timeval timeout; + struct timeval next_statwrite; + bool need_statwrite; + HASHCTL hash_ctl; + + /* + * Close the writing end of the postmaster pipe, so we'll see it + * closing when the postmaster terminates and can terminate as well. */ close(pgStatPmPipe[1]); pgStatPmPipe[1] = -1; @@ -1142,15 +1139,16 @@ pgstat_main(void) pqsignal(SIGWINCH, SIG_DFL); /* - * Start a buffering process to read from the socket, so - * we have a little more time to process incoming messages. + * Start a buffering process to read from the socket, so we have a + * little more time to process incoming messages. * * NOTE: the process structure is: postmaster is parent of buffer process - * is parent of collector process. This way, the buffer can detect + * is parent of collector process. This way, the buffer can detect * collector failure via SIGCHLD, whereas otherwise it wouldn't notice - * collector failure until it tried to write on the pipe. That would mean - * that after the postmaster started a new collector, we'd have two buffer - * processes competing to read from the UDP socket --- not good. + * collector failure until it tried to write on the pipe. That would + * mean that after the postmaster started a new collector, we'd have + * two buffer processes competing to read from the UDP socket --- not + * good. */ if (pipe(pgStatPipe) < 0) { @@ -1178,8 +1176,8 @@ pgstat_main(void) } /* - * In the child we can have default SIGCHLD handling (in case we - * want to call system() here...) + * In the child we can have default SIGCHLD handling (in case we want + * to call system() here...) */ pqsignal(SIGCHLD, SIG_DFL); @@ -1196,8 +1194,8 @@ pgstat_main(void) need_statwrite = TRUE; /* - * Read in an existing statistics stats file or initialize the - * stats to zero. + * Read in an existing statistics stats file or initialize the stats + * to zero. */ pgStatRunningInCollector = TRUE; pgstat_read_statsfile(&pgStatDBHash, InvalidOid, NULL, NULL); @@ -1206,14 +1204,14 @@ pgstat_main(void) * Create the dead backend hashtable */ memset(&hash_ctl, 0, sizeof(hash_ctl)); - hash_ctl.keysize = sizeof(int); + hash_ctl.keysize = sizeof(int); hash_ctl.entrysize = sizeof(PgStat_StatBeDead); - hash_ctl.hash = tag_hash; + hash_ctl.hash = tag_hash; pgStatBeDead = hash_create("Dead Backends", PGSTAT_BE_HASH_SIZE, &hash_ctl, HASH_ELEM | HASH_FUNCTION); if (pgStatBeDead == NULL) { - fprintf(stderr, + fprintf(stderr, "PGSTAT: Creation of dead backend hash table failed\n"); exit(1); } @@ -1221,8 +1219,8 @@ pgstat_main(void) /* * Create the known backends table */ - pgStatBeTable = (PgStat_StatBeEntry *)malloc( - sizeof(PgStat_StatBeEntry) * MaxBackends); + pgStatBeTable = (PgStat_StatBeEntry *) malloc( + sizeof(PgStat_StatBeEntry) * MaxBackends); if (pgStatBeTable == NULL) { perror("PGSTAT: Allocation of backend table failed"); @@ -1233,29 +1231,29 @@ pgstat_main(void) readPipe = pgStatPipe[0]; /* - * Process incoming messages and handle all the reporting stuff - * until there are no more messages. + * Process incoming messages and handle all the reporting stuff until + * there are no more messages. */ for (;;) { /* - * If we need to write the status file again (there have - * been changes in the statistics since we wrote it last) - * calculate the timeout until we have to do so. + * If we need to write the status file again (there have been + * changes in the statistics since we wrote it last) calculate the + * timeout until we have to do so. */ if (need_statwrite) { gettimeofday(&timeout, NULL); timeout.tv_usec = next_statwrite.tv_usec - timeout.tv_usec; - timeout.tv_sec = next_statwrite.tv_sec - timeout.tv_sec; + timeout.tv_sec = next_statwrite.tv_sec - timeout.tv_sec; if (timeout.tv_usec < 0) { - timeout.tv_sec -= 1; + timeout.tv_sec -= 1; timeout.tv_usec += 1000000; } if (timeout.tv_sec < 0) { - timeout.tv_sec = 0; + timeout.tv_sec = 0; timeout.tv_usec = 0; } } @@ -1275,7 +1273,7 @@ pgstat_main(void) /* * Now wait for something to do. */ - nready = select(maxfd + 1, &rfds, NULL, NULL, + nready = select(maxfd + 1, &rfds, NULL, NULL, (need_statwrite) ? &timeout : NULL); if (nready < 0) { @@ -1286,8 +1284,8 @@ pgstat_main(void) } /* - * If there are no descriptors ready, our timeout for writing - * the stats file happened. + * If there are no descriptors ready, our timeout for writing the + * stats file happened. */ if (nready == 0) { @@ -1303,14 +1301,14 @@ pgstat_main(void) if (FD_ISSET(readPipe, &rfds)) { /* - * We may need to issue multiple read calls in case the - * buffer process didn't write the message in a single write, - * which is possible since it dumps its buffer bytewise. - * In any case, we'd need two reads since we don't know the - * message length initially. + * We may need to issue multiple read calls in case the buffer + * process didn't write the message in a single write, which + * is possible since it dumps its buffer bytewise. In any + * case, we'd need two reads since we don't know the message + * length initially. */ - int nread = 0; - int targetlen = sizeof(PgStat_MsgHdr); /* initial */ + int nread = 0; + int targetlen = sizeof(PgStat_MsgHdr); /* initial */ while (nread < targetlen) { @@ -1335,15 +1333,16 @@ pgstat_main(void) targetlen > (int) sizeof(msg)) { /* - * Bogus message length implies that we got out - * of sync with the buffer process somehow. - * Abort so that we can restart both processes. + * Bogus message length implies that we got out of + * sync with the buffer process somehow. Abort so + * that we can restart both processes. */ fprintf(stderr, "PGSTAT: bogus message length\n"); exit(1); } } } + /* * EOF on the pipe implies that the buffer process exited. * Fall out of outer loop. @@ -1352,7 +1351,8 @@ pgstat_main(void) break; /* - * Distribute the message to the specific function handling it. + * Distribute the message to the specific function handling + * it. */ switch (msg.msg_hdr.m_type) { @@ -1360,31 +1360,31 @@ pgstat_main(void) break; case PGSTAT_MTYPE_BESTART: - pgstat_recv_bestart((PgStat_MsgBestart *)&msg, nread); + pgstat_recv_bestart((PgStat_MsgBestart *) &msg, nread); break; case PGSTAT_MTYPE_BETERM: - pgstat_recv_beterm((PgStat_MsgBeterm *)&msg, nread); + pgstat_recv_beterm((PgStat_MsgBeterm *) &msg, nread); break; case PGSTAT_MTYPE_TABSTAT: - pgstat_recv_tabstat((PgStat_MsgTabstat *)&msg, nread); + pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, nread); break; case PGSTAT_MTYPE_TABPURGE: - pgstat_recv_tabpurge((PgStat_MsgTabpurge *)&msg, nread); + pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, nread); break; case PGSTAT_MTYPE_ACTIVITY: - pgstat_recv_activity((PgStat_MsgActivity *)&msg, nread); + pgstat_recv_activity((PgStat_MsgActivity *) &msg, nread); break; case PGSTAT_MTYPE_DROPDB: - pgstat_recv_dropdb((PgStat_MsgDropdb *)&msg, nread); + pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, nread); break; case PGSTAT_MTYPE_RESETCOUNTER: - pgstat_recv_resetcounter((PgStat_MsgResetcounter *)&msg, + pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg, nread); break; @@ -1398,15 +1398,14 @@ pgstat_main(void) pgStatNumMessages++; /* - * If this is the first message after we wrote the stats - * file the last time, setup the timeout that it'd be - * written. + * If this is the first message after we wrote the stats file + * the last time, setup the timeout that it'd be written. */ if (!need_statwrite) { gettimeofday(&next_statwrite, NULL); next_statwrite.tv_usec += ((PGSTAT_STAT_INTERVAL) * 1000); - next_statwrite.tv_sec += (next_statwrite.tv_usec / 1000000); + next_statwrite.tv_sec += (next_statwrite.tv_usec / 1000000); next_statwrite.tv_usec %= 1000000; need_statwrite = TRUE; } @@ -1414,21 +1413,22 @@ pgstat_main(void) /* * Note that we do NOT check for postmaster exit inside the loop; - * only EOF on the buffer pipe causes us to fall out. This ensures - * we don't exit prematurely if there are still a few messages in - * the buffer or pipe at postmaster shutdown. + * only EOF on the buffer pipe causes us to fall out. This + * ensures we don't exit prematurely if there are still a few + * messages in the buffer or pipe at postmaster shutdown. */ } /* - * Okay, we saw EOF on the buffer pipe, so there are no more messages to - * process. If the buffer process quit because of postmaster shutdown, - * we want to save the final stats to reuse at next startup. But if the - * buffer process failed, it seems best not to (there may even now be a - * new collector firing up, and we don't want it to read a partially- - * rewritten stats file). We can tell whether the postmaster is still - * alive by checking to see if the postmaster pipe is still open. If it - * is read-ready (ie, EOF), the postmaster must have quit. + * Okay, we saw EOF on the buffer pipe, so there are no more messages + * to process. If the buffer process quit because of postmaster + * shutdown, we want to save the final stats to reuse at next startup. + * But if the buffer process failed, it seems best not to (there may + * even now be a new collector firing up, and we don't want it to read + * a partially- rewritten stats file). We can tell whether the + * postmaster is still alive by checking to see if the postmaster pipe + * is still open. If it is read-ready (ie, EOF), the postmaster must + * have quit. */ if (FD_ISSET(pmPipe, &rfds)) pgstat_write_statsfile(); @@ -1447,23 +1447,23 @@ pgstat_main(void) static void pgstat_recvbuffer(void) { - fd_set rfds; - fd_set wfds; - int writePipe = pgStatPipe[1]; - int pmPipe = pgStatPmPipe[0]; - int maxfd; - int nready; - int len; - int xfr; - int frm; - PgStat_Msg input_buffer; - char *msgbuffer; - 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_in fromaddr; - int fromlen; - bool overflow = false; + fd_set rfds; + fd_set wfds; + int writePipe = pgStatPipe[1]; + int pmPipe = pgStatPmPipe[0]; + int maxfd; + int nready; + int len; + int xfr; + int frm; + PgStat_Msg input_buffer; + char *msgbuffer; + 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_in fromaddr; + int fromlen; + bool overflow = false; /* * Identify myself via ps @@ -1472,11 +1472,11 @@ pgstat_recvbuffer(void) set_ps_display(""); /* - * We want to die if our child collector process does. There are two ways - * we might notice that it has died: receive SIGCHLD, or get a write - * failure on the pipe leading to the child. We can set SIGPIPE to kill - * us here. Our SIGCHLD handler was already set up before we forked (must - * do it that way, else it's a race condition). + * We want to die if our child collector process does. There are two + * ways we might notice that it has died: receive SIGCHLD, or get a + * write failure on the pipe leading to the child. We can set SIGPIPE + * to kill us here. Our SIGCHLD handler was already set up before we + * forked (must do it that way, else it's a race condition). */ pqsignal(SIGPIPE, SIG_DFL); PG_SETMASK(&UnBlockSig); @@ -1511,8 +1511,8 @@ pgstat_recvbuffer(void) maxfd = -1; /* - * As long as we have buffer space we add the socket - * to the read descriptor set. + * As long as we have buffer space we add the socket to the read + * descriptor set. */ if (msg_have <= (int) (PGSTAT_RECVBUFFERSZ - sizeof(PgStat_Msg))) { @@ -1530,9 +1530,9 @@ pgstat_recvbuffer(void) } /* - * If we have messages to write out, we add the pipe - * to the write descriptor set. Otherwise, we check if - * the postmaster might have terminated. + * If we have messages to write out, we add the pipe to the write + * descriptor set. Otherwise, we check if the postmaster might + * have terminated. */ if (msg_have > 0) { @@ -1566,7 +1566,7 @@ pgstat_recvbuffer(void) if (FD_ISSET(pgStatSock, &rfds)) { fromlen = sizeof(fromaddr); - len = recvfrom(pgStatSock, + len = recvfrom(pgStatSock, &input_buffer, sizeof(PgStat_Msg), 0, (struct sockaddr *) &fromaddr, &fromlen); if (len < 0) @@ -1591,14 +1591,14 @@ pgstat_recvbuffer(void) * The source address of the packet must be our own socket. * This ensures that only real hackers or our own backends * tell us something. (This should be redundant with a - * kernel-level check due to having used connect(), but - * let's do it anyway.) + * kernel-level check due to having used connect(), but let's + * do it anyway.) */ if (fromaddr.sin_addr.s_addr != pgStatAddr.sin_addr.s_addr) continue; if (fromaddr.sin_port != pgStatAddr.sin_port) continue; - + /* * O.K. - we accept this message. Copy it to the circular * msgbuffer. @@ -1627,13 +1627,13 @@ pgstat_recvbuffer(void) * pipe. We may or may not be able to write all that we have. * * NOTE: if what we have is less than PIPE_BUF bytes but more than - * the space available in the pipe buffer, most kernels will refuse - * to write any of it, and will return EAGAIN. This means we will - * busy-loop until the situation changes (either because the collector - * caught up, or because more data arrives so that we have more than - * PIPE_BUF bytes buffered). This is not good, but is there any way - * around it? We have no way to tell when the collector has - * caught up... + * the space available in the pipe buffer, most kernels will + * refuse to write any of it, and will return EAGAIN. This means + * we will busy-loop until the situation changes (either because + * the collector caught up, or because more data arrives so that + * we have more than PIPE_BUF bytes buffered). This is not good, + * but is there any way around it? We have no way to tell when + * the collector has caught up... */ if (FD_ISSET(writePipe, &wfds)) { @@ -1664,9 +1664,9 @@ pgstat_recvbuffer(void) continue; /* - * If the pipe from the postmaster is ready for reading, - * the kernel must have closed it on exit() (the postmaster - * never really writes to it). So we've done our job. + * If the pipe from the postmaster is ready for reading, the + * kernel must have closed it on exit() (the postmaster never + * really writes to it). So we've done our job. */ if (FD_ISSET(pmPipe, &rfds)) exit(0); @@ -1689,10 +1689,10 @@ pgstat_die(SIGNAL_ARGS) static int pgstat_add_backend(PgStat_MsgHdr *msg) { - PgStat_StatDBEntry *dbentry; - PgStat_StatBeEntry *beentry; - PgStat_StatBeDead *deadbe; - bool found; + PgStat_StatDBEntry *dbentry; + PgStat_StatBeEntry *beentry; + PgStat_StatBeDead *deadbe; + bool found; /* * Check that the backend ID is valid @@ -1710,19 +1710,19 @@ pgstat_add_backend(PgStat_MsgHdr *msg) if (beentry->databaseid != InvalidOid) { /* - * If the slot contains the PID of this backend, - * everything is fine and we got nothing to do. + * If the slot contains the PID of this backend, everything is + * fine and we got nothing to do. */ if (beentry->procpid == msg->m_procpid) return 0; } /* - * Lookup if this backend is known to be dead. This can be caused - * due to messages arriving in the wrong order - i.e. Postmaster's - * BETERM message might have arrived before we received all the - * backends stats messages, or even a new backend with the same - * backendid was faster in sending his BESTART. + * Lookup if this backend is known to be dead. This can be caused due + * to messages arriving in the wrong order - i.e. Postmaster's BETERM + * message might have arrived before we received all the backends + * stats messages, or even a new backend with the same backendid was + * faster in sending his BESTART. * * If the backend is known to be dead, we ignore this add. */ @@ -1733,8 +1733,8 @@ pgstat_add_backend(PgStat_MsgHdr *msg) return 1; /* - * Backend isn't known to be dead. If it's slot is currently used, - * we have to kick out the old backend. + * Backend isn't known to be dead. If it's slot is currently used, we + * have to kick out the old backend. */ if (beentry->databaseid != InvalidOid) pgstat_sub_backend(beentry->procpid); @@ -1743,17 +1743,17 @@ pgstat_add_backend(PgStat_MsgHdr *msg) * Put this new backend into the slot. */ beentry->databaseid = msg->m_databaseid; - beentry->procpid = msg->m_procpid; - beentry->userid = msg->m_userid; + beentry->procpid = msg->m_procpid; + beentry->userid = msg->m_userid; MemSet(beentry->activity, 0, PGSTAT_ACTIVITY_SIZE); /* * Lookup or create the database entry for this backends DB. */ dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash, - (void *) &(msg->m_databaseid), + (void *) &(msg->m_databaseid), HASH_ENTER, &found); - if (dbentry == NULL) + if (dbentry == NULL) { fprintf(stderr, "PGSTAT: DB hash table out of memory - abort\n"); exit(1); @@ -1764,20 +1764,20 @@ pgstat_add_backend(PgStat_MsgHdr *msg) */ if (!found) { - HASHCTL hash_ctl; + HASHCTL hash_ctl; - dbentry->tables = NULL; - dbentry->n_xact_commit = 0; - dbentry->n_xact_rollback = 0; - dbentry->n_blocks_fetched = 0; - dbentry->n_blocks_hit = 0; - dbentry->n_connects = 0; - dbentry->destroy = 0; + dbentry->tables = NULL; + dbentry->n_xact_commit = 0; + dbentry->n_xact_rollback = 0; + dbentry->n_blocks_fetched = 0; + dbentry->n_blocks_hit = 0; + dbentry->n_connects = 0; + dbentry->destroy = 0; memset(&hash_ctl, 0, sizeof(hash_ctl)); - hash_ctl.keysize = sizeof(Oid); + hash_ctl.keysize = sizeof(Oid); hash_ctl.entrysize = sizeof(PgStat_StatTabEntry); - hash_ctl.hash = tag_hash; + hash_ctl.hash = tag_hash; dbentry->tables = hash_create("Per-database table", PGSTAT_TAB_HASH_SIZE, &hash_ctl, @@ -1785,7 +1785,7 @@ pgstat_add_backend(PgStat_MsgHdr *msg) if (dbentry->tables == NULL) { fprintf(stderr, "PGSTAT: failed to initialize hash table for " - "new database entry\n"); + "new database entry\n"); exit(1); } } @@ -1808,13 +1808,13 @@ pgstat_add_backend(PgStat_MsgHdr *msg) static void pgstat_sub_backend(int procpid) { - int i; - PgStat_StatBeDead *deadbe; - bool found; + int i; + PgStat_StatBeDead *deadbe; + bool found; /* - * Search in the known-backends table for the slot containing - * this PID. + * Search in the known-backends table for the slot containing this + * PID. */ for (i = 0; i < MaxBackends; i++) { @@ -1823,22 +1823,21 @@ pgstat_sub_backend(int procpid) { /* * That's him. Add an entry to the known to be dead backends. - * Due to possible misorder in the arrival of UDP packets - * it's possible that even if we know the backend is dead, - * there could still be messages queued that arrive later. - * Those messages must not cause our number of backends - * statistics to get screwed up, so we remember for a couple - * of seconds that this PID is dead and ignore them (only - * the counting of backends, not the table access stats they - * sent). + * Due to possible misorder in the arrival of UDP packets it's + * possible that even if we know the backend is dead, there + * could still be messages queued that arrive later. Those + * messages must not cause our number of backends statistics + * to get screwed up, so we remember for a couple of seconds + * that this PID is dead and ignore them (only the counting of + * backends, not the table access stats they sent). */ deadbe = (PgStat_StatBeDead *) hash_search(pgStatBeDead, (void *) &procpid, - HASH_ENTER, &found); + HASH_ENTER, &found); if (deadbe == NULL) { fprintf(stderr, "PGSTAT: dead backend hash table out of memory " - "- abort\n"); + "- abort\n"); exit(1); } if (!found) @@ -1856,8 +1855,8 @@ pgstat_sub_backend(int procpid) } /* - * No big problem if not found. This can happen if UDP messages - * arrive out of order here. + * No big problem if not found. This can happen if UDP messages arrive + * out of order here. */ } @@ -1871,17 +1870,16 @@ pgstat_sub_backend(int procpid) static void pgstat_write_statsfile(void) { - HASH_SEQ_STATUS hstat; - HASH_SEQ_STATUS tstat; - PgStat_StatDBEntry *dbentry; - PgStat_StatTabEntry *tabentry; - PgStat_StatBeDead *deadbe; - FILE *fpout; - int i; + HASH_SEQ_STATUS hstat; + HASH_SEQ_STATUS tstat; + PgStat_StatDBEntry *dbentry; + PgStat_StatTabEntry *tabentry; + PgStat_StatBeDead *deadbe; + FILE *fpout; + int i; /* - * Open the statistics temp file to write out - * the current values. + * Open the statistics temp file to write out the current values. */ fpout = fopen(pgStat_tmpfname, PG_BINARY_W); if (fpout == NULL) @@ -1899,8 +1897,8 @@ pgstat_write_statsfile(void) while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL) { /* - * If this database is marked destroyed, count down and do - * so if it reaches 0. + * If this database is marked destroyed, count down and do so if + * it reaches 0. */ if (dbentry->destroy > 0) { @@ -1909,15 +1907,16 @@ pgstat_write_statsfile(void) if (dbentry->tables != NULL) hash_destroy(dbentry->tables); - if (hash_search(pgStatDBHash, + if (hash_search(pgStatDBHash, (void *) &(dbentry->databaseid), HASH_REMOVE, NULL) == NULL) { fprintf(stderr, "PGSTAT: database hash table corrupted " - "during cleanup - abort\n"); + "during cleanup - abort\n"); exit(1); } } + /* * Don't include statistics for it. */ @@ -1937,8 +1936,8 @@ pgstat_write_statsfile(void) while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL) { /* - * If table entry marked for destruction, same as above - * for the database entry. + * If table entry marked for destruction, same as above for + * the database entry. */ if (tabentry->destroy > 0) { @@ -1949,9 +1948,9 @@ pgstat_write_statsfile(void) HASH_REMOVE, NULL) == NULL) { fprintf(stderr, "PGSTAT: tables hash table for " - "database %d corrupted during " - "cleanup - abort\n", - dbentry->databaseid); + "database %d corrupted during " + "cleanup - abort\n", + dbentry->databaseid); exit(1); } } @@ -1959,13 +1958,13 @@ pgstat_write_statsfile(void) } /* - * At least we think this is still a life table. Print - * it's access stats. + * At least we think this is still a life table. Print it's + * access stats. */ fputc('T', fpout); fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout); } - + /* * Mark the end of this DB */ @@ -1989,8 +1988,8 @@ pgstat_write_statsfile(void) } /* - * No more output to be done. Close the temp file and - * replace the old pgstat.stat with it's content. + * No more output to be done. Close the temp file and replace the old + * pgstat.stat with it's content. */ fputc('E', fpout); if (fclose(fpout) < 0) @@ -2006,7 +2005,7 @@ pgstat_write_statsfile(void) if (rename(pgStat_tmpfname, pgStat_fname) < 0) { fprintf(stderr, "PGSTAT: Cannot rename temp stats file\n" - "PGSTAT: "); + "PGSTAT: "); perror(pgStat_fname); fflush(stderr); } @@ -2019,8 +2018,8 @@ pgstat_write_statsfile(void) while ((deadbe = (PgStat_StatBeDead *) hash_seq_search(&hstat)) != NULL) { /* - * Count down the destroy delay and remove entries where - * it reaches 0. + * Count down the destroy delay and remove entries where it + * reaches 0. */ if (--(deadbe->destroy) <= 0) { @@ -2029,7 +2028,7 @@ pgstat_write_statsfile(void) HASH_REMOVE, NULL) == NULL) { fprintf(stderr, "PGSTAT: dead backend hash table corrupted " - "during cleanup - abort\n"); + "during cleanup - abort\n"); exit(1); } } @@ -2046,28 +2045,27 @@ pgstat_write_statsfile(void) * ---------- */ static void -pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, - PgStat_StatBeEntry **betab, int *numbackends) +pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, + PgStat_StatBeEntry **betab, int *numbackends) { - PgStat_StatDBEntry *dbentry; - PgStat_StatDBEntry dbbuf; - PgStat_StatTabEntry *tabentry; - PgStat_StatTabEntry tabbuf; - HASHCTL hash_ctl; - HTAB *tabhash = NULL; - FILE *fpin; - int maxbackends = 0; - int havebackends = 0; - bool found; - MemoryContext use_mcxt; - int mcxt_flags; - - /* - * If running in the collector we use the DynaHashCxt - * memory context. If running in a backend, we use the - * TopTransactionContext instead, so the caller must only know the - * last XactId when this call happened to know if his tables are - * still valid or already gone! + PgStat_StatDBEntry *dbentry; + PgStat_StatDBEntry dbbuf; + PgStat_StatTabEntry *tabentry; + PgStat_StatTabEntry tabbuf; + HASHCTL hash_ctl; + HTAB *tabhash = NULL; + FILE *fpin; + int maxbackends = 0; + int havebackends = 0; + bool found; + MemoryContext use_mcxt; + int mcxt_flags; + + /* + * If running in the collector we use the DynaHashCxt memory context. + * If running in a backend, we use the TopTransactionContext instead, + * so the caller must only know the last XactId when this call + * happened to know if his tables are still valid or already gone! */ if (pgStatRunningInCollector) { @@ -2084,12 +2082,12 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, * Create the DB hashtable */ memset(&hash_ctl, 0, sizeof(hash_ctl)); - hash_ctl.keysize = sizeof(Oid); + hash_ctl.keysize = sizeof(Oid); hash_ctl.entrysize = sizeof(PgStat_StatDBEntry); - hash_ctl.hash = tag_hash; - hash_ctl.hcxt = use_mcxt; - *dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl, - HASH_ELEM | HASH_FUNCTION | mcxt_flags); + hash_ctl.hash = tag_hash; + hash_ctl.hcxt = use_mcxt; + *dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl, + HASH_ELEM | HASH_FUNCTION | mcxt_flags); if (pgStatDBHash == NULL) { if (pgStatRunningInCollector) @@ -2097,12 +2095,12 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, fprintf(stderr, "PGSTAT: Creation of DB hash table failed\n"); exit(1); } - elog(ERROR, "PGSTAT: Creation of DB hash table failed"); + elog(ERROR, "PGSTAT: Creation of DB hash table failed"); } /* - * Initialize the number of known backends to zero, just in case we - * do a silent error return below. + * Initialize the number of known backends to zero, just in case we do + * a silent error return below. */ if (numbackends != NULL) *numbackends = 0; @@ -2111,39 +2109,39 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, /* * Try to open the status file. If it doesn't exist, the backends - * simply return zero for anything and the collector simply - * starts from scratch with empty counters. + * simply return zero for anything and the collector simply starts + * from scratch with empty counters. */ if ((fpin = fopen(pgStat_fname, PG_BINARY_R)) == NULL) return; /* - * We found an existing collector stats file. Read it and put - * all the hashtable entries into place. + * We found an existing collector stats file. Read it and put all the + * hashtable entries into place. */ for (;;) { switch (fgetc(fpin)) { - /* - * 'D' A PgStat_StatDBEntry struct describing a database - * follows. Subsequently, zero to many 'T' entries will - * follow until a 'd' is encountered. - */ + /* + * 'D' A PgStat_StatDBEntry struct describing a database + * follows. Subsequently, zero to many 'T' entries will + * follow until a 'd' is encountered. + */ case 'D': if (fread(&dbbuf, 1, sizeof(dbbuf), fpin) != sizeof(dbbuf)) { if (pgStatRunningInCollector) { - fprintf(stderr, + fprintf(stderr, "PGSTAT: corrupted pgstat.stat file\n"); fclose(fpin); return; } else { - elog(NOTICE, - "PGSTAT: corrupted pgstat.stat file"); + elog(NOTICE, + "PGSTAT: corrupted pgstat.stat file"); fclose(fpin); return; } @@ -2153,8 +2151,8 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, * Add to the DB hash */ dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash, - (void *) &dbbuf.databaseid, - HASH_ENTER, &found); + (void *) &dbbuf.databaseid, + HASH_ENTER, &found); if (dbentry == NULL) { if (pgStatRunningInCollector) @@ -2172,24 +2170,24 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, { if (pgStatRunningInCollector) { - fprintf(stderr, + fprintf(stderr, "PGSTAT: corrupted pgstat.stat file\n"); fclose(fpin); return; } else { - elog(NOTICE, - "PGSTAT: corrupted pgstat.stat file"); + elog(NOTICE, + "PGSTAT: corrupted pgstat.stat file"); fclose(fpin); return; } } memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry)); - dbentry->tables = NULL; - dbentry->destroy = 0; - dbentry->n_backends = 0; + dbentry->tables = NULL; + dbentry->destroy = 0; + dbentry->n_backends = 0; /* * Don't collect tables if not the requested DB @@ -2199,27 +2197,27 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, memset(&hash_ctl, 0, sizeof(hash_ctl)); - hash_ctl.keysize = sizeof(Oid); + hash_ctl.keysize = sizeof(Oid); hash_ctl.entrysize = sizeof(PgStat_StatTabEntry); - hash_ctl.hash = tag_hash; - hash_ctl.hcxt = use_mcxt; + hash_ctl.hash = tag_hash; + hash_ctl.hcxt = use_mcxt; dbentry->tables = hash_create("Per-database table", PGSTAT_TAB_HASH_SIZE, &hash_ctl, - HASH_ELEM | HASH_FUNCTION | mcxt_flags); + HASH_ELEM | HASH_FUNCTION | mcxt_flags); if (dbentry->tables == NULL) { if (pgStatRunningInCollector) { fprintf(stderr, "PGSTAT: failed to initialize " - "hash table for new database entry\n"); + "hash table for new database entry\n"); exit(1); } else { fclose(fpin); elog(ERROR, "PGSTAT: failed to initialize " - "hash table for new database entry\n"); + "hash table for new database entry\n"); } } @@ -2230,30 +2228,30 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, tabhash = dbentry->tables; break; - /* - * 'd' End of this database. - */ + /* + * 'd' End of this database. + */ case 'd': tabhash = NULL; break; - /* - * 'T' A PgStat_StatTabEntry follows. - */ + /* + * 'T' A PgStat_StatTabEntry follows. + */ case 'T': if (fread(&tabbuf, 1, sizeof(tabbuf), fpin) != sizeof(tabbuf)) { if (pgStatRunningInCollector) { - fprintf(stderr, + fprintf(stderr, "PGSTAT: corrupted pgstat.stat file\n"); fclose(fpin); return; } else { - elog(NOTICE, - "PGSTAT: corrupted pgstat.stat file"); + elog(NOTICE, + "PGSTAT: corrupted pgstat.stat file"); fclose(fpin); return; } @@ -2266,8 +2264,8 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, break; tabentry = (PgStat_StatTabEntry *) hash_search(tabhash, - (void *) &tabbuf.tableid, - HASH_ENTER, &found); + (void *) &tabbuf.tableid, + HASH_ENTER, &found); if (tabentry == NULL) { if (pgStatRunningInCollector) @@ -2286,15 +2284,15 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, { if (pgStatRunningInCollector) { - fprintf(stderr, + fprintf(stderr, "PGSTAT: corrupted pgstat.stat file\n"); fclose(fpin); return; } else { - elog(NOTICE, - "PGSTAT: corrupted pgstat.stat file"); + elog(NOTICE, + "PGSTAT: corrupted pgstat.stat file"); fclose(fpin); return; } @@ -2303,9 +2301,9 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, memcpy(tabentry, &tabbuf, sizeof(tabbuf)); break; - /* - * 'M' The maximum number of backends to expect follows. - */ + /* + * 'M' The maximum number of backends to expect follows. + */ case 'M': if (betab == NULL || numbackends == NULL) { @@ -2313,19 +2311,19 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, return; } if (fread(&maxbackends, 1, sizeof(maxbackends), fpin) != - sizeof(maxbackends)) + sizeof(maxbackends)) { if (pgStatRunningInCollector) { - fprintf(stderr, + fprintf(stderr, "PGSTAT: corrupted pgstat.stat file\n"); fclose(fpin); return; } else { - elog(NOTICE, - "PGSTAT: corrupted pgstat.stat file"); + elog(NOTICE, + "PGSTAT: corrupted pgstat.stat file"); fclose(fpin); return; } @@ -2337,21 +2335,21 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, } /* - * Allocate space (in TopTransactionContext too) for - * the backend table. + * Allocate space (in TopTransactionContext too) for the + * backend table. */ if (use_mcxt == NULL) - *betab = (PgStat_StatBeEntry *)malloc( - sizeof(PgStat_StatBeEntry) * maxbackends); + *betab = (PgStat_StatBeEntry *) malloc( + sizeof(PgStat_StatBeEntry) * maxbackends); else - *betab = (PgStat_StatBeEntry *)MemoryContextAlloc( - use_mcxt, - sizeof(PgStat_StatBeEntry) * maxbackends); + *betab = (PgStat_StatBeEntry *) MemoryContextAlloc( + use_mcxt, + sizeof(PgStat_StatBeEntry) * maxbackends); break; - /* - * 'B' A PgStat_StatBeEntry follows. - */ + /* + * 'B' A PgStat_StatBeEntry follows. + */ case 'B': if (betab == NULL || numbackends == NULL) { @@ -2363,24 +2361,25 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, fclose(fpin); return; } + /* * Read it directly into the table. */ - if (fread(&(*betab)[havebackends], 1, - sizeof(PgStat_StatBeEntry), fpin) != - sizeof(PgStat_StatBeEntry)) + if (fread(&(*betab)[havebackends], 1, + sizeof(PgStat_StatBeEntry), fpin) != + sizeof(PgStat_StatBeEntry)) { if (pgStatRunningInCollector) { - fprintf(stderr, + fprintf(stderr, "PGSTAT: corrupted pgstat.stat file\n"); fclose(fpin); return; } else { - elog(NOTICE, - "PGSTAT: corrupted pgstat.stat file"); + elog(NOTICE, + "PGSTAT: corrupted pgstat.stat file"); fclose(fpin); return; } @@ -2389,9 +2388,9 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, /* * Count backends per database here. */ - dbentry = (PgStat_StatDBEntry *)hash_search(*dbhash, - (void *) &((*betab)[havebackends].databaseid), - HASH_FIND, NULL); + dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash, + (void *) &((*betab)[havebackends].databaseid), + HASH_FIND, NULL); if (dbentry) dbentry->n_backends++; @@ -2405,9 +2404,9 @@ pgstat_read_statsfile(HTAB **dbhash, Oid onlydb, } break; - /* - * 'E' The EOF marker of a complete stats file. - */ + /* + * 'E' The EOF marker of a complete stats file. + */ case 'E': fclose(fpin); return; @@ -2468,13 +2467,13 @@ static void pgstat_recv_activity(PgStat_MsgActivity *msg, int len) { /* - * Here we check explicitly for 0 return, since we don't - * want to mangle the activity of an active backend by - * a delayed packed from a dead one. + * Here we check explicitly for 0 return, since we don't want to + * mangle the activity of an active backend by a delayed packed from a + * dead one. */ if (pgstat_add_backend(&msg->m_hdr) != 0) return; - + strncpy(pgStatBeTable[msg->m_hdr.m_backendid - 1].activity, msg->m_what, PGSTAT_ACTIVITY_SIZE); } @@ -2489,11 +2488,11 @@ pgstat_recv_activity(PgStat_MsgActivity *msg, int len) static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len) { - PgStat_TableEntry *tabmsg = &(msg->m_entry[0]); - PgStat_StatDBEntry *dbentry; - PgStat_StatTabEntry *tabentry; - int i; - bool found; + PgStat_TableEntry *tabmsg = &(msg->m_entry[0]); + PgStat_StatDBEntry *dbentry; + PgStat_StatTabEntry *tabentry; + int i; + bool found; /* * Make sure the backend is counted for. @@ -2505,20 +2504,20 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len) * Lookup the database in the hashtable. */ dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash, - (void *) &(msg->m_hdr.m_databaseid), - HASH_FIND, NULL); + (void *) &(msg->m_hdr.m_databaseid), + HASH_FIND, NULL); if (!dbentry) return; /* - * If the database is marked for destroy, this is a delayed - * UDP packet and not worth being counted. + * If the database is marked for destroy, this is a delayed UDP packet + * and not worth being counted. */ if (dbentry->destroy > 0) return; - dbentry->n_xact_commit += (PgStat_Counter)(msg->m_xact_commit); - dbentry->n_xact_rollback += (PgStat_Counter)(msg->m_xact_rollback); + dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit); + dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback); /* * Process all table entries in the message. @@ -2526,29 +2525,29 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len) for (i = 0; i < msg->m_nentries; i++) { tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables, - (void *) &(tabmsg[i].t_id), - HASH_ENTER, &found); + (void *) &(tabmsg[i].t_id), + HASH_ENTER, &found); if (tabentry == NULL) { fprintf(stderr, "PGSTAT: tables hash table out of memory for " - "database %d - abort\n", dbentry->databaseid); + "database %d - abort\n", dbentry->databaseid); exit(1); } if (!found) { /* - * If it's a new table entry, initialize counters - * to the values we just got. + * If it's a new table entry, initialize counters to the + * values we just got. */ - tabentry->numscans = tabmsg[i].t_numscans; - tabentry->tuples_returned = tabmsg[i].t_tuples_returned; - tabentry->tuples_fetched = tabmsg[i].t_tuples_fetched; - tabentry->tuples_inserted = tabmsg[i].t_tuples_inserted; - tabentry->tuples_updated = tabmsg[i].t_tuples_updated; - tabentry->tuples_deleted = tabmsg[i].t_tuples_deleted; - tabentry->blocks_fetched = tabmsg[i].t_blocks_fetched; - tabentry->blocks_hit = tabmsg[i].t_blocks_hit; + tabentry->numscans = tabmsg[i].t_numscans; + tabentry->tuples_returned = tabmsg[i].t_tuples_returned; + tabentry->tuples_fetched = tabmsg[i].t_tuples_fetched; + tabentry->tuples_inserted = tabmsg[i].t_tuples_inserted; + tabentry->tuples_updated = tabmsg[i].t_tuples_updated; + tabentry->tuples_deleted = tabmsg[i].t_tuples_deleted; + tabentry->blocks_fetched = tabmsg[i].t_blocks_fetched; + tabentry->blocks_hit = tabmsg[i].t_blocks_hit; tabentry->destroy = 0; } @@ -2557,21 +2556,21 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len) /* * Otherwise add the values to the existing entry. */ - tabentry->numscans += tabmsg[i].t_numscans; - tabentry->tuples_returned += tabmsg[i].t_tuples_returned; - tabentry->tuples_fetched += tabmsg[i].t_tuples_fetched; - tabentry->tuples_inserted += tabmsg[i].t_tuples_inserted; - tabentry->tuples_updated += tabmsg[i].t_tuples_updated; - tabentry->tuples_deleted += tabmsg[i].t_tuples_deleted; - tabentry->blocks_fetched += tabmsg[i].t_blocks_fetched; - tabentry->blocks_hit += tabmsg[i].t_blocks_hit; + tabentry->numscans += tabmsg[i].t_numscans; + tabentry->tuples_returned += tabmsg[i].t_tuples_returned; + tabentry->tuples_fetched += tabmsg[i].t_tuples_fetched; + tabentry->tuples_inserted += tabmsg[i].t_tuples_inserted; + tabentry->tuples_updated += tabmsg[i].t_tuples_updated; + tabentry->tuples_deleted += tabmsg[i].t_tuples_deleted; + tabentry->blocks_fetched += tabmsg[i].t_blocks_fetched; + tabentry->blocks_hit += tabmsg[i].t_blocks_hit; } /* * And add the block IO to the database entry. */ - dbentry->n_blocks_fetched += tabmsg[i].t_blocks_fetched; - dbentry->n_blocks_hit += tabmsg[i].t_blocks_hit; + dbentry->n_blocks_fetched += tabmsg[i].t_blocks_fetched; + dbentry->n_blocks_hit += tabmsg[i].t_blocks_hit; } } @@ -2585,9 +2584,9 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len) static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len) { - PgStat_StatDBEntry *dbentry; - PgStat_StatTabEntry *tabentry; - int i; + PgStat_StatDBEntry *dbentry; + PgStat_StatTabEntry *tabentry; + int i; /* * Make sure the backend is counted for. @@ -2599,14 +2598,14 @@ pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len) * Lookup the database in the hashtable. */ dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash, - (void *) &(msg->m_hdr.m_databaseid), - HASH_FIND, NULL); + (void *) &(msg->m_hdr.m_databaseid), + HASH_FIND, NULL); if (!dbentry) return; /* - * If the database is marked for destroy, this is a delayed - * UDP packet and the tables will go away at DB destruction. + * If the database is marked for destroy, this is a delayed UDP packet + * and the tables will go away at DB destruction. */ if (dbentry->destroy > 0) return; @@ -2617,8 +2616,8 @@ pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len) for (i = 0; i < msg->m_nentries; i++) { tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables, - (void *) &(msg->m_tableid[i]), - HASH_FIND, NULL); + (void *) &(msg->m_tableid[i]), + HASH_FIND, NULL); if (tabentry) tabentry->destroy = PGSTAT_DESTROY_COUNT; } @@ -2634,7 +2633,7 @@ pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len) static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len) { - PgStat_StatDBEntry *dbentry; + PgStat_StatDBEntry *dbentry; /* * Make sure the backend is counted for. @@ -2646,8 +2645,8 @@ pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len) * Lookup the database in the hashtable. */ dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash, - (void *) &(msg->m_databaseid), - HASH_FIND, NULL); + (void *) &(msg->m_databaseid), + HASH_FIND, NULL); if (!dbentry) return; @@ -2667,8 +2666,8 @@ pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len) static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len) { - HASHCTL hash_ctl; - PgStat_StatDBEntry *dbentry; + HASHCTL hash_ctl; + PgStat_StatDBEntry *dbentry; /* * Make sure the backend is counted for. @@ -2680,8 +2679,8 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len) * Lookup the database in the hashtable. */ dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash, - (void *) &(msg->m_hdr.m_databaseid), - HASH_FIND, NULL); + (void *) &(msg->m_hdr.m_databaseid), + HASH_FIND, NULL); if (!dbentry) return; @@ -2692,18 +2691,18 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len) if (dbentry->tables != NULL) hash_destroy(dbentry->tables); - dbentry->tables = NULL; - dbentry->n_xact_commit = 0; - dbentry->n_xact_rollback = 0; - dbentry->n_blocks_fetched = 0; - dbentry->n_blocks_hit = 0; - dbentry->n_connects = 0; - dbentry->destroy = 0; + dbentry->tables = NULL; + dbentry->n_xact_commit = 0; + dbentry->n_xact_rollback = 0; + dbentry->n_blocks_fetched = 0; + dbentry->n_blocks_hit = 0; + dbentry->n_connects = 0; + dbentry->destroy = 0; memset(&hash_ctl, 0, sizeof(hash_ctl)); - hash_ctl.keysize = sizeof(Oid); + hash_ctl.keysize = sizeof(Oid); hash_ctl.entrysize = sizeof(PgStat_StatTabEntry); - hash_ctl.hash = tag_hash; + hash_ctl.hash = tag_hash; dbentry->tables = hash_create("Per-database table", PGSTAT_TAB_HASH_SIZE, &hash_ctl, @@ -2711,9 +2710,7 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len) if (dbentry->tables == NULL) { fprintf(stderr, "PGSTAT: failed to reinitialize hash table for " - "database entry\n"); + "database entry\n"); exit(1); } } - - diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 08a6ce22c1..1659f09752 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.251 2001/10/22 19:41:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/postmaster/postmaster.c,v 1.252 2001/10/25 05:49:40 momjian Exp $ * * NOTES * @@ -116,6 +116,7 @@ sigset_t UnBlockSig, BlockSig, AuthBlockSig; + #else int UnBlockSig, BlockSig, @@ -223,6 +224,7 @@ static unsigned int random_seed = 0; extern char *optarg; extern int optind, opterr; + #ifdef HAVE_INT_OPTRESET extern int optreset; #endif @@ -245,9 +247,12 @@ static void usage(const char *); static int ServerLoop(void); static int BackendStartup(Port *port); static int ProcessStartupPacket(Port *port, bool SSLdone); -static void processCancelRequest(Port *port, void *pkt); +static void processCancelRequest(Port *port, void *pkt); static int initMasks(fd_set *rmask, fd_set *wmask); -enum CAC_state { CAC_OK, CAC_STARTUP, CAC_SHUTDOWN, CAC_RECOVERY, CAC_TOOMANY }; +enum CAC_state +{ + CAC_OK, CAC_STARTUP, CAC_SHUTDOWN, CAC_RECOVERY, CAC_TOOMANY +}; static enum CAC_state canAcceptConnections(void); static long PostmasterRandom(void); static void RandomSalt(char *cryptSalt, char *md5Salt); @@ -255,7 +260,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))); @@ -278,14 +284,14 @@ checkDataDir(const char *checkdir) if (checkdir == NULL) { fprintf(stderr, gettext( - "%s does not know where to find the database system data.\n" - "You must specify the directory that contains the database system\n" - "either by specifying the -D invocation option or by setting the\n" - "PGDATA environment variable.\n\n"), + "%s does not know where to find the database system data.\n" + "You must specify the directory that contains the database system\n" + "either by specifying the -D invocation option or by setting the\n" + "PGDATA environment variable.\n\n"), progname); ExitPostmaster(2); } - + /* * Check if the directory has group or world access. If so, reject. */ @@ -311,9 +317,9 @@ checkDataDir(const char *checkdir) if (fp == NULL) { fprintf(stderr, gettext( - "%s does not find the database system.\n" - "Expected to find it in the PGDATA directory \"%s\",\n" - "but unable to open file \"%s\": %s\n\n"), + "%s does not find the database system.\n" + "Expected to find it in the PGDATA directory \"%s\",\n" + "but unable to open file \"%s\": %s\n\n"), progname, checkdir, path, strerror(errno)); ExitPostmaster(2); } @@ -464,6 +470,7 @@ PostmasterMain(int argc, char *argv[]) /* already done above */ break; case 'd': + /* * Turn on debugging for the postmaster and the backend * servers descended from it. @@ -583,9 +590,8 @@ PostmasterMain(int argc, char *argv[]) } /* - * Now that we are done processing the postmaster arguments, - * reset getopt(3) library so that it will work correctly in - * subprocesses. + * Now that we are done processing the postmaster arguments, reset + * getopt(3) library so that it will work correctly in subprocesses. */ optind = 1; #ifdef HAVE_INT_OPTRESET @@ -649,8 +655,9 @@ PostmasterMain(int argc, char *argv[]) ExitPostmaster(1); /* - * Remove old temporary files. At this point there can be no other - * Postgres processes running in this directory, so this should be safe. + * Remove old temporary files. At this point there can be no other + * Postgres processes running in this directory, so this should be + * safe. */ RemovePgTempFiles(); @@ -725,9 +732,9 @@ PostmasterMain(int argc, char *argv[]) /* * Reset whereToSendOutput from Debug (its starting state) to None. * This prevents elog from sending 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. + * 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. */ whereToSendOutput = None; @@ -938,8 +945,8 @@ ServerLoop(void) } /* - * New connection pending on our well-known port's socket? - * If so, fork a child process to deal with it. + * New connection pending on our well-known port's socket? If so, + * fork a child process to deal with it. */ #ifdef HAVE_UNIX_SOCKETS @@ -950,9 +957,10 @@ ServerLoop(void) if (port) { 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); @@ -967,9 +975,10 @@ ServerLoop(void) if (port) { 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); @@ -1083,7 +1092,7 @@ ProcessStartupPacket(Port *port, bool SSLdone) { elog(DEBUG, "failed to send SSL negotiation response: %s", strerror(errno)); - return STATUS_ERROR; /* close the connection */ + return STATUS_ERROR; /* close the connection */ } #ifdef USE_SSL @@ -1131,8 +1140,7 @@ ProcessStartupPacket(Port *port, bool SSLdone) /* * Truncate given database and user names to length of a Postgres - * name. This avoids lookup failures when overlength names are - * given. + * name. This avoids lookup failures when overlength names are given. */ if ((int) sizeof(port->database) >= NAMEDATALEN) port->database[NAMEDATALEN - 1] = '\0'; @@ -1241,14 +1249,15 @@ canAcceptConnections(void) return CAC_STARTUP; if (FatalError) return CAC_RECOVERY; + /* * Don't start too many children. * - * We allow more connections than we can have backends here because - * some might still be authenticating; they might fail auth, or some - * existing backend might exit before the auth cycle is completed. - * The exact MaxBackends limit is enforced when a new backend tries - * to join the shared-inval backend array. + * We allow more connections than we can have backends here because some + * might still be authenticating; they might fail auth, or some + * existing backend might exit before the auth cycle is completed. The + * exact MaxBackends limit is enforced when a new backend tries to + * join the shared-inval backend array. */ if (CountChildren() >= 2 * MaxBackends) return CAC_TOOMANY; @@ -1340,7 +1349,6 @@ ClosePostmasterPorts(bool pgstat_too) static void reset_shared(unsigned short port) { - /* * Reset assignment of shared mem and semaphore IPC keys. Doing this * means that in normal cases we'll assign the same keys on each @@ -1529,8 +1537,10 @@ static void reaper(SIGNAL_ARGS) { int save_errno = errno; + #ifdef HAVE_WAITPID int status; /* backend exit status */ + #else union wait status; /* backend exit status */ #endif @@ -1552,9 +1562,10 @@ reaper(SIGNAL_ARGS) { exitstatus = status.w_status; #endif + /* - * Check if this child was the statistics collector. If - * so, start a new one. + * Check if this child was the statistics collector. If so, start + * a new one. */ if (pgstat_ispgstat(pid)) { @@ -1843,8 +1854,8 @@ BackendStartup(Port *port) MyCancelKey = PostmasterRandom(); /* - * Make room for backend data structure. Better before the fork() - * so we can handle failure cleanly. + * Make room for backend data structure. Better before the fork() so + * we can handle failure cleanly. */ bn = (Backend *) malloc(sizeof(Backend)); if (!bn) @@ -1873,7 +1884,7 @@ BackendStartup(Port *port) if (pid == 0) /* child */ { - int status; + int status; free(bn); #ifdef __BEOS__ @@ -2001,10 +2012,11 @@ DoBackend(Port *port) /* * Initialize libpq and enable reporting of elog errors to the client. - * Must do this now because authentication uses libpq to send messages. + * Must do this now because authentication uses libpq to send + * messages. */ pq_init(); /* initialize libpq to talk to client */ - whereToSendOutput = Remote; /* now safe to elog to client */ + whereToSendOutput = Remote; /* now safe to elog to client */ /* * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT @@ -2016,9 +2028,9 @@ DoBackend(Port *port) * * PreAuthDelay is a debugging aid for investigating problems in the * authentication cycle: it can be set in postgresql.conf to allow - * time to attach to the newly-forked backend with a debugger. - * (See also the -W backend switch, which we allow clients to pass - * through PGOPTIONS, but it is not honored until after authentication.) + * time to attach to the newly-forked backend with a debugger. (See + * also the -W backend switch, which we allow clients to pass through + * PGOPTIONS, but it is not honored until after authentication.) */ pqsignal(SIGTERM, authdie); pqsignal(SIGQUIT, authdie); @@ -2028,7 +2040,7 @@ DoBackend(Port *port) if (PreAuthDelay > 0) sleep(PreAuthDelay); - if (! enable_sigalrm_interrupt(AuthenticationTimeout * 1000)) + if (!enable_sigalrm_interrupt(AuthenticationTimeout * 1000)) elog(FATAL, "DoBackend: Unable to set timer for auth timeout"); /* @@ -2042,7 +2054,8 @@ DoBackend(Port *port) /* * Now that we have the user and database name, we can set the process - * title for ps. It's good to do this as early as possible in startup. + * title for ps. It's good to do this as early as possible in + * startup. * * But first, we need the remote host name. */ @@ -2101,10 +2114,10 @@ DoBackend(Port *port) ClientAuthentication(port); /* might not return, if failure */ /* - * Done with authentication. Disable timeout, and prevent SIGTERM/SIGQUIT - * again until backend startup is complete. + * Done with authentication. Disable timeout, and prevent + * SIGTERM/SIGQUIT again until backend startup is complete. */ - if (! disable_sigalrm_interrupt()) + if (!disable_sigalrm_interrupt()) elog(FATAL, "DoBackend: Unable to disable timer for auth timeout"); PG_SETMASK(&BlockSig); @@ -2294,14 +2307,15 @@ RandomSalt(char *cryptSalt, char *md5Salt) cryptSalt[0] = CharRemap(rand % 62); cryptSalt[1] = CharRemap(rand / 62); + /* - * It's okay to reuse the first random value for one of the MD5 salt bytes, - * since only one of the two salts will be sent to the client. After that - * we need to compute more random bits. + * It's okay to reuse the first random value for one of the MD5 salt + * bytes, since only one of the two salts will be sent to the client. + * After that we need to compute more random bits. * * We use % 255, sacrificing one possible byte value, so as to ensure - * that all bits of the random() value participate in the result. While - * at it, add one to avoid generating any null bytes. + * that all bits of the random() value participate in the result. + * While at it, add one to avoid generating any null bytes. */ md5Salt[0] = (rand % 255) + 1; rand = PostmasterRandom(); @@ -2391,7 +2405,6 @@ InitSSL(void) ExitPostmaster(1); } } - #endif /* @@ -2428,7 +2441,8 @@ SSDataBase(int xlop) beos_backend_startup(); #endif - IsUnderPostmaster = true; /* we are a postmaster subprocess now */ + IsUnderPostmaster = true; /* we are a postmaster subprocess + * now */ /* Lose the postmaster's on-exit routines and port connections */ on_exit_reset(); @@ -2487,7 +2501,7 @@ SSDataBase(int xlop) beos_backend_startup_failed(); #endif - switch(xlop) + switch (xlop) { case BS_XLOG_STARTUP: elog(DEBUG, "could not launch startup process (fork failure): %s", @@ -2585,9 +2599,9 @@ CreateOptsFile(int argc, char *argv[]) static void -postmaster_error(const char *fmt, ...) +postmaster_error(const char *fmt,...) { - va_list ap; + va_list ap; fprintf(stderr, "%s: ", progname); va_start(ap, fmt); diff --git a/src/backend/regex/engine.c b/src/backend/regex/engine.c index 2d7f4ee92d..79b71415ed 100644 --- a/src/backend/regex/engine.c +++ b/src/backend/regex/engine.c @@ -87,15 +87,15 @@ struct match states empty; /* empty set of states */ }; -static int matcher(struct re_guts * g, pg_wchar * string, size_t nmatch, +static int matcher(struct re_guts * g, pg_wchar *string, size_t nmatch, regmatch_t *pmatch, int eflags); -static pg_wchar *dissect(struct match * m, pg_wchar * start, pg_wchar * stop, +static pg_wchar *dissect(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst); -static pg_wchar *backref(struct match * m, pg_wchar * start, pg_wchar * stop, +static pg_wchar *backref(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst, sopno lev); -static pg_wchar *fast(struct match * m, pg_wchar * start, pg_wchar * stop, +static pg_wchar *fast(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst); -static pg_wchar *slow(struct match * m, pg_wchar * start, pg_wchar * stop, +static pg_wchar *slow(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst); static states step(struct re_guts * g, sopno start, sopno stop, states bef, int ch, states aft); @@ -117,13 +117,12 @@ static states step(struct re_guts * g, sopno start, #endif #ifdef REDEBUG -static void print(struct match * m, pg_wchar * caption, states st, int ch, +static void print(struct match * m, pg_wchar *caption, states st, int ch, FILE *d); -static void at(struct match * m, pg_wchar * title, pg_wchar * start, - pg_wchar * stop, sopno startst, sopno stopst); +static void at(struct match * m, pg_wchar *title, pg_wchar *start, + pg_wchar *stop, sopno startst, sopno stopst); static pg_wchar *pchar(int ch); static int pg_isprint(int c); - #endif #ifdef REDEBUG @@ -145,7 +144,7 @@ do { \ * matcher - the actual matching engine */ static int /* 0 success, REG_NOMATCH failure */ -matcher(struct re_guts * g, pg_wchar * string, size_t nmatch, +matcher(struct re_guts * g, pg_wchar *string, size_t nmatch, regmatch_t *pmatch, int eflags) { pg_wchar *endp; @@ -331,7 +330,7 @@ matcher(struct re_guts * g, pg_wchar * string, size_t nmatch, * dissect - figure out what matched what, no back references */ static pg_wchar * /* == stop (success) always */ -dissect(struct match * m, pg_wchar * start, pg_wchar * stop, +dissect(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst) { int i; @@ -527,7 +526,7 @@ dissect(struct match * m, pg_wchar * start, pg_wchar * stop, * lev is PLUS nesting level */ static pg_wchar * /* == stop (success) or NULL (failure) */ -backref(struct match * m, pg_wchar * start, pg_wchar * stop, +backref(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst, sopno lev) { int i; @@ -686,7 +685,7 @@ backref(struct match * m, pg_wchar * start, pg_wchar * stop, return dp; /* that one missed, try next one */ if (OP(m->g->strip[esub]) == O_CH) - return NULL;/* there is none */ + return NULL; /* there is none */ esub++; assert(OP(m->g->strip[esub]) == OOR2); ssub = esub + 1; @@ -734,7 +733,7 @@ backref(struct match * m, pg_wchar * start, pg_wchar * stop, * fast - step through the string at top speed */ static pg_wchar * /* where tentative match ended, or NULL */ -fast(struct match * m, pg_wchar * start, pg_wchar * stop, +fast(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst) { states st = m->st; @@ -823,7 +822,7 @@ fast(struct match * m, pg_wchar * start, pg_wchar * stop, * slow - step through the string more deliberately */ static pg_wchar * /* where it ended */ -slow(struct match * m, pg_wchar * start, pg_wchar * stop, +slow(struct match * m, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst) { states st = m->st; @@ -1029,7 +1028,7 @@ step(struct re_guts * g, * print - print a set of states */ static void -print(struct match * m, pg_wchar * caption, states st, +print(struct match * m, pg_wchar *caption, states st, int ch, FILE *d) { struct re_guts *g = m->g; @@ -1055,7 +1054,7 @@ print(struct match * m, pg_wchar * caption, states st, * at - print current situation */ static void -at(struct match * m, pg_wchar * title, pg_wchar * start, pg_wchar * stop, +at(struct match * m, pg_wchar *title, pg_wchar *start, pg_wchar *stop, sopno startst, sopno stopst) { if (!(m->eflags & REG_TRACE)) @@ -1097,7 +1096,6 @@ pg_isprint(int c) return (isprint((unsigned char) c)); #endif } - #endif #endif diff --git a/src/backend/regex/regcomp.c b/src/backend/regex/regcomp.c index 837a12c27c..3b433b20f4 100644 --- a/src/backend/regex/regcomp.c +++ b/src/backend/regex/regcomp.c @@ -88,7 +88,6 @@ static unsigned char othercase(int ch); #else static char othercase(int ch); - #endif static void bothcases(struct parse * p, int ch); static void ordinary(struct parse * p, int ch); @@ -173,7 +172,6 @@ pg95_regcomp(regex_t *preg, const char *pattern, int cflags) #ifdef MULTIBYTE pg_wchar *wcp; - #endif #ifdef REDEBUG @@ -724,7 +722,6 @@ p_bracket(struct parse * p) #ifdef MULTIBYTE pg_wchar sp1[] = {'[', ':', '<', ':', ']', ']'}; pg_wchar sp2[] = {'[', ':', '>', ':', ']', ']'}; - #endif /* Dept of Truly Sickening Special-Case Kludges */ @@ -930,7 +927,7 @@ p_b_eclass(struct parse * p, cset *cs) /* * p_b_symbol - parse a character or [..]ed multicharacter collating symbol */ -static pg_wchar /* value of symbol */ +static pg_wchar /* value of symbol */ p_b_symbol(struct parse * p) { pg_wchar value; @@ -1020,7 +1017,7 @@ bothcases(struct parse * p, int ch) pg_wchar *oldend = p->end; pg_wchar bracket[3]; - assert(othercase(ch) != ch);/* p_bracket() would recurse */ + assert(othercase(ch) != ch); /* p_bracket() would recurse */ p->next = bracket; p->end = bracket + 2; bracket[0] = ch; @@ -1110,7 +1107,7 @@ repeat(struct parse * p, case REP(0, N): /* as x{1,n}? */ case REP(0, INF): /* as x{1,}? */ /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */ - INSERT(OCH_, start);/* offset is wrong... */ + INSERT(OCH_, start); /* offset is wrong... */ repeat(p, start + 1, 1, to); ASTERN(OOR1, start); AHEAD(start); /* ... fix it */ diff --git a/src/backend/regex/regexec.c b/src/backend/regex/regexec.c index b1733a9d40..4767730441 100644 --- a/src/backend/regex/regexec.c +++ b/src/backend/regex/regexec.c @@ -126,7 +126,7 @@ do { \ do { \ free((m)->space); \ } while (0) - + #define SETUP(v) ((v) = &m->space[m->vn++ * m->g->nstates]) #define onestate int #define INIT(o, n) ((o) = (n)) @@ -157,7 +157,6 @@ pg95_regexec(const regex_t *preg, const char *string, size_t nmatch, #ifdef MULTIBYTE pg_wchar *str; int sts; - #endif #ifdef REDEBUG diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index 3b3d209d46..f3e2306a00 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.97 2001/07/09 23:50:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.98 2001/10/25 05:49:41 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -33,10 +33,10 @@ static Query *rewriteRuleAction(Query *parsetree, - Query *rule_action, - Node *rule_qual, - int rt_index, - CmdType event); + Query *rule_action, + Node *rule_qual, + int rt_index, + CmdType event); static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index); static void markQueryForUpdate(Query *qry, bool skipOldNew); static List *matchLocks(CmdType event, RuleLock *rulelocks, @@ -92,16 +92,16 @@ rewriteRuleAction(Query *parsetree, PRS2_OLD_VARNO + rt_length, rt_index, 0); /* - * 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 clean those out 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. + * 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 clean those out 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. + * that rule action's rtable is separate and shares no substructure + * with the main rtable. Hence do a deep copy here. */ sub_action->rtable = nconc((List *) copyObject(parsetree->rtable), sub_action->rtable); @@ -118,8 +118,8 @@ rewriteRuleAction(Query *parsetree, * joined twice, however, so avoid keeping it if the rule action * mentions it. * - * As above, the action's jointree must not share substructure with - * the main parsetree's. + * As above, the action's jointree must not share substructure with the + * main parsetree's. */ if (sub_action->jointree != NULL) { @@ -129,7 +129,7 @@ rewriteRuleAction(Query *parsetree, keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree, rt_index, 0)) && (rangeTableEntry_used(rule_qual, rt_index, 0) || - rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0)); + rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0)); newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index); sub_action->jointree->fromlist = nconc(newjointree, sub_action->jointree->fromlist); @@ -139,8 +139,8 @@ rewriteRuleAction(Query *parsetree, * We copy the qualifications of the parsetree to the action and vice * versa. So force hasSubLinks if one of them has it. If this is not * right, the flag will get cleared later, but we mustn't risk having - * it not set when it needs to be. (XXX this should probably be handled - * by AddQual and friends, not here...) + * it not set when it needs to be. (XXX this should probably be + * handled by AddQual and friends, not here...) */ if (parsetree->hasSubLinks) sub_action->hasSubLinks = TRUE; @@ -313,7 +313,6 @@ ApplyRetrieveRule(Query *parsetree, */ if (intMember(rt_index, parsetree->rowMarks)) { - /* * Remove the view from the list of rels that will actually be * marked FOR UPDATE by the executor. It will still be access- @@ -482,10 +481,10 @@ fireRIRrules(Query *parsetree) rel = heap_openr(rte->relname, lockmode); /* - * Check to see if relation's OID matches the RTE. If not, the RTE - * actually refers to an older relation that had the same name. - * Eventually we might want to reparse the referencing rule, but - * for now all we can do is punt. + * Check to see if relation's OID matches the RTE. If not, the + * RTE actually refers to an older relation that had the same + * name. Eventually we might want to reparse the referencing rule, + * but for now all we can do is punt. */ if (RelationGetRelid(rel) != rte->relid) elog(ERROR, "Relation \"%s\" with OID %u no longer exists", @@ -771,8 +770,8 @@ RewriteQuery(Query *parsetree, bool *instead_flag, List **qual_products) /* * Check to see if relation's OID matches the RTE. If not, the RTE * actually refers to an older relation that had the same name. - * Eventually we might want to reparse the referencing rule, but - * for now all we can do is punt. + * Eventually we might want to reparse the referencing rule, but for + * now all we can do is punt. */ if (RelationGetRelid(rt_entry_relation) != rt_entry->relid) elog(ERROR, "Relation \"%s\" with OID %u no longer exists", @@ -845,12 +844,13 @@ deepRewriteQuery(Query *parsetree) } /* - * For INSERTs, the original query is done first; for UPDATE/DELETE, it is - * done last. This is needed because update and delete rule actions might - * not do anything if they are invoked after the update or delete is - * performed. The command counter increment between the query execution - * makes the deleted (and maybe the updated) tuples disappear so the scans - * for them in the rule actions cannot find them. + * For INSERTs, the original query is done first; for UPDATE/DELETE, + * it is done last. This is needed because update and delete rule + * actions might not do anything if they are invoked after the update + * or delete is performed. The command counter increment between the + * query execution makes the deleted (and maybe the updated) tuples + * disappear so the scans for them in the rule actions cannot find + * them. */ if (parsetree->commandType == CMD_INSERT) { @@ -860,6 +860,7 @@ deepRewriteQuery(Query *parsetree) */ if (qual_products != NIL) rewritten = nconc(qual_products, rewritten); + /* * Add the unmodified original query, if no INSTEAD rule was seen. */ @@ -874,6 +875,7 @@ deepRewriteQuery(Query *parsetree) */ if (qual_products != NIL) rewritten = nconc(rewritten, qual_products); + /* * Add the unmodified original query, if no INSTEAD rule was seen. */ diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 238897d58e..63e0ced180 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.58 2001/09/07 20:52:31 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteManip.c,v 1.59 2001/10/25 05:49:41 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -43,7 +43,6 @@ static bool checkExprHasSubLink_walker(Node *node, void *context); bool checkExprHasAggs(Node *node) { - /* * If a Query is passed, examine it --- but we will not recurse into * sub-Queries. @@ -74,7 +73,6 @@ checkExprHasAggs_walker(Node *node, void *context) bool checkExprHasSubLink(Node *node) { - /* * If a Query is passed, examine it --- but we will not recurse into * sub-Queries. @@ -596,13 +594,13 @@ AddQual(Query *parsetree, Node *qual) * There's noplace to put the qual on a utility statement. * * If it's a NOTIFY, silently ignore the qual; this means that the - * NOTIFY will execute, whether or not there are any qualifying rows. - * While clearly wrong, this is much more useful than refusing to - * execute the rule at all, and extra NOTIFY events are harmless for - * typical uses of NOTIFY. + * NOTIFY will execute, whether or not there are any qualifying + * rows. While clearly wrong, this is much more useful than + * refusing to execute the rule at all, and extra NOTIFY events + * are harmless for typical uses of NOTIFY. * - * If it isn't a NOTIFY, error out, since unconditional execution - * of other utility stmts is unlikely to be wanted. (This case is + * If it isn't a NOTIFY, error out, since unconditional execution of + * other utility stmts is unlikely to be wanted. (This case is * not currently allowed anyway, but keep the test for safety.) */ if (parsetree->utilityStmt && IsA(parsetree->utilityStmt, NotifyStmt)) @@ -680,7 +678,6 @@ AddNotHavingQual(Query *parsetree, Node *havingQual) AddHavingQual(parsetree, notqual); } - #endif void @@ -733,7 +730,6 @@ FindMatchingTLEntry(List *tlist, char *e_attname) } return NULL; } - #endif @@ -999,5 +995,4 @@ HandleRIRAttributeRule(Query *parsetree, query_tree_mutator(parsetree, HandleRIRAttributeRule_mutator, (void *) &context, true); } - #endif /* NOT_USED */ diff --git a/src/backend/storage/buffer/buf_init.c b/src/backend/storage/buffer/buf_init.c index 322c45b031..cd0453c573 100644 --- a/src/backend/storage/buffer/buf_init.c +++ b/src/backend/storage/buffer/buf_init.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/buffer/buf_init.c,v 1.45 2001/10/01 05:36:13 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/buffer/buf_init.c,v 1.46 2001/10/25 05:49:41 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -183,8 +183,8 @@ InitBufferPool(void) /* * link the buffers into a circular, doubly-linked list to - * initialize free list, and initialize the buffer headers. - * Still don't know anything about replacement strategy in this file. + * initialize free list, and initialize the buffer headers. Still + * don't know anything about replacement strategy in this file. */ for (i = 0; i < Data_Descriptors; block += BLCKSZ, buf++, i++) { diff --git a/src/backend/storage/buffer/buf_table.c b/src/backend/storage/buffer/buf_table.c index d54d5e6915..eb4ce0330c 100644 --- a/src/backend/storage/buffer/buf_table.c +++ b/src/backend/storage/buffer/buf_table.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/buffer/buf_table.c,v 1.24 2001/10/05 17:28:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/buffer/buf_table.c,v 1.25 2001/10/25 05:49:41 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -61,7 +61,7 @@ InitBufTable(void) BufferDesc * BufTableLookup(BufferTag *tagPtr) { - BufferLookupEnt *result; + BufferLookupEnt *result; if (tagPtr->blockNum == P_NEW) return NULL; @@ -80,7 +80,7 @@ BufTableLookup(BufferTag *tagPtr) bool BufTableDelete(BufferDesc *buf) { - BufferLookupEnt *result; + BufferLookupEnt *result; /* * buffer not initialized or has been removed from table already. @@ -116,7 +116,7 @@ BufTableDelete(BufferDesc *buf) bool BufTableInsert(BufferDesc *buf) { - BufferLookupEnt *result; + BufferLookupEnt *result; bool found; /* cannot insert it twice */ @@ -152,5 +152,4 @@ DBG_LookupListCheck(int nlookup) hash_stats("Shared", SharedBufHash); } - #endif diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c index 86c2c478f4..0a74896e95 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.117 2001/09/29 04:02:23 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/buffer/bufmgr.c,v 1.118 2001/10/25 05:49:41 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -88,9 +88,9 @@ extern void AbortBufferIO(void); #define BUFFER_IS_BROKEN(buf) ((buf->flags & BM_IO_ERROR) && !(buf->flags & BM_DIRTY)) static Buffer ReadBufferInternal(Relation reln, BlockNumber blockNum, - bool bufferLockHeld); + bool bufferLockHeld); static BufferDesc *BufferAlloc(Relation reln, BlockNumber blockNum, - bool *foundPtr); + bool *foundPtr); static int ReleaseBufferWithBufferLock(Buffer buffer); static int BufferReplace(BufferDesc *bufHdr); void PrintBufferDescs(void); @@ -173,6 +173,7 @@ ReadBufferInternal(Relation reln, BlockNumber blockNum, blockNum = reln->rd_nblocks = smgrnblocks(DEFAULT_SMGR, reln); reln->rd_nblocks++; } + /* * lookup the buffer. IO_IN_PROGRESS is set if the requested * block is not currently in memory. @@ -198,12 +199,14 @@ ReadBufferInternal(Relation reln, BlockNumber blockNum, /* That is, we're done if we expected to be able to find it ... */ if (!isExtend) return BufferDescriptorGetBuffer(bufHdr); + /* - * If we found a buffer when we were expecting to extend the relation, - * the implication is that a buffer was already created for the next - * page position, but then smgrextend failed to write the page. - * We'd better try the smgrextend again. But since BufferAlloc - * won't have done StartBufferIO, we must do that first. + * If we found a buffer when we were expecting to extend the + * relation, the implication is that a buffer was already created + * for the next page position, but then smgrextend failed to write + * the page. We'd better try the smgrextend again. But since + * BufferAlloc won't have done StartBufferIO, we must do that + * first. */ if (!isLocalBuf) { @@ -308,7 +311,6 @@ BufferAlloc(Relation reln, buf = BufTableLookup(&newTag); if (buf != NULL) { - /* * Found it. Now, (a) pin the buffer so no one steals it from the * buffer pool, (b) check IO_IN_PROGRESS, someone may be faulting @@ -326,7 +328,6 @@ BufferAlloc(Relation reln, } if (BUFFER_IS_BROKEN(buf)) { - /* * I couldn't understand the following old comment. If there's * no IO for the buffer and the buffer is BROKEN,it should be @@ -481,7 +482,6 @@ BufferAlloc(Relation reln, buf2 = BufTableLookup(&newTag); if (buf2 != NULL) { - /* * Found it. Someone has already done what we're about to * do. We'll just handle this as if it were found in the @@ -853,9 +853,9 @@ WaitIO(BufferDesc *buf) /* * Changed to wait until there's no IO - Inoue 01/13/2000 * - * Note this is *necessary* because an error abort in the process - * doing I/O could release the io_in_progress_lock prematurely. - * See AbortBufferIO. + * Note this is *necessary* because an error abort in the process doing + * I/O could release the io_in_progress_lock prematurely. See + * AbortBufferIO. */ while ((buf->flags & BM_IO_IN_PROGRESS) != 0) { @@ -930,7 +930,7 @@ ResetBufferPool(bool isCommit) { BufferDesc *buf = &BufferDescriptors[i]; - PrivateRefCount[i] = 1; /* make sure we release shared pin */ + PrivateRefCount[i] = 1; /* make sure we release shared pin */ LWLockAcquire(BufMgrLock, LW_EXCLUSIVE); UnpinBuffer(buf); LWLockRelease(BufMgrLock); @@ -1090,9 +1090,9 @@ BlockNumber RelationGetNumberOfBlocks(Relation relation) { /* - * relation->rd_nblocks should be accurate already if the relation - * is myxactonly. (XXX how safe is that really?) Don't call smgr - * on a view, either. + * relation->rd_nblocks should be accurate already if the relation is + * myxactonly. (XXX how safe is that really?) Don't call smgr on a + * view, either. */ if (relation->rd_rel->relkind == RELKIND_VIEW) relation->rd_nblocks = 0; @@ -1147,7 +1147,6 @@ DropRelationBuffers(Relation rel) recheck: if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node)) { - /* * If there is I/O in progress, better wait till it's done; * don't want to delete the relation out from under someone @@ -1231,7 +1230,6 @@ DropRelFileNodeBuffers(RelFileNode rnode) recheck: if (RelFileNodeEquals(bufHdr->tag.rnode, rnode)) { - /* * If there is I/O in progress, better wait till it's done; * don't want to delete the relation out from under someone @@ -1307,7 +1305,6 @@ recheck: */ if (bufHdr->tag.rnode.tblNode == dbid) { - /* * If there is I/O in progress, better wait till it's done; * don't want to delete the database out from under someone @@ -1428,7 +1425,6 @@ BufferPoolBlowaway() BufTableDelete(&BufferDescriptors[i - 1]); } } - #endif /* --------------------------------------------------------------------- @@ -1681,7 +1677,6 @@ refcount = %ld, file: %s, line: %d\n", PrivateRefCount[buffer - 1], file, line); } } - #endif #ifdef NOT_USED @@ -1701,7 +1696,6 @@ refcount = %ld, file: %s, line: %d\n", PrivateRefCount[buffer - 1], file, line); } } - #endif #ifdef NOT_USED @@ -1742,7 +1736,6 @@ refcount = %ld, file: %s, line: %d\n", } return b; } - #endif #ifdef BMTRACE @@ -1888,7 +1881,6 @@ _bm_die(Oid dbId, Oid relId, int blkNo, int bufNo, kill(getpid(), SIGILL); } - #endif /* BMTRACE */ /* @@ -1943,7 +1935,7 @@ UnlockBuffers(void) for (i = 0; i < NBuffers; i++) { - bits8 buflocks = BufferLocks[i]; + bits8 buflocks = BufferLocks[i]; if (buflocks == 0) continue; @@ -1960,9 +1952,11 @@ UnlockBuffers(void) if (buflocks & BL_PIN_COUNT_LOCK) { LWLockAcquire(BufMgrLock, LW_EXCLUSIVE); + /* - * Don't complain if flag bit not set; it could have been reset - * but we got a cancel/die interrupt before getting the signal. + * Don't complain if flag bit not set; it could have been + * reset but we got a cancel/die interrupt before getting the + * signal. */ if ((buf->flags & BM_PIN_COUNT_WAITER) != 0 && buf->wait_backend_id == MyBackendId) @@ -1992,13 +1986,9 @@ LockBuffer(Buffer buffer, int mode) buf = &(BufferDescriptors[buffer - 1]); if (mode == BUFFER_LOCK_UNLOCK) - { LWLockRelease(buf->cntx_lock); - } else if (mode == BUFFER_LOCK_SHARE) - { LWLockAcquire(buf->cntx_lock, LW_SHARED); - } else if (mode == BUFFER_LOCK_EXCLUSIVE) { LWLockAcquire(buf->cntx_lock, LW_EXCLUSIVE); @@ -2012,9 +2002,7 @@ LockBuffer(Buffer buffer, int mode) buf->cntxDirty = true; } else - { elog(ERROR, "LockBuffer: unknown lock mode %d", mode); - } } /* @@ -2163,7 +2151,6 @@ InitBufferIO(void) { InProgressBuf = (BufferDesc *) 0; } - #endif /* @@ -2180,11 +2167,11 @@ AbortBufferIO(void) if (buf) { /* - * Since LWLockReleaseAll has already been called, - * we're not holding the buffer's io_in_progress_lock. - * We have to re-acquire it so that we can use TerminateBufferIO. - * Anyone who's executing WaitIO on the buffer will be in a busy spin - * until we succeed in doing this. + * Since LWLockReleaseAll has already been called, we're not + * holding the buffer's io_in_progress_lock. We have to re-acquire + * it so that we can use TerminateBufferIO. Anyone who's executing + * WaitIO on the buffer will be in a busy spin until we succeed in + * doing this. */ LWLockAcquire(buf->io_in_progress_lock, LW_EXCLUSIVE); diff --git a/src/backend/storage/buffer/freelist.c b/src/backend/storage/buffer/freelist.c index f8ac2e287c..073d3ae4fc 100644 --- a/src/backend/storage/buffer/freelist.c +++ b/src/backend/storage/buffer/freelist.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/buffer/freelist.c,v 1.25 2001/09/29 04:02:23 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/buffer/freelist.c,v 1.26 2001/10/25 05:49:41 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -91,7 +91,7 @@ AddBufferToFreelist(BufferDesc *bf) void PinBuffer(BufferDesc *buf) { - int b = BufferDescriptorGetBuffer(buf) - 1; + int b = BufferDescriptorGetBuffer(buf) - 1; if (buf->refcount == 0) { @@ -129,7 +129,6 @@ refcount = %ld, file: %s, line: %d\n", PrivateRefCount[buffer - 1], file, line); } } - #endif #undef UnpinBuffer @@ -143,7 +142,7 @@ refcount = %ld, file: %s, line: %d\n", void UnpinBuffer(BufferDesc *buf) { - int b = BufferDescriptorGetBuffer(buf) - 1; + int b = BufferDescriptorGetBuffer(buf) - 1; IsNotInQueue(buf); Assert(buf->refcount > 0); @@ -186,7 +185,6 @@ refcount = %ld, file: %s, line: %d\n", PrivateRefCount[buffer - 1], file, line); } } - #endif /* @@ -277,7 +275,6 @@ DBG_FreeListCheck(int nfree) printf("\tfree list corrupted: %d-th buffer is %d\n", nfree, buf->buf_id); } - #endif #ifdef NOT_USED @@ -312,5 +309,4 @@ PrintBufferFreeList() buf = &(BufferDescriptors[buf->freeNext]); } } - #endif diff --git a/src/backend/storage/file/buffile.c b/src/backend/storage/file/buffile.c index 2ce6d31c38..bb8b8f39a7 100644 --- a/src/backend/storage/file/buffile.c +++ b/src/backend/storage/file/buffile.c @@ -7,7 +7,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/file/buffile.c,v 1.10 2001/03/22 03:59:45 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/file/buffile.c,v 1.11 2001/10/25 05:49:41 momjian Exp $ * * NOTES: * @@ -135,7 +135,7 @@ extendBufFile(BufFile *file) * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are * written to it). */ -BufFile * +BufFile * BufFileCreateTemp(void) { BufFile *file; @@ -158,12 +158,11 @@ BufFileCreateTemp(void) * to attach a BufFile to a non-temporary file. Note that BufFiles created * in this way CANNOT be expanded into multiple files. */ -BufFile * +BufFile * BufFileCreate(File file) { return makeBufFile(file); } - #endif /* @@ -254,7 +253,6 @@ BufFileDumpBuffer(BufFile *file) */ while (wpos < file->nbytes) { - /* * Advance to next component file if necessary and possible. */ @@ -489,7 +487,6 @@ BufFileSeek(BufFile *file, int fileno, long offset, int whence) newOffset >= file->curOffset && newOffset <= file->curOffset + file->nbytes) { - /* * Seek is to a point within existing buffer; we can just adjust * pos-within-buffer, without flushing buffer. Note this is OK @@ -575,5 +572,4 @@ BufFileTellBlock(BufFile *file) blknum += file->curFile * RELSEG_SIZE; return blknum; } - #endif diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index c2db3c8dea..3c6722863e 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.84 2001/09/30 18:57:45 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/file/fd.c,v 1.85 2001/10/25 05:49:41 momjian Exp $ * * NOTES: * @@ -92,7 +92,7 @@ * far beyond what they can really support. This GUC parameter limits what * we will believe. */ -int max_files_per_process = 1000; +int max_files_per_process = 1000; /* Debugging.... */ @@ -122,7 +122,7 @@ typedef struct vfd #define FD_TEMPORARY (1 << 1)/* should be unlinked when closed */ File nextFree; /* link to next free VFD, if in freelist */ - File lruMoreRecently;/* doubly linked recency-of-use list */ + File lruMoreRecently; /* doubly linked recency-of-use list */ File lruLessRecently; long seekPos; /* current logical file position */ char *fileName; /* name of file, or NULL for unused VFD */ @@ -307,16 +307,16 @@ pg_nofile(void) elog(DEBUG, "pg_nofile: sysconf(_SC_OPEN_MAX) failed; using %ld", no_files); } -#else /* !HAVE_SYSCONF */ +#else /* !HAVE_SYSCONF */ #ifdef NOFILE no_files = (long) NOFILE; #else no_files = (long) max_files_per_process; #endif -#endif /* HAVE_SYSCONF */ +#endif /* HAVE_SYSCONF */ /* - * Some platforms return hopelessly optimistic values. Apply a + * Some platforms return hopelessly optimistic values. Apply a * configurable upper limit. */ if (no_files > (long) max_files_per_process) @@ -355,7 +355,6 @@ _dump_lru(void) sprintf(buf + strlen(buf), "LEAST"); elog(DEBUG, buf); } - #endif /* FDDEBUG */ static void @@ -497,7 +496,6 @@ ReleaseLruFile(void) if (nfile > 0) { - /* * There are opened files and so there should be at least one used * vfd in the ring. @@ -537,7 +535,6 @@ AllocateVfd(void) if (VfdCache[0].nextFree == 0) { - /* * The free list is empty so it is time to increase the size of * the array. We choose to double it each time this happens. @@ -550,8 +547,8 @@ AllocateVfd(void) newCacheSize = 32; /* - * Be careful not to clobber VfdCache ptr if realloc fails; - * we will need it during proc_exit cleanup! + * Be careful not to clobber VfdCache ptr if realloc fails; we + * will need it during proc_exit cleanup! */ newVfdCache = (Vfd *) realloc(VfdCache, sizeof(Vfd) * newCacheSize); if (newVfdCache == NULL) @@ -624,9 +621,7 @@ filepath(const char *filename) sprintf(buf, "%s/%s", DatabasePath, filename); } else - { buf = pstrdup(filename); - } #ifdef FILEDEBUG printf("filepath: path is %s\n", buf); @@ -657,7 +652,6 @@ FileAccess(File file) } else if (VfdCache[0].lruLessRecently != file) { - /* * We now know that the file is open and that it is not the last * one accessed, so we need to move it to the head of the Lru @@ -682,7 +676,6 @@ FileInvalidate(File file) if (!FileIsNotOpen(file)) LruDelete(file); } - #endif static File @@ -798,15 +791,15 @@ OpenTemporaryFile(void) 0600); if (file <= 0) { - char *dirpath; + char *dirpath; /* - * We might need to create the pg_tempfiles subdirectory, if - * no one has yet done so. + * We might need to create the pg_tempfiles subdirectory, if no + * one has yet done so. * * Don't check for error from mkdir; it could fail if someone else - * just did the same thing. If it doesn't work then we'll bomb out - * on the second create attempt, instead. + * just did the same thing. If it doesn't work then we'll bomb + * out on the second create attempt, instead. */ dirpath = filepath(PG_TEMP_FILES_DIR); mkdir(dirpath, S_IRWXU); @@ -1009,7 +1002,6 @@ FileTell(File file) file, VfdCache[file].fileName)); return VfdCache[file].seekPos; } - #endif int @@ -1077,7 +1069,6 @@ FileSync(File file) } else { - /* * We don't use FileAccess() because we don't want to force the * file to the front of the LRU ring; we aren't expecting to @@ -1275,17 +1266,17 @@ AtEOXact_Files(void) void RemovePgTempFiles(void) { - char db_path[MAXPGPATH]; - char temp_path[MAXPGPATH]; - char rm_path[MAXPGPATH]; + char db_path[MAXPGPATH]; + char temp_path[MAXPGPATH]; + char rm_path[MAXPGPATH]; DIR *db_dir; DIR *temp_dir; - struct dirent *db_de; - struct dirent *temp_de; + struct dirent *db_de; + struct dirent *temp_de; /* - * Cycle through pg_tempfiles for all databases - * and remove old temp files. + * Cycle through pg_tempfiles for all databases and remove old temp + * files. */ snprintf(db_path, sizeof(db_path), "%s/base", DataDir); if ((db_dir = opendir(db_path)) != NULL) @@ -1317,14 +1308,12 @@ RemovePgTempFiles(void) if (strncmp(temp_de->d_name, PG_TEMP_FILE_PREFIX, strlen(PG_TEMP_FILE_PREFIX)) == 0) - { unlink(rm_path); - } else { /* - * would prefer to use elog here, but it's not - * up and running during postmaster startup... + * would prefer to use elog here, but it's not up + * and running during postmaster startup... */ fprintf(stderr, "Unexpected file found in temporary-files directory: %s\n", diff --git a/src/backend/storage/freespace/freespace.c b/src/backend/storage/freespace/freespace.c index b51b1fb230..1956b92d68 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.7 2001/10/05 17:28:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/freespace/freespace.c,v 1.8 2001/10/25 05:49:42 momjian Exp $ * * * NOTES: @@ -19,13 +19,13 @@ * These currently work as follows: * * The number of distinct relations tracked is limited by a configuration - * variable (MaxFSMRelations). When this would be exceeded, we discard the - * least frequently used relation. A previously-unknown relation is always + * variable (MaxFSMRelations). When this would be exceeded, we discard the + * least frequently used relation. A previously-unknown relation is always * entered into the map with useCount 1 on first reference, even if this * causes an existing entry with higher useCount to be discarded. This may * cause a little bit of thrashing among the bottom entries in the list, * but if we didn't do it then there'd be no way for a relation not in the - * map to get in once the map is full. Note we allow a relation to be in the + * map to get in once the map is full. Note we allow a relation to be in the * map even if no pages are currently stored for it: this allows us to track * its useCount & threshold, which may eventually go high enough to give it * priority for page storage. @@ -89,13 +89,14 @@ struct FSMHeader */ struct FSMRelation { - RelFileNode key; /* hash key (must be first) */ + RelFileNode key; /* hash key (must be first) */ FSMRelation *nextRel; /* next rel in useCount order */ FSMRelation *priorRel; /* prior rel in useCount order */ int useCount; /* use count for prioritizing rels */ Size threshold; /* minimum amount of free space to keep */ int nextPage; /* index (from 0) to start next search at */ - int numPages; /* total number of pages we have info about */ + int numPages; /* total number of pages we have info + * about */ int numChunks; /* number of FSMChunks allocated to rel */ FSMChunk *relChunks; /* linked list of page info chunks */ }; @@ -109,21 +110,22 @@ struct FSMRelation * to the freelist; but there's no point in doing the compaction before that. */ -#define CHUNKPAGES 32 /* each chunk can store this many pages */ +#define CHUNKPAGES 32 /* each chunk can store this many pages */ struct FSMChunk { FSMChunk *next; /* linked-list link */ int numPages; /* number of pages described here */ - BlockNumber pages[CHUNKPAGES]; /* page numbers within relation */ - ItemLength bytes[CHUNKPAGES]; /* free space available on each page */ + BlockNumber pages[CHUNKPAGES]; /* page numbers within relation */ + ItemLength bytes[CHUNKPAGES]; /* free space available on each + * page */ }; -int MaxFSMRelations; /* these are set by guc.c */ -int MaxFSMPages; +int MaxFSMRelations; /* these are set by guc.c */ +int MaxFSMPages; -static FSMHeader *FreeSpaceMap; /* points to FSMHeader in shared memory */ +static FSMHeader *FreeSpaceMap; /* points to FSMHeader in shared memory */ static FSMRelation *lookup_fsm_rel(RelFileNode *rel); @@ -134,16 +136,16 @@ static void unlink_fsm_rel(FSMRelation *fsmrel); static void free_chunk_chain(FSMChunk *fchunk); static BlockNumber find_free_space(FSMRelation *fsmrel, Size spaceNeeded); static void fsm_record_free_space(FSMRelation *fsmrel, BlockNumber page, - Size spaceAvail); + Size spaceAvail); static bool lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, - FSMChunk **outChunk, int *outChunkRelIndex); + FSMChunk **outChunk, int *outChunkRelIndex); static bool insert_fsm_page_entry(FSMRelation *fsmrel, - BlockNumber page, Size spaceAvail, - FSMChunk *chunk, int chunkRelIndex); + BlockNumber page, Size spaceAvail, + FSMChunk *chunk, int chunkRelIndex); static bool push_fsm_page_entry(BlockNumber page, Size spaceAvail, - FSMChunk *chunk, int chunkRelIndex); + FSMChunk *chunk, int chunkRelIndex); static void delete_fsm_page_entry(FSMRelation *fsmrel, FSMChunk *chunk, - int chunkRelIndex); + int chunkRelIndex); static void compact_fsm_page_list(FSMRelation *fsmrel); static void acquire_fsm_free_space(void); @@ -241,32 +243,34 @@ 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 (via RecordFreeSpace) and - * then try again. If InvalidBlockNumber is returned, extend the relation. + * then try again. If InvalidBlockNumber is returned, extend the relation. */ BlockNumber GetPageWithFreeSpace(RelFileNode *rel, Size spaceNeeded) { FSMRelation *fsmrel; - BlockNumber freepage; + BlockNumber freepage; LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE); + /* * We always add a rel to the hashtable when it is inquired about. */ fsmrel = create_fsm_rel(rel); + /* - * Adjust the threshold towards the space request. This essentially + * Adjust the threshold towards the space request. This essentially * implements an exponential moving average with an equivalent period * of about 63 requests. Ignore silly requests, however, to ensure * that the average stays in bounds. * * In theory, if the threshold increases here we should immediately - * delete any pages that fall below the new threshold. In practice - * it seems OK to wait until we have a need to compact space. + * delete any pages that fall below the new threshold. In practice it + * seems OK to wait until we have a need to compact space. */ if (spaceNeeded > 0 && spaceNeeded < BLCKSZ) { - int cur_avg = (int) fsmrel->threshold; + int cur_avg = (int) fsmrel->threshold; cur_avg += ((int) spaceNeeded - cur_avg) / 32; fsmrel->threshold = (Size) cur_avg; @@ -293,6 +297,7 @@ RecordFreeSpace(RelFileNode *rel, BlockNumber page, Size spaceAvail) AssertArg(spaceAvail < BLCKSZ); LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE); + /* * We choose not to add rels to the hashtable unless they've been * inquired about with GetPageWithFreeSpace. Also, a Record operation @@ -315,27 +320,29 @@ RecordAndGetPageWithFreeSpace(RelFileNode *rel, Size spaceNeeded) { FSMRelation *fsmrel; - BlockNumber freepage; + BlockNumber freepage; /* Sanity check: ensure spaceAvail will fit into ItemLength */ AssertArg(oldSpaceAvail < BLCKSZ); LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE); + /* * We always add a rel to the hashtable when it is inquired about. */ fsmrel = create_fsm_rel(rel); + /* * Adjust the threshold towards the space request, same as in * GetPageWithFreeSpace. * - * Note that we do this before storing data for oldPage, which means - * this isn't exactly equivalent to Record followed by Get; but it - * seems appropriate to adjust the threshold first. + * Note that we do this before storing data for oldPage, which means this + * isn't exactly equivalent to Record followed by Get; but it seems + * appropriate to adjust the threshold first. */ if (spaceNeeded > 0 && spaceNeeded < BLCKSZ) { - int cur_avg = (int) fsmrel->threshold; + int cur_avg = (int) fsmrel->threshold; cur_avg += ((int) spaceNeeded - cur_avg) / 32; fsmrel->threshold = (Size) cur_avg; @@ -356,7 +363,7 @@ RecordAndGetPageWithFreeSpace(RelFileNode *rel, * pages in that page number range (inclusive). This allows obsolete info * to be discarded. Second, if nPages > 0, record the page numbers and free * space amounts in the given arrays. As with RecordFreeSpace, the FSM is at - * liberty to discard some of the information. However, it *must* discard + * liberty to discard some of the information. However, it *must* discard * previously stored info in the minPage..maxPage range (for example, this * case is used to remove info about deleted pages during relation truncation). */ @@ -390,7 +397,7 @@ MultiRecordFreeSpace(RelFileNode *rel, done = false; while (chunk && !done) { - int numPages = chunk->numPages; + int numPages = chunk->numPages; for (; chunkRelIndex < numPages; chunkRelIndex++) { @@ -407,22 +414,23 @@ MultiRecordFreeSpace(RelFileNode *rel, /* Now compact out the zeroed entries */ compact_fsm_page_list(fsmrel); } + /* * Add new entries, if appropriate. * * XXX we could probably be smarter about this than doing it - * completely separately for each one. FIXME later. + * completely separately for each one. FIXME later. * - * One thing we can do is short-circuit the process entirely if - * a page (a) has too little free space to be recorded, and (b) - * is within the minPage..maxPage range --- then we deleted any - * old entry above, and we aren't going to make a new one. - * This is particularly useful since in most cases, all the passed - * pages will in fact be in the minPage..maxPage range. + * One thing we can do is short-circuit the process entirely if a + * page (a) has too little free space to be recorded, and (b) is + * within the minPage..maxPage range --- then we deleted any old + * entry above, and we aren't going to make a new one. This is + * particularly useful since in most cases, all the passed pages + * will in fact be in the minPage..maxPage range. */ for (i = 0; i < nPages; i++) { - BlockNumber page = pages[i]; + BlockNumber page = pages[i]; Size avail = spaceAvail[i]; if (avail >= fsmrel->threshold || @@ -470,7 +478,7 @@ FreeSpaceMapForgetDatabase(Oid dbid) LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE); for (fsmrel = FreeSpaceMap->relList; fsmrel; fsmrel = nextrel) { - nextrel = fsmrel->nextRel; /* in case we delete it */ + nextrel = fsmrel->nextRel; /* in case we delete it */ if (fsmrel->key.tblNode == dbid) delete_fsm_rel(fsmrel); } @@ -525,7 +533,7 @@ create_fsm_rel(RelFileNode *rel) { /* New hashtable entry, initialize it (hash_search set the key) */ fsmrel->useCount = 1; - fsmrel->threshold = BLCKSZ/2; /* starting point for new entry */ + fsmrel->threshold = BLCKSZ / 2; /* starting point for new entry */ fsmrel->nextPage = 0; fsmrel->numPages = 0; fsmrel->numChunks = 0; @@ -533,6 +541,7 @@ create_fsm_rel(RelFileNode *rel) /* Discard lowest-priority existing rel, if we are over limit */ if (FreeSpaceMap->numRels >= MaxFSMRelations) delete_fsm_rel(FreeSpaceMap->relListTail); + /* * Add new entry in front of any others with useCount 1 (since it * is more recently used than them). @@ -545,18 +554,16 @@ create_fsm_rel(RelFileNode *rel) } else { - int myCount; + int myCount; /* Existing entry, advance its useCount */ - if (++(fsmrel->useCount) >= INT_MAX/2) + if (++(fsmrel->useCount) >= INT_MAX / 2) { /* When useCounts threaten to overflow, reduce 'em all 2X */ for (oldrel = FreeSpaceMap->relList; oldrel != NULL; oldrel = oldrel->nextRel) - { oldrel->useCount >>= 1; - } } /* If warranted, move it up the priority list */ oldrel = fsmrel->priorRel; @@ -665,7 +672,7 @@ free_chunk_chain(FSMChunk *fchunk) /* * Look to see if a page with at least the specified amount of space is - * available in the given FSMRelation. If so, return its page number, + * available in the given FSMRelation. If so, return its page number, * and advance the nextPage counter so that the next inquiry will return * a different page if possible. Return InvalidBlockNumber if no success. */ @@ -699,7 +706,7 @@ find_free_space(FSMRelation *fsmrel, Size spaceNeeded) /* Check the next page */ if ((Size) curChunk->bytes[chunkRelIndex] >= spaceNeeded) { - fsmrel->nextPage = pageIndex+1; + fsmrel->nextPage = pageIndex + 1; return curChunk->pages[chunkRelIndex]; } /* Advance pageIndex and chunkRelIndex, wrapping around if needed */ @@ -739,12 +746,12 @@ fsm_record_free_space(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail) /* * No existing entry; add one if spaceAvail exceeds threshold. * - * CORNER CASE: if we have to do acquire_fsm_free_space then - * our own threshold will increase, possibly meaning that we - * shouldn't store the page after all. Loop to redo the test - * if that happens. The loop also covers the possibility that - * acquire_fsm_free_space must be executed more than once to - * free any space (ie, thresholds must be more than doubled). + * CORNER CASE: if we have to do acquire_fsm_free_space then our own + * threshold will increase, possibly meaning that we shouldn't + * store the page after all. Loop to redo the test if that + * happens. The loop also covers the possibility that + * acquire_fsm_free_space must be executed more than once to free + * any space (ie, thresholds must be more than doubled). */ while (spaceAvail >= fsmrel->threshold) { @@ -755,6 +762,7 @@ fsm_record_free_space(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail) acquire_fsm_free_space(); if (spaceAvail < fsmrel->threshold) break; + /* * Need to redo the lookup since our own page list may well * have lost entries, so position is not correct anymore. @@ -784,10 +792,10 @@ lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, for (chunk = fsmrel->relChunks; chunk; chunk = chunk->next) { - int numPages = chunk->numPages; + int numPages = chunk->numPages; /* Can skip the chunk quickly if page must be after last in chunk */ - if (numPages > 0 && page <= chunk->pages[numPages-1]) + if (numPages > 0 && page <= chunk->pages[numPages - 1]) { for (chunkRelIndex = 0; chunkRelIndex < numPages; chunkRelIndex++) { @@ -801,9 +809,10 @@ lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, /* Should not get here, given above test */ Assert(false); } + /* - * If we are about to fall off the end, and there's space available - * in the end chunk, return a pointer to it. + * If we are about to fall off the end, and there's space + * available in the end chunk, return a pointer to it. */ if (chunk->next == NULL && numPages < CHUNKPAGES) { @@ -812,6 +821,7 @@ lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, return false; } } + /* * Adding the page would require a new chunk (or, perhaps, compaction * of available free space --- not my problem here). @@ -838,7 +848,7 @@ insert_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail, { /* No free space within chunk list, so need another chunk */ if ((newChunk = FreeSpaceMap->freeChunks) == NULL) - return false; /* can't do it */ + return false; /* can't do it */ FreeSpaceMap->freeChunks = newChunk->next; FreeSpaceMap->numFreeChunks--; newChunk->next = NULL; @@ -870,10 +880,11 @@ insert_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail, fsmrel->nextPage++; /* don't return same page twice running */ return true; } + /* - * There is space available, but evidently it's before the place - * where the page entry needs to go. Compact the list and try again. - * This will require us to redo the search for the appropriate place. + * There is space available, but evidently it's before the place where + * the page entry needs to go. Compact the list and try again. This + * will require us to redo the search for the appropriate place. */ compact_fsm_page_list(fsmrel); if (lookup_fsm_page_entry(fsmrel, page, &newChunk, &newChunkRelIndex)) @@ -892,7 +903,7 @@ insert_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail, /* * Auxiliary routine for insert_fsm_page_entry: try to push entries to the - * right to insert at chunk/chunkRelIndex. Return TRUE if successful. + * right to insert at chunk/chunkRelIndex. Return TRUE if successful. * Note that the FSMRelation's own fields are not updated. */ static bool @@ -906,17 +917,17 @@ push_fsm_page_entry(BlockNumber page, Size spaceAvail, if (chunk->next == NULL) return false; /* no space */ /* try to push chunk's last item to next chunk */ - if (! push_fsm_page_entry(chunk->pages[CHUNKPAGES-1], - chunk->bytes[CHUNKPAGES-1], - chunk->next, 0)) + if (!push_fsm_page_entry(chunk->pages[CHUNKPAGES - 1], + chunk->bytes[CHUNKPAGES - 1], + chunk->next, 0)) return false; /* successfully pushed it */ chunk->numPages--; } for (i = chunk->numPages; i > chunkRelIndex; i--) { - chunk->pages[i] = chunk->pages[i-1]; - chunk->bytes[i] = chunk->bytes[i-1]; + chunk->pages[i] = chunk->pages[i - 1]; + chunk->bytes[i] = chunk->bytes[i - 1]; } chunk->numPages++; chunk->pages[chunkRelIndex] = page; @@ -939,12 +950,12 @@ delete_fsm_page_entry(FSMRelation *fsmrel, FSMChunk *chunk, int chunkRelIndex) lim = --chunk->numPages; for (i = chunkRelIndex; i < lim; i++) { - chunk->pages[i] = chunk->pages[i+1]; - chunk->bytes[i] = chunk->bytes[i+1]; + chunk->pages[i] = chunk->pages[i + 1]; + chunk->bytes[i] = chunk->bytes[i + 1]; } /* Compact the whole list if a chunk can be freed */ fsmrel->numPages--; - if (fsmrel->numPages <= (fsmrel->numChunks-1) * CHUNKPAGES) + if (fsmrel->numPages <= (fsmrel->numChunks - 1) * CHUNKPAGES) compact_fsm_page_list(fsmrel); } @@ -971,7 +982,7 @@ compact_fsm_page_list(FSMRelation *fsmrel) while (srcChunk != NULL) { - int srcPages = srcChunk->numPages; + int srcPages = srcChunk->numPages; while (srcIndex < srcPages) { @@ -1069,7 +1080,7 @@ DumpFreeSpace(void) nChunks = nPages = 0; for (chunk = fsmrel->relChunks; chunk; chunk = chunk->next) { - int numPages = chunk->numPages; + int numPages = chunk->numPages; nChunks++; for (chunkRelIndex = 0; chunkRelIndex < numPages; chunkRelIndex++) @@ -1105,5 +1116,4 @@ DumpFreeSpace(void) fprintf(stderr, "DumpFreeSpace: %d chunks in list, but numFreeChunks = %d\n", nChunks, FreeSpaceMap->numFreeChunks); } - #endif /* FREESPACE_DEBUG */ diff --git a/src/backend/storage/ipc/ipc.c b/src/backend/storage/ipc/ipc.c index 1eb28a48cd..d083d071bd 100644 --- a/src/backend/storage/ipc/ipc.c +++ b/src/backend/storage/ipc/ipc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/ipc/ipc.c,v 1.71 2001/10/01 23:26:55 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/ipc.c,v 1.72 2001/10/25 05:49:42 momjian Exp $ * * NOTES * @@ -114,7 +114,6 @@ static int on_proc_exit_index, void proc_exit(int code) { - /* * Once we set this flag, we are committed to exit. Any elog() will * NOT send control back to the main loop, but right back here. @@ -275,7 +274,6 @@ InternalIpcSemaphoreCreate(IpcSemaphoreKey semKey, if (semId < 0) { - /* * Fail quietly if error indicates a collision with existing set. * One would expect EEXIST, given that we said IPC_EXCL, but @@ -592,7 +590,7 @@ InternalIpcMemoryCreate(IpcMemoryKey memKey, uint32 size, int permission) "\nThis error usually means that PostgreSQL's request for a shared memory\n" "segment exceeded your kernel's SHMMAX parameter. You can either\n" "reduce the request size or reconfigure the kernel with larger SHMMAX.\n" - "To reduce the request size (currently %u bytes), reduce\n" + "To reduce the request size (currently %u bytes), reduce\n" "PostgreSQL's shared_buffers parameter (currently %d) and/or\n" "its max_connections parameter (currently %d).\n" "\n" @@ -607,8 +605,8 @@ InternalIpcMemoryCreate(IpcMemoryKey memKey, uint32 size, int permission) else if (errno == ENOMEM) fprintf(stderr, "\nThis error usually means that PostgreSQL's request for a shared\n" - "memory segment exceeded available memory or swap space.\n" - "To reduce the request size (currently %u bytes), reduce\n" + "memory segment exceeded available memory or swap space.\n" + "To reduce the request size (currently %u bytes), reduce\n" "PostgreSQL's shared_buffers parameter (currently %d) and/or\n" "its max_connections parameter (currently %d).\n" "\n" @@ -623,7 +621,7 @@ InternalIpcMemoryCreate(IpcMemoryKey memKey, uint32 size, int permission) "It occurs either if all available shared memory IDs have been taken,\n" "in which case you need to raise the SHMMNI parameter in your kernel,\n" "or because the system's overall limit for shared memory has been\n" - "reached. If you cannot increase the shared memory limit,\n" + "reached. If you cannot increase the shared memory limit,\n" "reduce PostgreSQL's shared memory request (currently %u bytes),\n" "by reducing its shared_buffers parameter (currently %d) and/or\n" "its max_connections parameter (currently %d).\n" @@ -710,7 +708,6 @@ SharedMemoryIsInUse(IpcMemoryKey shmKey, IpcMemoryId shmId) */ if (shmctl(shmId, IPC_STAT, &shmStat) < 0) { - /* * EINVAL actually has multiple possible causes documented in the * shmctl man page, but we assume it must mean the segment no @@ -748,7 +745,7 @@ PrivateMemoryCreate(uint32 size) fprintf(stderr, "PrivateMemoryCreate: malloc(%u) failed\n", size); proc_exit(1); } - MemSet(memAddress, 0, size);/* keep Purify quiet */ + MemSet(memAddress, 0, size); /* keep Purify quiet */ /* Register on-exit routine to release storage */ on_shmem_exit(PrivateMemoryDelete, PointerGetDatum(memAddress)); diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c index 7dac93f3a0..cf841a614d 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.43 2001/09/29 04:02:23 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/ipci.c,v 1.44 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -83,8 +83,8 @@ CreateSharedMemoryAndSemaphores(bool makePrivate, int maxBackends) InitShmemAllocation(seghdr); /* - * Now initialize LWLocks, which do shared memory allocation and - * are needed for InitShmemIndex. + * Now initialize LWLocks, which do shared memory allocation and are + * needed for InitShmemIndex. */ CreateLWLocks(); diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c index 32f2cf98a1..3304ec67c5 100644 --- a/src/backend/storage/ipc/shmem.c +++ b/src/backend/storage/ipc/shmem.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/ipc/shmem.c,v 1.61 2001/10/05 17:28:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/shmem.c,v 1.62 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -97,8 +97,9 @@ InitShmemAllocation(void *seghdr) ShmemEnd = ShmemBase + shmhdr->totalsize; /* - * Initialize the spinlock used by ShmemAlloc. We have to do the - * space allocation the hard way, since ShmemAlloc can't be called yet. + * Initialize the spinlock used by ShmemAlloc. We have to do the + * space allocation the hard way, since ShmemAlloc can't be called + * yet. */ ShmemLock = (slock_t *) (((char *) shmhdr) + shmhdr->freeoffset); shmhdr->freeoffset += MAXALIGN(sizeof(slock_t)); @@ -234,7 +235,7 @@ InitShmemIndex(void) * table at once. */ HTAB * -ShmemInitHash(const char *name, /* table string name for shmem index */ +ShmemInitHash(const char *name, /* table string name for shmem index */ long init_size, /* initial table size */ long max_size, /* max size of the table */ HASHCTL *infoP, /* info about key and bucket size */ @@ -256,7 +257,7 @@ ShmemInitHash(const char *name, /* table string name for shmem index */ /* look it up in the shmem index */ location = ShmemInitStruct(name, - sizeof(HASHHDR) + infoP->dsize * sizeof(HASHSEGMENT), + sizeof(HASHHDR) + infoP->dsize * sizeof(HASHSEGMENT), &found); /* @@ -267,8 +268,8 @@ ShmemInitHash(const char *name, /* table string name for shmem index */ return NULL; /* - * if it already exists, attach to it rather than allocate and initialize - * new space + * if it already exists, attach to it rather than allocate and + * initialize new space */ if (found) hash_flags |= HASH_ATTACH; diff --git a/src/backend/storage/ipc/shmqueue.c b/src/backend/storage/ipc/shmqueue.c index b840596a6f..4f67788742 100644 --- a/src/backend/storage/ipc/shmqueue.c +++ b/src/backend/storage/ipc/shmqueue.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/ipc/shmqueue.c,v 1.16 2001/03/22 03:59:45 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/shmqueue.c,v 1.17 2001/10/25 05:49:42 momjian Exp $ * * NOTES * @@ -33,7 +33,6 @@ #define SHMQUEUE_DEBUG_ELOG NOTICE static void dumpQ(SHM_QUEUE *q, char *s); - #endif @@ -59,7 +58,6 @@ SHMQueueIsDetached(SHM_QUEUE *queue) Assert(SHM_PTR_VALID(queue)); return (queue)->prev == INVALID_OFFSET; } - #endif /* @@ -152,7 +150,6 @@ SHMQueueInsertAfter(SHM_QUEUE *queue, SHM_QUEUE *elem) dumpQ(queue, "in SHMQueueInsertAfter: end"); #endif } - #endif /* NOT_USED */ /*-------------------- @@ -256,5 +253,4 @@ dumpQ(SHM_QUEUE *q, char *s) strcat(buf, elem); elog(SHMQUEUE_DEBUG_ELOG, "%s: %s", s, buf); } - #endif /* SHMQUEUE_DEBUG */ diff --git a/src/backend/storage/ipc/sinval.c b/src/backend/storage/ipc/sinval.c index 4a3b1114a9..1d1e9076d7 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.42 2001/09/29 15:29:48 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/ipc/sinval.c,v 1.43 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -42,7 +42,7 @@ CreateSharedInvalidationState(int maxBackends) void InitBackendSharedInvalidationState(void) { - int flag; + int flag; LWLockAcquire(SInvalLock, LW_EXCLUSIVE); flag = SIBackendInit(shmInvalBuffer); @@ -75,8 +75,8 @@ SendSharedInvalidMessage(SharedInvalidationMessage *msg) */ void ReceiveSharedInvalidMessages( - void (*invalFunction) (SharedInvalidationMessage *msg), - void (*resetFunction) (void)) + void (*invalFunction) (SharedInvalidationMessage *msg), + void (*resetFunction) (void)) { SharedInvalidationMessage data; int getResult; @@ -85,19 +85,19 @@ ReceiveSharedInvalidMessages( for (;;) { /* - * We can run SIGetDataEntry in parallel with other backends running - * SIGetDataEntry for themselves, since each instance will modify - * only fields of its own backend's ProcState, and no instance will - * look at fields of other backends' ProcStates. We express this - * by grabbing SInvalLock in shared mode. Note that this is not - * exactly the normal (read-only) interpretation of a shared lock! - * Look closely at the interactions before allowing SInvalLock to - * be grabbed in shared mode for any other reason! + * We can run SIGetDataEntry in parallel with other backends + * running SIGetDataEntry for themselves, since each instance will + * modify only fields of its own backend's ProcState, and no + * instance will look at fields of other backends' ProcStates. We + * express this by grabbing SInvalLock in shared mode. Note that + * this is not exactly the normal (read-only) interpretation of a + * shared lock! Look closely at the interactions before allowing + * SInvalLock to be grabbed in shared mode for any other reason! * - * The routines later in this file that use shared mode are okay - * with this, because they aren't looking at the ProcState fields - * associated with SI message transfer; they only use the ProcState - * array as an easy way to find all the PROC structures. + * The routines later in this file that use shared mode are okay with + * this, because they aren't looking at the ProcState fields + * associated with SI message transfer; they only use the + * ProcState array as an easy way to find all the PROC structures. */ LWLockAcquire(SInvalLock, LW_SHARED); getResult = SIGetDataEntry(shmInvalBuffer, MyBackendId, &data); @@ -209,6 +209,7 @@ TransactionIdIsInProgress(TransactionId xid) if (pOffset != INVALID_OFFSET) { PROC *proc = (PROC *) MAKE_PTR(pOffset); + /* Fetch xid just once - see GetNewTransactionId */ TransactionId pxid = proc->xid; @@ -233,7 +234,7 @@ TransactionIdIsInProgress(TransactionId xid) * then only backends running in my own database are considered. * * This is used by VACUUM to decide which deleted tuples must be preserved - * in a table. allDbs = TRUE is needed for shared relations, but allDbs = + * in a table. allDbs = TRUE is needed for shared relations, but allDbs = * FALSE is sufficient for non-shared relations, since only backends in my * own database could ever see the tuples in them. * @@ -331,7 +332,7 @@ GetSnapshotData(bool serializable) /*-------------------- * Unfortunately, we have to call ReadNewTransactionId() after acquiring * SInvalLock above. It's not good because ReadNewTransactionId() does - * LWLockAcquire(XidGenLock), but *necessary*. We need to be sure that + * LWLockAcquire(XidGenLock), but *necessary*. We need to be sure that * no transactions exit the set of currently-running transactions * between the time we fetch xmax and the time we finish building our * snapshot. Otherwise we could have a situation like this: @@ -364,18 +365,19 @@ GetSnapshotData(bool serializable) if (pOffset != INVALID_OFFSET) { PROC *proc = (PROC *) MAKE_PTR(pOffset); + /* Fetch xid just once - see GetNewTransactionId */ TransactionId xid = proc->xid; /* * Ignore my own proc (dealt with my xid above), procs not - * running a transaction, and xacts started since we read - * the next transaction ID. There's no need to store XIDs - * above what we got from ReadNewTransactionId, since we'll - * treat them as running anyway. + * running a transaction, and xacts started since we read the + * next transaction ID. There's no need to store XIDs above + * what we got from ReadNewTransactionId, since we'll treat + * them as running anyway. */ if (proc == MyProc || - ! TransactionIdIsNormal(xid) || + !TransactionIdIsNormal(xid) || TransactionIdFollowsOrEquals(xid, snapshot->xmax)) continue; diff --git a/src/backend/storage/large_object/inv_api.c b/src/backend/storage/large_object/inv_api.c index 6072cd3945..c3efe50270 100644 --- a/src/backend/storage/large_object/inv_api.c +++ b/src/backend/storage/large_object/inv_api.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/large_object/inv_api.c,v 1.89 2001/08/10 20:52:24 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/large_object/inv_api.c,v 1.90 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -416,9 +416,10 @@ inv_write(LargeObjectDesc *obj_desc, char *buf, int nbytes) bool neednextpage; bytea *datafield; bool pfreeit; - struct { - struct varlena hdr; - char data[LOBLKSIZE]; + struct + { + struct varlena hdr; + char data[LOBLKSIZE]; } workbuf; char *workb = VARATT_DATA(&workbuf.hdr); HeapTuple newtup; @@ -462,7 +463,6 @@ inv_write(LargeObjectDesc *obj_desc, char *buf, int nbytes) while (nwritten < nbytes) { - /* * If possible, get next pre-existing page of the LO. We assume * the indexscan will deliver these in order --- but there may be @@ -491,7 +491,6 @@ inv_write(LargeObjectDesc *obj_desc, char *buf, int nbytes) */ if (olddata != NULL && olddata->pageno == pageno) { - /* * Update an existing page with fresh data. * @@ -558,7 +557,6 @@ inv_write(LargeObjectDesc *obj_desc, char *buf, int nbytes) } else { - /* * Write a brand new page. * diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c index 7a550ea346..e7a0c6e855 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.6 2001/09/30 00:45:47 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/deadlock.c,v 1.7 2001/10/25 05:49:42 momjian Exp $ * * Interface: * @@ -58,7 +58,6 @@ static bool TopoSort(LOCK *lock, EDGE *constraints, int nConstraints, #ifdef DEBUG_DEADLOCK static void PrintLockQueue(LOCK *lock, const char *info); - #endif @@ -499,7 +498,6 @@ FindLockCycleRecurse(PROC *checkProc, /* This proc soft-blocks checkProc */ if (FindLockCycleRecurse(proc, softEdges, nSoftEdges)) { - /* * Add this edge to the list of soft edges in the * cycle @@ -533,7 +531,6 @@ FindLockCycleRecurse(PROC *checkProc, /* This proc soft-blocks checkProc */ if (FindLockCycleRecurse(proc, softEdges, nSoftEdges)) { - /* * Add this edge to the list of soft edges in the * cycle @@ -759,5 +756,4 @@ PrintLockQueue(LOCK *lock, const char *info) printf("\n"); fflush(stdout); } - #endif diff --git a/src/backend/storage/lmgr/lmgr.c b/src/backend/storage/lmgr/lmgr.c index 659c3381e0..ef4fa5f849 100644 --- a/src/backend/storage/lmgr/lmgr.c +++ b/src/backend/storage/lmgr/lmgr.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/lmgr.c,v 1.51 2001/09/27 16:29:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/lmgr.c,v 1.52 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -332,9 +332,9 @@ void XactLockTableWait(TransactionId xid) { LOCKTAG tag; - TransactionId myxid = GetCurrentTransactionId(); + TransactionId myxid = GetCurrentTransactionId(); - Assert(! TransactionIdEquals(xid, myxid)); + Assert(!TransactionIdEquals(xid, myxid)); MemSet(&tag, 0, sizeof(tag)); tag.relId = XactLockTableId; diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c index 8c569710d0..a33b633d2d 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.100 2001/10/05 17:28:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/lock.c,v 1.101 2001/10/25 05:49:42 momjian Exp $ * * NOTES * Outside modules can create a lock table and acquire/release @@ -42,7 +42,7 @@ /* This configuration variable is used to set the lock table size */ -int max_locks_per_xact; /* set by guc.c */ +int max_locks_per_xact; /* set by guc.c */ #define NLOCKENTS(maxBackends) (max_locks_per_xact * (maxBackends)) @@ -54,15 +54,15 @@ static void LockCountMyLocks(SHMEM_OFFSET lockOffset, PROC *proc, static char *lock_mode_names[] = { - "INVALID", - "AccessShareLock", - "RowShareLock", - "RowExclusiveLock", - "ShareUpdateExclusiveLock", - "ShareLock", - "ShareRowExclusiveLock", - "ExclusiveLock", - "AccessExclusiveLock" + "INVALID", + "AccessShareLock", + "RowShareLock", + "RowExclusiveLock", + "ShareUpdateExclusiveLock", + "ShareLock", + "ShareRowExclusiveLock", + "ExclusiveLock", + "AccessExclusiveLock" }; @@ -96,10 +96,10 @@ inline static bool LOCK_DEBUG_ENABLED(const LOCK *lock) { return - (((LOCK_LOCKMETHOD(*lock) == DEFAULT_LOCKMETHOD && Trace_locks) - || (LOCK_LOCKMETHOD(*lock) == USER_LOCKMETHOD && Trace_userlocks)) - && (lock->tag.relId >= (Oid) Trace_lock_oidmin)) - || (Trace_lock_table && (lock->tag.relId == Trace_lock_table)); + (((LOCK_LOCKMETHOD(*lock) == DEFAULT_LOCKMETHOD && Trace_locks) + || (LOCK_LOCKMETHOD(*lock) == USER_LOCKMETHOD && Trace_userlocks)) + && (lock->tag.relId >= (Oid) Trace_lock_oidmin)) + || (Trace_lock_table && (lock->tag.relId == Trace_lock_table)); } @@ -132,7 +132,7 @@ HOLDER_PRINT(const char *where, const HOLDER *holderP) || (HOLDER_LOCKMETHOD(*holderP) == USER_LOCKMETHOD && Trace_userlocks)) && (((LOCK *) MAKE_PTR(holderP->tag.lock))->tag.relId >= (Oid) Trace_lock_oidmin)) || (Trace_lock_table && (((LOCK *) MAKE_PTR(holderP->tag.lock))->tag.relId == Trace_lock_table)) - ) + ) elog(DEBUG, "%s: holder(%lx) lock(%lx) tbl(%d) proc(%lx) xid(%u) hold(%d,%d,%d,%d,%d,%d,%d)=%d", where, MAKE_OFFSET(holderP), holderP->tag.lock, @@ -147,7 +147,6 @@ HOLDER_PRINT(const char *where, const HOLDER *holderP) #define LOCK_PRINT(where, lock, type) #define HOLDER_PRINT(where, holderP) - #endif /* not LOCK_DEBUG */ @@ -647,9 +646,11 @@ LockAcquire(LOCKMETHOD lockmethod, LOCKTAG *locktag, else { Assert(status == STATUS_FOUND); + /* * We can't acquire the lock immediately. If caller specified no - * blocking, remove the holder entry and return FALSE without waiting. + * blocking, remove the holder entry and return FALSE without + * waiting. */ if (dontWait) { @@ -911,7 +912,6 @@ WaitOnLock(LOCKMETHOD lockmethod, LOCKMODE lockmode, lock, holder) != STATUS_OK) { - /* * We failed as a result of a deadlock, see HandleDeadLock(). Quit * now. Removal of the holder and lock objects, if no longer @@ -1114,7 +1114,6 @@ LockRelease(LOCKMETHOD lockmethod, LOCKTAG *locktag, if (lock->nRequested == 0) { - /* * if there's no one waiting in the queue, we just released the * last lock on this object. Delete it from the lock table. @@ -1464,5 +1463,4 @@ DumpAllLocks(void) elog(DEBUG, "DumpAllLocks: holder->tag.lock = NULL"); } } - #endif /* LOCK_DEBUG */ diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c index 5fdcc11f59..7c268937c3 100644 --- a/src/backend/storage/lmgr/lwlock.c +++ b/src/backend/storage/lmgr/lwlock.c @@ -6,7 +6,7 @@ * Lightweight locks are intended primarily to provide mutual exclusion of * access to shared-memory data structures. Therefore, they offer both * exclusive and shared lock modes (to support read/write and read-only - * access to a shared object). There are few other frammishes. User-level + * access to a shared object). There are few other frammishes. User-level * locking should be done with the full lock manager --- which depends on * an LWLock to protect its shared state. * @@ -15,7 +15,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/lwlock.c,v 1.1 2001/09/29 04:02:24 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/lwlock.c,v 1.2 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -43,8 +43,9 @@ typedef struct LWLock * the array. */ static LWLock *LWLockArray = NULL; + /* shared counter for dynamic allocation of LWLockIds */ -static int *LWLockCounter; +static int *LWLockCounter; /* @@ -55,8 +56,8 @@ static int *LWLockCounter; */ #define MAX_SIMUL_LWLOCKS 100 -static int num_held_lwlocks = 0; -static LWLockId held_lwlocks[MAX_SIMUL_LWLOCKS]; +static int num_held_lwlocks = 0; +static LWLockId held_lwlocks[MAX_SIMUL_LWLOCKS]; #ifdef LOCK_DEBUG @@ -71,9 +72,9 @@ PRINT_LWDEBUG(const char *where, LWLockId lockid, const LWLock *lock) (int) lock->exclusive, lock->shared, lock->head); } -#else /* not LOCK_DEBUG */ +#else /* not LOCK_DEBUG */ #define PRINT_LWDEBUG(a,b,c) -#endif /* LOCK_DEBUG */ +#endif /* LOCK_DEBUG */ /* @@ -82,13 +83,13 @@ PRINT_LWDEBUG(const char *where, LWLockId lockid, const LWLock *lock) int NumLWLocks(void) { - int numLocks; + int numLocks; /* - * Possibly this logic should be spread out among the affected modules, - * the same way that shmem space estimation is done. But for now, - * there are few enough users of LWLocks that we can get away with - * just keeping the knowledge here. + * Possibly this logic should be spread out among the affected + * modules, the same way that shmem space estimation is done. But for + * now, there are few enough users of LWLocks that we can get away + * with just keeping the knowledge here. */ /* Predefined LWLocks */ @@ -112,8 +113,8 @@ NumLWLocks(void) int LWLockShmemSize(void) { - int numLocks = NumLWLocks(); - uint32 spaceLocks; + int numLocks = NumLWLocks(); + uint32 spaceLocks; /* Allocate the LWLocks plus space for shared allocation counter. */ spaceLocks = numLocks * sizeof(LWLock) + 2 * sizeof(int); @@ -129,10 +130,10 @@ LWLockShmemSize(void) void CreateLWLocks(void) { - int numLocks = NumLWLocks(); - uint32 spaceLocks = LWLockShmemSize(); - LWLock *lock; - int id; + int numLocks = NumLWLocks(); + uint32 spaceLocks = LWLockShmemSize(); + LWLock *lock; + int id; /* Allocate space */ LWLockArray = (LWLock *) ShmemAlloc(spaceLocks); @@ -184,8 +185,8 @@ LWLockAssign(void) void LWLockAcquire(LWLockId lockid, LWLockMode mode) { - LWLock *lock = LWLockArray + lockid; - bool mustwait; + LWLock *lock = LWLockArray + lockid; + bool mustwait; PRINT_LWDEBUG("LWLockAcquire", lockid, lock); @@ -229,13 +230,13 @@ LWLockAcquire(LWLockId lockid, LWLockMode mode) if (mustwait) { /* Add myself to wait queue */ - PROC *proc = MyProc; - int extraWaits = 0; + PROC *proc = MyProc; + int extraWaits = 0; /* - * If we don't have a PROC structure, there's no way to wait. - * This should never occur, since MyProc should only be null - * during shared memory initialization. + * If we don't have a PROC structure, there's no way to wait. This + * should never occur, since MyProc should only be null during + * shared memory initialization. */ if (proc == NULL) elog(FATAL, "LWLockAcquire: can't wait without a PROC structure"); @@ -256,13 +257,13 @@ LWLockAcquire(LWLockId lockid, LWLockMode mode) * Wait until awakened. * * Since we share the process wait semaphore with the regular lock - * manager and ProcWaitForSignal, and we may need to acquire an LWLock - * while one of those is pending, it is possible that we get awakened - * for a reason other than being granted the LWLock. If so, loop back - * and wait again. Once we've gotten the lock, re-increment the sema - * by the number of additional signals received, so that the lock - * manager or signal manager will see the received signal when it - * next waits. + * manager and ProcWaitForSignal, and we may need to acquire an + * LWLock while one of those is pending, it is possible that we + * get awakened for a reason other than being granted the LWLock. + * If so, loop back and wait again. Once we've gotten the lock, + * re-increment the sema by the number of additional signals + * received, so that the lock manager or signal manager will see + * the received signal when it next waits. */ for (;;) { @@ -272,6 +273,7 @@ LWLockAcquire(LWLockId lockid, LWLockMode mode) break; extraWaits++; } + /* * The awakener already updated the lock struct's state, so we * don't need to do anything more to it. Just need to fix the @@ -301,8 +303,8 @@ LWLockAcquire(LWLockId lockid, LWLockMode mode) bool LWLockConditionalAcquire(LWLockId lockid, LWLockMode mode) { - LWLock *lock = LWLockArray + lockid; - bool mustwait; + LWLock *lock = LWLockArray + lockid; + bool mustwait; PRINT_LWDEBUG("LWLockConditionalAcquire", lockid, lock); @@ -367,18 +369,18 @@ LWLockConditionalAcquire(LWLockId lockid, LWLockMode mode) void LWLockRelease(LWLockId lockid) { - LWLock *lock = LWLockArray + lockid; - PROC *head; - PROC *proc; - int i; + LWLock *lock = LWLockArray + lockid; + PROC *head; + PROC *proc; + int i; PRINT_LWDEBUG("LWLockRelease", lockid, lock); /* - * Remove lock from list of locks held. Usually, but not always, - * it will be the latest-acquired lock; so search array backwards. + * Remove lock from list of locks held. Usually, but not always, it + * will be the latest-acquired lock; so search array backwards. */ - for (i = num_held_lwlocks; --i >= 0; ) + for (i = num_held_lwlocks; --i >= 0;) { if (lockid == held_lwlocks[i]) break; @@ -387,7 +389,7 @@ LWLockRelease(LWLockId lockid) elog(ERROR, "LWLockRelease: lock %d is not held", (int) lockid); num_held_lwlocks--; for (; i < num_held_lwlocks; i++) - held_lwlocks[i] = held_lwlocks[i+1]; + held_lwlocks[i] = held_lwlocks[i + 1]; /* Acquire mutex. Time spent holding mutex should be short! */ SpinLockAcquire_NoHoldoff(&lock->mutex); @@ -402,8 +404,8 @@ LWLockRelease(LWLockId lockid) } /* - * See if I need to awaken any waiters. If I released a non-last shared - * hold, there cannot be anything to do. + * See if I need to awaken any waiters. If I released a non-last + * shared hold, there cannot be anything to do. */ head = lock->head; if (head != NULL) @@ -411,14 +413,12 @@ LWLockRelease(LWLockId lockid) if (lock->exclusive == 0 && lock->shared == 0) { /* - * Remove the to-be-awakened PROCs from the queue, and update the - * lock state to show them as holding the lock. + * Remove the to-be-awakened PROCs from the queue, and update + * the lock state to show them as holding the lock. */ proc = head; if (proc->lwExclusive) - { lock->exclusive++; - } else { lock->shared++; @@ -465,10 +465,10 @@ LWLockRelease(LWLockId lockid) /* * LWLockReleaseAll - release all currently-held locks * - * Used to clean up after elog(ERROR). An important difference between this + * Used to clean up after elog(ERROR). An important difference between this * function and retail LWLockRelease calls is that InterruptHoldoffCount is * unchanged by this operation. This is necessary since InterruptHoldoffCount - * has been set to an appropriate level earlier in error recovery. We could + * has been set to an appropriate level earlier in error recovery. We could * decrement it below zero if we allow it to drop for each released lock! */ void @@ -478,6 +478,6 @@ LWLockReleaseAll(void) { HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */ - LWLockRelease(held_lwlocks[num_held_lwlocks-1]); + LWLockRelease(held_lwlocks[num_held_lwlocks - 1]); } } diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 5b88e22bd9..503312b53d 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.112 2001/10/01 18:16:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/proc.c,v 1.113 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -127,8 +127,8 @@ InitProcGlobal(int maxBackends) * besides those used for regular backends. */ Assert(maxBackends > 0); - semMapEntries = PROC_SEM_MAP_ENTRIES(maxBackends+1); - procGlobalSize = sizeof(PROC_HDR) + (semMapEntries-1) * sizeof(SEM_MAP_ENTRY); + semMapEntries = PROC_SEM_MAP_ENTRIES(maxBackends + 1); + procGlobalSize = sizeof(PROC_HDR) + (semMapEntries - 1) *sizeof(SEM_MAP_ENTRY); /* Create or attach to the ProcGlobal shared structure */ ProcGlobal = (PROC_HDR *) @@ -182,10 +182,10 @@ InitProcGlobal(int maxBackends) */ DummyProc = (PROC *) ShmemAlloc(sizeof(PROC)); DummyProc->pid = 0; /* marks DummyProc as not in use */ - i = semMapEntries-1; - ProcGlobal->procSemMap[i].freeSemMap |= 1 << (PROC_NSEMS_PER_SET-1); + i = semMapEntries - 1; + ProcGlobal->procSemMap[i].freeSemMap |= 1 << (PROC_NSEMS_PER_SET - 1); DummyProc->sem.semId = ProcGlobal->procSemMap[i].procSemId; - DummyProc->sem.semNum = PROC_NSEMS_PER_SET-1; + DummyProc->sem.semNum = PROC_NSEMS_PER_SET - 1; /* Create ProcStructLock spinlock, too */ ProcStructLock = (slock_t *) ShmemAlloc(sizeof(slock_t)); @@ -199,11 +199,11 @@ InitProcGlobal(int maxBackends) void InitProcess(void) { - SHMEM_OFFSET myOffset; + SHMEM_OFFSET myOffset; /* - * ProcGlobal should be set by a previous call to InitProcGlobal - * (if we are a backend, we inherit this by fork() from the postmaster). + * ProcGlobal should be set by a previous call to InitProcGlobal (if + * we are a backend, we inherit this by fork() from the postmaster). */ if (ProcGlobal == NULL) elog(STOP, "InitProcess: Proc Header uninitialized"); @@ -260,8 +260,8 @@ InitProcess(void) on_shmem_exit(ProcKill, 0); /* - * Set up a wait-semaphore for the proc. (We rely on ProcKill to clean - * up MyProc if this fails.) + * Set up a wait-semaphore for the proc. (We rely on ProcKill to + * clean up MyProc if this fails.) */ if (IsUnderPostmaster) ProcGetNewSemIdAndNum(&MyProc->sem.semId, &MyProc->sem.semNum); @@ -291,8 +291,8 @@ void InitDummyProcess(void) { /* - * ProcGlobal should be set by a previous call to InitProcGlobal - * (we inherit this by fork() from the postmaster). + * ProcGlobal should be set by a previous call to InitProcGlobal (we + * inherit this by fork() from the postmaster). */ if (ProcGlobal == NULL || DummyProc == NULL) elog(STOP, "InitDummyProcess: Proc Header uninitialized"); @@ -309,8 +309,8 @@ InitDummyProcess(void) MyProc = DummyProc; /* - * Initialize all fields of MyProc, except MyProc->sem which was - * set up by InitProcGlobal. + * Initialize all fields of MyProc, except MyProc->sem which was set + * up by InitProcGlobal. */ MyProc->pid = MyProcPid; /* marks DummyProc as in use by me */ SHMQueueElemInit(&(MyProc->links)); @@ -471,7 +471,7 @@ ProcKill(void) /* * DummyProcKill() -- Cut-down version of ProcKill for dummy (checkpoint) - * processes. The PROC and sema are not released, only marked + * processes. The PROC and sema are not released, only marked * as not-in-use. */ static void @@ -520,7 +520,6 @@ ProcQueueAlloc(char *name) ProcQueueInit(queue); return queue; } - #endif /* @@ -599,10 +598,11 @@ ProcSleep(LOCKMETHODTABLE *lockMethodTable, if (lockctl->conflictTab[lockmode] & proc->heldLocks) { /* - * Yes, so we have a deadlock. Easiest way to clean 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. + * Yes, so we have a deadlock. Easiest way to clean + * 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. */ early_deadlock = true; break; @@ -653,12 +653,12 @@ ProcSleep(LOCKMETHODTABLE *lockMethodTable, MyProc->waitHolder = holder; MyProc->waitLockMode = lockmode; - MyProc->errType = STATUS_OK; /* initialize result for success */ + MyProc->errType = STATUS_OK; /* initialize result for success */ /* * If we detected deadlock, give up without waiting. This must agree - * with HandleDeadLock's recovery code, except that we shouldn't release - * the semaphore since we haven't tried to lock it yet. + * with HandleDeadLock's recovery code, except that we shouldn't + * release the semaphore since we haven't tried to lock it yet. */ if (early_deadlock) { @@ -689,7 +689,7 @@ ProcSleep(LOCKMETHODTABLE *lockMethodTable, * By delaying the check until we've waited for a bit, we can avoid * running the rather expensive deadlock-check code in most cases. */ - if (! enable_sigalrm_interrupt(DeadlockTimeout)) + if (!enable_sigalrm_interrupt(DeadlockTimeout)) elog(FATAL, "ProcSleep: Unable to set timer for process wakeup"); /* @@ -711,7 +711,7 @@ ProcSleep(LOCKMETHODTABLE *lockMethodTable, /* * Disable the timer, if it's still running */ - if (! disable_sigalrm_interrupt()) + if (!disable_sigalrm_interrupt()) elog(FATAL, "ProcSleep: Unable to disable timer for process wakeup"); /* @@ -821,7 +821,6 @@ ProcLockWakeup(LOCKMETHODTABLE *lockMethodTable, LOCK *lock) } else { - /* * Cannot wake this guy. Remember his request for later * checks. @@ -851,8 +850,8 @@ HandleDeadLock(SIGNAL_ARGS) * Acquire locktable lock. Note that the SIGALRM interrupt had better * not be enabled anywhere that this process itself holds the * locktable lock, else this will wait forever. Also note that - * LWLockAcquire creates a critical section, so that this - * routine cannot be interrupted by cancel/die interrupts. + * LWLockAcquire creates a critical section, so that this routine + * cannot be interrupted by cancel/die interrupts. */ LWLockAcquire(LockMgrLock, LW_EXCLUSIVE); @@ -960,7 +959,7 @@ ProcCancelWaitForSignal(void) void ProcSendSignal(BackendId procId) { - PROC *proc = BackendIdGetProc(procId); + PROC *proc = BackendIdGetProc(procId); if (proc != NULL) IpcSemaphoreUnlock(proc->sem.semId, proc->sem.semNum); @@ -976,7 +975,7 @@ ProcSendSignal(BackendId procId) /* * Enable the SIGALRM interrupt to fire after the specified delay * - * Delay is given in milliseconds. Caller should be sure a SIGALRM + * Delay is given in milliseconds. Caller should be sure a SIGALRM * signal handler is installed before this is called. * * Returns TRUE if okay, FALSE on failure. @@ -997,7 +996,7 @@ enable_sigalrm_interrupt(int delayms) /* BeOS doesn't have setitimer, but has set_alarm */ bigtime_t time_interval; - time_interval = delayms * 1000; /* usecs */ + time_interval = delayms * 1000; /* usecs */ if (set_alarm(time_interval, B_ONE_SHOT_RELATIVE_ALARM) < 0) return false; #endif @@ -1044,7 +1043,7 @@ ProcGetNewSemIdAndNum(IpcSemaphoreId *semId, int *semNum) { int i; int semMapEntries = ProcGlobal->semMapEntries; - SEM_MAP_ENTRY *procSemMap = ProcGlobal->procSemMap; + SEM_MAP_ENTRY *procSemMap = ProcGlobal->procSemMap; int32 fullmask = (1 << PROC_NSEMS_PER_SET) - 1; SpinLockAcquire(ProcStructLock); @@ -1080,10 +1079,11 @@ ProcGetNewSemIdAndNum(IpcSemaphoreId *semId, int *semNum) SpinLockRelease(ProcStructLock); /* - * If we reach here, all the semaphores are in use. This is one of the - * possible places to detect "too many backends", so give the standard - * error message. (Whether we detect it here or in sinval.c depends on - * whether MaxBackends is a multiple of PROC_NSEMS_PER_SET.) + * If we reach here, all the semaphores are in use. This is one of + * the possible places to detect "too many backends", so give the + * standard error message. (Whether we detect it here or in sinval.c + * depends on whether MaxBackends is a multiple of + * PROC_NSEMS_PER_SET.) */ elog(FATAL, "Sorry, too many clients already"); } diff --git a/src/backend/storage/lmgr/s_lock.c b/src/backend/storage/lmgr/s_lock.c index 055c809cf8..84934b3b02 100644 --- a/src/backend/storage/lmgr/s_lock.c +++ b/src/backend/storage/lmgr/s_lock.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/s_lock.c,v 1.2 2001/09/29 04:02:25 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/s_lock.c,v 1.3 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -48,13 +48,14 @@ s_lock(volatile slock_t *lock, const char *file, int line) struct timeval delay; /* - * We loop tightly for awhile, then delay using select() and try again. - * Preferably, "awhile" should be a small multiple of the maximum time - * we expect a spinlock to be held. 100 iterations seems about right. + * We loop tightly for awhile, then delay using select() and try + * again. Preferably, "awhile" should be a small multiple of the + * maximum time we expect a spinlock to be held. 100 iterations seems + * about right. * * We use a 10 millisec select delay because that is the lower limit on - * many platforms. The timeout is figured on this delay only, and so the - * nominal 1 minute is a lower bound. + * many platforms. The timeout is figured on this delay only, and so + * the nominal 1 minute is a lower bound. */ #define SPINS_PER_DELAY 100 #define DELAY_MSEC 10 @@ -108,7 +109,6 @@ _success: \n\ rts \n\ "); } - #endif /* __m68k__ */ #if defined(__APPLE__) && defined(__ppc__) @@ -138,7 +138,6 @@ success: \n\ blr \n\ "); } - #endif /* __APPLE__ && __ppc__ */ #if defined(__powerpc__) @@ -163,7 +162,6 @@ success: \n\ blr \n\ "); } - #endif /* __powerpc__ */ #if defined(__mips__) && !defined(__sgi) @@ -171,7 +169,7 @@ static void tas_dummy() { __asm__ __volatile__( - "\ + "\ .global tas \n\ tas: \n\ .frame $sp, 0, $31 \n\ @@ -188,10 +186,9 @@ fail: \n\ j $31 \n\ "); } - #endif /* __mips__ && !__sgi */ -#else /* not __GNUC__ */ +#else /* not __GNUC__ */ /*************************************************************************** * All non gcc */ @@ -220,7 +217,6 @@ tas_dummy() /* really means: extern int tas(slock_t asm(" rts"); asm(" .data"); } - #endif /* sun3 */ @@ -244,7 +240,6 @@ tas_dummy() /* really means: extern int tas(slock_t asm("retl"); asm("nop"); } - #endif /* NEED_SPARC_TAS_ASM */ @@ -255,7 +250,6 @@ tas_dummy() /* really means: extern int tas(slock_t #endif /* NEED_I386_TAS_ASM */ - #endif /* not __GNUC__ */ @@ -298,5 +292,4 @@ main() exit(3); } - #endif /* S_LOCK_TEST */ diff --git a/src/backend/storage/lmgr/spin.c b/src/backend/storage/lmgr/spin.c index 6ace9cc11a..59a7b4414c 100644 --- a/src/backend/storage/lmgr/spin.c +++ b/src/backend/storage/lmgr/spin.c @@ -5,8 +5,8 @@ * * * For machines that have test-and-set (TAS) instructions, s_lock.h/.c - * define the spinlock implementation. This file contains only a stub - * implementation for spinlocks using SysV semaphores. The semaphore method + * define the spinlock implementation. This file contains only a stub + * implementation for spinlocks using SysV semaphores. The semaphore method * is too slow to be very useful :-( * * @@ -15,7 +15,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/spin.c,v 1.4 2001/10/01 18:16:35 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/spin.c,v 1.5 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -92,8 +92,8 @@ CreateSpinlocks(void) { /* * Compute number of spinlocks needed. It would be cleaner to - * distribute this logic into the affected modules, - * similar to the way shmem space estimation is handled. + * distribute this logic into the affected modules, similar to the + * way shmem space estimation is handled. * * For now, though, we just need a few spinlocks (10 should be * plenty) plus one for each LWLock. @@ -186,5 +186,4 @@ tas_sema(volatile slock_t *lock) /* Note that TAS macros return 0 if *success* */ return !IpcSemaphoreTryLock(lock->semId, lock->sem); } - #endif /* !HAS_TEST_AND_SET */ diff --git a/src/backend/storage/page/bufpage.c b/src/backend/storage/page/bufpage.c index 038ec65ac7..3fc1958b53 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.38 2001/10/23 02:20:15 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/page/bufpage.c,v 1.39 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -125,7 +125,6 @@ PageAddItem(Page page, } else { - /* * Don't actually do the shuffle till we've checked free * space! @@ -264,7 +263,7 @@ itemoffcompare(const void *itemidp1, const void *itemidp2) * It doesn't remove unused line pointers! Please don't change this. * This routine is usable for heap pages only. * - * Returns number of unused line pointers on page. If "unused" is not NULL + * Returns number of unused line pointers on page. If "unused" is not NULL * then the unused[] array is filled with indexes of unused line pointers. */ int @@ -283,11 +282,11 @@ PageRepairFragmentation(Page page, OffsetNumber *unused) Offset upper; /* - * It's worth the trouble to be more paranoid here than in most places, - * because we are about to reshuffle data in (what is usually) a shared - * disk buffer. If we aren't careful then corrupted pointers, lengths, - * etc could cause us to clobber adjacent disk buffers, spreading the - * data loss further. So, check everything. + * It's worth the trouble to be more paranoid here than in most + * places, because we are about to reshuffle data in (what is usually) + * a shared disk buffer. If we aren't careful then corrupted + * pointers, lengths, etc could cause us to clobber adjacent disk + * buffers, spreading the data loss further. So, check everything. */ if (pd_lower < (sizeof(PageHeaderData) - sizeof(ItemIdData)) || pd_lower > pd_upper || @@ -344,7 +343,7 @@ PageRepairFragmentation(Page page, OffsetNumber *unused) } else { - (*lp).lp_len = 0; /* indicate unused & deallocated */ + (*lp).lp_len = 0; /* indicate unused & deallocated */ } } @@ -390,7 +389,7 @@ PageGetFreeSpace(Page page) if (space < sizeof(ItemIdData)) return 0; - space -= sizeof(ItemIdData); /* XXX not always appropriate */ + space -= sizeof(ItemIdData); /* XXX not always appropriate */ return space; } diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c index 424b667c63..c8fd782988 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.87 2001/08/24 14:07:49 petere Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/smgr/md.c,v 1.88 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -58,7 +58,7 @@ typedef struct _MdfdVec int mdfd_nextFree; /* link to next freelist member, if free */ #ifndef LET_OS_MANAGE_FILESIZE - struct _MdfdVec *mdfd_chain;/* for large relations */ + struct _MdfdVec *mdfd_chain; /* for large relations */ #endif } MdfdVec; @@ -194,7 +194,7 @@ mdunlink(RelFileNode rnode) if (status == SM_SUCCESS) { char *segpath = (char *) palloc(strlen(path) + 12); - BlockNumber segno; + BlockNumber segno; for (segno = 1;; segno++) { @@ -258,11 +258,11 @@ mdextend(Relation reln, BlockNumber blocknum, char *buffer) /* * Note: because caller obtained blocknum by calling mdnblocks, which * did a seek(SEEK_END), this seek is often redundant and will be - * optimized away by fd.c. It's not redundant, however, if there is a - * partial page at the end of the file. In that case we want to try to - * overwrite the partial page with a full page. It's also not redundant - * if bufmgr.c had to dump another buffer of the same file to make room - * for the new page's buffer. + * optimized away by fd.c. It's not redundant, however, if there is a + * partial page at the end of the file. In that case we want to try + * to overwrite the partial page with a full page. It's also not + * redundant if bufmgr.c had to dump another buffer of the same file + * to make room for the new page's buffer. */ if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos) return SM_FAIL; @@ -271,7 +271,7 @@ mdextend(Relation reln, BlockNumber blocknum, char *buffer) { if (nbytes > 0) { - int save_errno = errno; + int save_errno = errno; /* Remove the partially-written page */ FileTruncate(v->mdfd_vfd, seekpos); @@ -309,7 +309,6 @@ mdopen(Relation reln) if (fd < 0) { - /* * During bootstrap, there are cases where a system relation will * be accessed (by internal backend processes) before the @@ -383,7 +382,6 @@ mdclose_fd(int fd) /* if not closed already */ if (v->mdfd_vfd >= 0) { - /* * We sync the file descriptor so that we don't need to reopen * it at transaction commit to force changes to disk. (This @@ -406,7 +404,6 @@ mdclose_fd(int fd) { if (v->mdfd_vfd >= 0) { - /* * We sync the file descriptor so that we don't need to reopen * it at transaction commit to force changes to disk. (This @@ -455,8 +452,8 @@ mdread(Relation reln, BlockNumber blocknum, char *buffer) if ((nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ) { /* - * If we are at EOF, return zeroes without complaining. - * (XXX Is this still necessary/a good idea??) + * If we are at EOF, return zeroes without complaining. (XXX Is + * this still necessary/a good idea??) */ if (nbytes == 0 || (nbytes > 0 && mdnblocks(reln) == blocknum)) @@ -664,9 +661,10 @@ mdnblocks(Relation reln) { int fd; MdfdVec *v; + #ifndef LET_OS_MANAGE_FILESIZE - BlockNumber nblocks; - BlockNumber segno; + BlockNumber nblocks; + BlockNumber segno; #endif fd = _mdfd_getrelnfd(reln); @@ -681,6 +679,7 @@ mdnblocks(Relation reln) elog(FATAL, "segment too big in mdnblocks!"); if (nblocks < ((BlockNumber) RELSEG_SIZE)) return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks; + /* * If segment is exactly RELSEG_SIZE, advance to next one. */ @@ -689,11 +688,11 @@ mdnblocks(Relation reln) if (v->mdfd_chain == (MdfdVec *) NULL) { /* - * Because we pass O_CREAT, we will create the next - * segment (with zero length) immediately, if the last - * segment is of length REL_SEGSIZE. This is unnecessary - * but harmless, and testing for the case would take more - * cycles than it seems worth. + * Because we pass O_CREAT, we will create the next segment + * (with zero length) immediately, if the last segment is of + * length REL_SEGSIZE. This is unnecessary but harmless, and + * testing for the case would take more cycles than it seems + * worth. */ v->mdfd_chain = _mdfd_openseg(reln, segno, O_CREAT); if (v->mdfd_chain == (MdfdVec *) NULL) @@ -718,9 +717,10 @@ mdtruncate(Relation reln, BlockNumber nblocks) { int fd; MdfdVec *v; - BlockNumber curnblk; + BlockNumber curnblk; + #ifndef LET_OS_MANAGE_FILESIZE - BlockNumber priorblocks; + BlockNumber priorblocks; #endif /* @@ -729,7 +729,7 @@ mdtruncate(Relation reln, BlockNumber nblocks) */ curnblk = mdnblocks(reln); if (nblocks > curnblk) - return InvalidBlockNumber; /* bogus request */ + return InvalidBlockNumber; /* bogus request */ if (nblocks == curnblk) return nblocks; /* no work */ @@ -768,7 +768,7 @@ mdtruncate(Relation reln, BlockNumber nblocks) * truncate the K+1st segment to 0 length but keep it. This is * mainly so that the right thing happens if nblocks==0. */ - BlockNumber lastsegblocks = nblocks - priorblocks; + BlockNumber lastsegblocks = nblocks - priorblocks; if (FileTruncate(v->mdfd_vfd, lastsegblocks * BLCKSZ) < 0) return InvalidBlockNumber; @@ -838,7 +838,6 @@ mdcommit() int mdabort() { - /* * We don't actually have to do anything here. fd.c will discard * fsync-needed bits in its AtEOXact_Files() routine. @@ -1004,9 +1003,10 @@ _mdfd_getseg(Relation reln, BlockNumber blkno) { MdfdVec *v; int fd; + #ifndef LET_OS_MANAGE_FILESIZE - BlockNumber segno; - BlockNumber i; + BlockNumber segno; + BlockNumber i; #endif fd = _mdfd_getrelnfd(reln); @@ -1019,7 +1019,6 @@ _mdfd_getseg(Relation reln, BlockNumber blkno) if (v->mdfd_chain == (MdfdVec *) NULL) { - /* * We will create the next segment only if the target block is * within it. This prevents Sorcerer's Apprentice syndrome if @@ -1063,8 +1062,9 @@ _mdfd_blind_getseg(RelFileNode rnode, BlockNumber blkno) { char *path; int fd; + #ifndef LET_OS_MANAGE_FILESIZE - BlockNumber segno; + BlockNumber segno; #endif path = relpath(rnode); diff --git a/src/backend/storage/smgr/mm.c b/src/backend/storage/smgr/mm.c index fcb282f916..789083fba2 100644 --- a/src/backend/storage/smgr/mm.c +++ b/src/backend/storage/smgr/mm.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/smgr/Attic/mm.c,v 1.27 2001/10/05 17:28:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/smgr/Attic/mm.c,v 1.28 2001/10/25 05:49:42 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -481,7 +481,7 @@ mmnblocks(Relation reln) { MMRelTag rtag; MMRelHashEntry *rentry; - BlockNumber nblocks; + BlockNumber nblocks; if (reln->rd_rel->relisshared) rtag.mmrt_dbid = (Oid) 0; @@ -561,5 +561,4 @@ MMShmemSize() return size; } - #endif /* STABLE_MEMORY_STORAGE */ diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 555b666faa..f4df40bf40 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -11,7 +11,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/storage/smgr/smgr.c,v 1.53 2001/09/29 04:02:25 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/storage/smgr/smgr.c,v 1.54 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -33,21 +33,21 @@ typedef struct f_smgr int (*smgr_create) (Relation reln); int (*smgr_unlink) (RelFileNode rnode); int (*smgr_extend) (Relation reln, BlockNumber blocknum, - char *buffer); + char *buffer); int (*smgr_open) (Relation reln); int (*smgr_close) (Relation reln); int (*smgr_read) (Relation reln, BlockNumber blocknum, - char *buffer); + char *buffer); int (*smgr_write) (Relation reln, BlockNumber blocknum, - char *buffer); + char *buffer); int (*smgr_flush) (Relation reln, BlockNumber blocknum, - char *buffer); + char *buffer); int (*smgr_blindwrt) (RelFileNode rnode, BlockNumber blkno, - char *buffer, bool dofsync); + char *buffer, bool dofsync); int (*smgr_markdirty) (Relation reln, BlockNumber blkno); int (*smgr_blindmarkdirty) (RelFileNode, BlockNumber blkno); - BlockNumber (*smgr_nblocks) (Relation reln); - BlockNumber (*smgr_truncate) (Relation reln, BlockNumber nblocks); + BlockNumber (*smgr_nblocks) (Relation reln); + BlockNumber (*smgr_truncate) (Relation reln, BlockNumber nblocks); int (*smgr_commit) (void); /* may be NULL */ int (*smgr_abort) (void); /* may be NULL */ int (*smgr_sync) (void); @@ -71,7 +71,6 @@ static f_smgr smgrsw[] = { {mminit, mmshutdown, mmcreate, mmunlink, mmextend, mmopen, mmclose, mmread, mmwrite, mmflush, mmblindwrt, mmmarkdirty, mmblindmarkdirty, mmnblocks, NULL, mmcommit, mmabort}, - #endif }; @@ -89,7 +88,6 @@ static bool smgrwo[] = { false, /* main memory */ #endif }; - #endif static int NSmgr = lengthof(smgrsw); @@ -438,9 +436,10 @@ smgrblindmarkdirty(int16 which, BlockNumber smgrnblocks(int16 which, Relation reln) { - BlockNumber nblocks; + BlockNumber nblocks; nblocks = (*(smgrsw[which].smgr_nblocks)) (reln); + /* * NOTE: if a relation ever did grow to 2^32-1 blocks, this code would * fail --- but that's a good thing, because it would stop us from @@ -464,15 +463,15 @@ smgrnblocks(int16 which, Relation reln) BlockNumber smgrtruncate(int16 which, Relation reln, BlockNumber nblocks) { - BlockNumber newblks; + BlockNumber newblks; newblks = nblocks; if (smgrsw[which].smgr_truncate) { /* * Tell the free space map to forget anything it may have stored - * for the about-to-be-deleted blocks. We want to be sure it won't - * return bogus block numbers later on. + * for the about-to-be-deleted blocks. We want to be sure it + * won't return bogus block numbers later on. */ MultiRecordFreeSpace(&reln->rd_node, nblocks, MaxBlockNumber, @@ -601,7 +600,6 @@ smgriswo(int16 smgrno) return smgrwo[smgrno]; } - #endif void diff --git a/src/backend/tcop/dest.c b/src/backend/tcop/dest.c index 0e9cdd2213..61b1b55821 100644 --- a/src/backend/tcop/dest.c +++ b/src/backend/tcop/dest.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/tcop/dest.c,v 1.44 2001/03/22 06:16:17 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/dest.c,v 1.45 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -173,7 +173,7 @@ DestToFunction(CommandDest dest) { switch (dest) { - case Remote: + case Remote: return printtup_create_DR(false); case RemoteInternal: @@ -272,13 +272,13 @@ NullCommand(CommandDest dest) { switch (dest) { - case RemoteInternal: - case Remote: + case RemoteInternal: + case Remote: /* * tell the fe that we saw an empty query string */ - pq_putbytes("I", 2);/* note we send I and \0 */ + pq_putbytes("I", 2); /* note we send I and \0 */ break; case Debug: @@ -303,8 +303,8 @@ ReadyForQuery(CommandDest dest) { switch (dest) { - case RemoteInternal: - case Remote: + case RemoteInternal: + case Remote: if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2) pq_putbytes("Z", 1); /* Flush output at end of cycle in any case. */ @@ -323,7 +323,7 @@ UpdateCommandInfo(int operation, Oid lastoid, uint32 tuples) { switch (operation) { - case CMD_INSERT: + case CMD_INSERT: if (tuples > 1) lastoid = InvalidOid; sprintf(CommandInfo, " %u %u", lastoid, tuples); diff --git a/src/backend/tcop/fastpath.c b/src/backend/tcop/fastpath.c index ccb36b20c1..c710d2c3d4 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.49 2001/06/01 15:45:42 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/fastpath.c,v 1.50 2001/10/25 05:49:43 momjian Exp $ * * NOTES * This cruft is the server side of PQfn. @@ -120,8 +120,8 @@ SendFunctionResult(Datum retval,/* actual return value */ * each fastpath call as a separate transaction command, and so the * cached data could never actually have been reused. If it had worked * as intended, it would have had problems anyway with dangling references - * in the FmgrInfo struct. So, forget about caching and just repeat the - * syscache fetches on each usage. They're not *that* expensive. + * in the FmgrInfo struct. So, forget about caching and just repeat the + * syscache fetches on each usage. They're not *that* expensive. */ struct fp_info { @@ -157,7 +157,8 @@ fetch_fp_info(Oid func_id, struct fp_info * fip) * correct value until we are about to return with a good struct * fp_info, since we can be interrupted (i.e., with an elog(ERROR, * ...)) at any time. [No longer really an issue since we don't save - * the struct fp_info across transactions anymore, but keep it anyway.] + * the struct fp_info across transactions anymore, but keep it + * anyway.] */ MemSet((char *) fip, 0, sizeof(struct fp_info)); fip->funcid = InvalidOid; @@ -260,8 +261,8 @@ HandleFunctionRequest(void) return EOF; /* - * There used to be a lame attempt at caching lookup info here. - * Now we just do the lookups on every call. + * There used to be a lame attempt at caching lookup info here. Now we + * just do the lookups on every call. */ fip = &my_fp; fetch_fp_info(fid, fip); diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index ce7ccb2af5..e839e47f1c 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.238 2001/10/21 03:25:35 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.239 2001/10/25 05:49:43 momjian Exp $ * * NOTES * this is the "main" module of the postgres backend and @@ -72,7 +72,7 @@ extern int optind; extern char *optarg; -char *debug_query_string; /* used by pgmonitor */ +char *debug_query_string; /* used by pgmonitor */ /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */ CommandDest whereToSendOutput = Debug; @@ -99,7 +99,6 @@ int UseNewLine = 1; /* Use newlines query delimiters (the #else int UseNewLine = 0; /* Use EOF as query delimiters */ - #endif /* TCOP_DONTUSENEWLINE */ /* @@ -163,7 +162,6 @@ InteractiveBackend(StringInfo inBuf) { if (UseNewLine) { - /* * if we are using \n as a delimiter, then read characters * until the \n. @@ -199,7 +197,6 @@ InteractiveBackend(StringInfo inBuf) } else { - /* * otherwise read characters until EOF. */ @@ -258,7 +255,6 @@ SocketBackend(StringInfo inBuf) switch (qtype) { - /* * 'Q': user entered a query */ @@ -686,7 +682,6 @@ pg_exec_query_string(char *query_string, /* string to execute */ if (!allowit) { - /* * the EndCommand() stuff is to tell the frontend that the * command ended. -cim 6/1/90 @@ -755,7 +750,6 @@ pg_exec_query_string(char *query_string, /* string to execute */ if (querytree->commandType == CMD_UTILITY) { - /* * process utility functions (create, destroy, etc..) */ @@ -768,7 +762,6 @@ pg_exec_query_string(char *query_string, /* string to execute */ } else { - /* * process a plannable query. */ @@ -848,7 +841,7 @@ pg_exec_query_string(char *query_string, /* string to execute */ if (xact_started) finish_xact_command(); - debug_query_string = NULL; /* used by pgmonitor */ + debug_query_string = NULL; /* used by pgmonitor */ } /* @@ -901,7 +894,7 @@ quickdie(SIGNAL_ARGS) "\n\tThe Postmaster has informed me that some other backend" "\n\tdied abnormally and possibly corrupted shared memory." "\n\tI have rolled back the current transaction and am" - "\n\tgoing to terminate your database system connection and exit." + "\n\tgoing to terminate your database system connection and exit." "\n\tPlease reconnect to the database system and repeat your query."); /* @@ -1111,7 +1104,7 @@ PostgresMain(int argc, char *argv[], const char *username) bool secure; int errs = 0; GucContext ctx; - char *tmp; + char *tmp; int firstchar; StringInfo parser_input; @@ -1482,9 +1475,9 @@ PostgresMain(int argc, char *argv[], const char *username) if (!potential_DataDir) { fprintf(stderr, "%s does not know where to find the database system " - "data. You must specify the directory that contains the " - "database system either by specifying the -D invocation " - "option or by setting the PGDATA environment variable.\n\n", + "data. You must specify the directory that contains the " + "database system either by specifying the -D invocation " + "option or by setting the PGDATA environment variable.\n\n", argv[0]); proc_exit(1); } @@ -1509,7 +1502,7 @@ PostgresMain(int argc, char *argv[], const char *username) pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */ pqsignal(SIGINT, QueryCancelHandler); /* cancel current query */ pqsignal(SIGTERM, die); /* cancel current query and exit */ - pqsignal(SIGQUIT, quickdie);/* hard crash time */ + pqsignal(SIGQUIT, quickdie); /* hard crash time */ pqsignal(SIGALRM, HandleDeadLock); /* check for deadlock after * timeout */ @@ -1529,7 +1522,8 @@ PostgresMain(int argc, char *argv[], const char *username) * Reset some signals that are accepted by postmaster but not by * backend */ - pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */ + pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some + * platforms */ pqsignal(SIGTTIN, SIG_DFL); pqsignal(SIGTTOU, SIG_DFL); pqsignal(SIGCONT, SIG_DFL); @@ -1586,8 +1580,8 @@ PostgresMain(int argc, char *argv[], const char *username) argv[0]); /* - * Validate we have been given a reasonable-looking DataDir - * (if under postmaster, assume postmaster did this already). + * Validate we have been given a reasonable-looking DataDir (if + * under postmaster, assume postmaster did this already). */ ValidatePgVersion(DataDir); @@ -1648,7 +1642,7 @@ PostgresMain(int argc, char *argv[], const char *username) if (!IsUnderPostmaster) { puts("\nPOSTGRES backend interactive interface "); - puts("$Revision: 1.238 $ $Date: 2001/10/21 03:25:35 $\n"); + puts("$Revision: 1.239 $ $Date: 2001/10/25 05:49:43 $\n"); } /* @@ -1740,7 +1734,6 @@ PostgresMain(int argc, char *argv[], const char *username) for (;;) { - /* * Release storage left over from prior query cycle, and create a * new query input buffer in the cleared QueryContext. @@ -1819,7 +1812,6 @@ PostgresMain(int argc, char *argv[], const char *username) */ switch (firstchar) { - /* * 'F' indicates a fastpath call. */ @@ -1849,7 +1841,6 @@ PostgresMain(int argc, char *argv[], const char *username) case 'Q': if (strspn(parser_input->data, " \t\r\n") == parser_input->len) { - /* * if there is nothing in the input buffer, don't * bother trying to parse and execute anything; just @@ -1860,7 +1851,6 @@ PostgresMain(int argc, char *argv[], const char *username) } else { - /* * otherwise, process the input string. * @@ -2058,6 +2048,5 @@ assertTest(int val) return val; } - #endif #endif diff --git a/src/backend/tcop/pquery.c b/src/backend/tcop/pquery.c index c7a33a3bc2..91d98a2d50 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.45 2001/10/05 17:28:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/pquery.c,v 1.46 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,7 +30,7 @@ static char *CreateOperationTag(int operationType); * CreateQueryDesc * ---------------------------------------------------------------- */ -QueryDesc * +QueryDesc * CreateQueryDesc(Query *parsetree, Plan *plantree, CommandDest dest) @@ -140,7 +140,6 @@ PreparePortal(char *portalName) portal = GetPortalByName(portalName); if (PortalIsValid(portal)) { - /* * XXX Should we raise an error rather than closing the old * portal? @@ -197,7 +196,6 @@ ProcessQuery(Query *parsetree, intoName = parsetree->into; if (parsetree->isBinary) { - /* * For internal format portals, we change Remote * (externalized form) to RemoteInternal (internalized diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c index 66ccb65278..7142f0e60f 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.121 2001/10/18 17:30:15 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/tcop/utility.c,v 1.122 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -144,7 +144,6 @@ ProcessUtility(Node *parsetree, switch (nodeTag(parsetree)) { - /* * ******************************** transactions ******************************** * @@ -386,7 +385,6 @@ ProcessUtility(Node *parsetree, */ if (stmt->column == NULL) { - /* * rename relation * @@ -398,7 +396,6 @@ ProcessUtility(Node *parsetree, } else { - /* * rename attribute */ @@ -476,7 +473,8 @@ ProcessUtility(Node *parsetree, case T_GrantStmt: { - GrantStmt *stmt = (GrantStmt *) parsetree; + GrantStmt *stmt = (GrantStmt *) parsetree; + commandTag = stmt->is_grant ? "GRANT" : "REVOKE"; set_ps_display(commandTag); diff --git a/src/backend/tioga/Arr_TgRecipe.h b/src/backend/tioga/Arr_TgRecipe.h index a382411455..346f74c293 100644 --- a/src/backend/tioga/Arr_TgRecipe.h +++ b/src/backend/tioga/Arr_TgRecipe.h @@ -52,7 +52,6 @@ typedef struct Arr_TgString AppendVarray((Varray *) (A), (void *) (V), (CopyingFunct) copyTgString) #define deleteArr_TgString(A) FreeVarray(A) - #endif /* _ARR_TgString_ */ /* -- Defining types and function for Arr_TgElementPtr type -- */ @@ -90,7 +89,6 @@ typedef struct Arr_TgElementPtr AppendVarray((Varray *) (A), (void *) (V), (CopyingFunct) copyTgElementPtr) #define deleteArr_TgElementPtr(A) FreeVarray(A) - #endif /* _ARR_TgElementPtr_ */ /* -- Defining types and function for Arr_TgNodePtr type -- */ @@ -128,5 +126,4 @@ typedef struct Arr_TgNodePtr AppendVarray((Varray *) (A), (void *) (V), (CopyingFunct) copyTgNodePtr) #define deleteArr_TgNodePtr(A) FreeVarray(A) - #endif /* _ARR_TgNodePtr_ */ diff --git a/src/backend/tioga/Varray.h b/src/backend/tioga/Varray.h index aed53855a4..c81a7f28ef 100644 --- a/src/backend/tioga/Varray.h +++ b/src/backend/tioga/Varray.h @@ -44,5 +44,4 @@ typedef void (*CopyingFunct) (void *from, void *to); extern Varray *NewVarray(size_t nobj, size_t size); extern int AppendVarray(Varray * array, void *value, CopyingFunct copy); - #endif /* _VARRAY_H_ */ diff --git a/src/backend/tioga/tgRecipe.c b/src/backend/tioga/tgRecipe.c index 0a2dca7dd8..b9304c5bf7 100644 --- a/src/backend/tioga/tgRecipe.c +++ b/src/backend/tioga/tgRecipe.c @@ -12,7 +12,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/tioga/Attic/tgRecipe.c,v 1.19 2001/03/22 03:59:48 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/tioga/Attic/tgRecipe.c,v 1.20 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -122,7 +122,7 @@ findElemInRecipe() XXX Currently, this is done by linear search. Change to using a hash table. -------------------------------------- */ -TgElement * +TgElement * findElemInRecipe(TgRecipe * r, char *elemName) { int i; @@ -188,7 +188,6 @@ fillTgNode(TgRecipe * r, TgNode * node, PortalBuffer * pbuf, int tupno) if (!attnums_initialized) { - /* * the first time fillTgNode is called, we find out all the * relevant attribute numbers in a TgNode so subsequent calls are @@ -278,7 +277,6 @@ fillTgElement(TgElement * elem, PortalBuffer * pbuf, int tupno) if (!attnums_initialized) { - /* * the first time fillTgElement is called, we find out all the * relevant attribute numbers in a TgElement so subsequent calls @@ -617,7 +615,7 @@ fillTgRecipe takes a query result in the PortalBuffer containing a Recipe and converts it to a C TgRecipe strcture ------------------------------------ */ -TgRecipe * +TgRecipe * fillTgRecipe(PortalBuffer * pbuf, int tupno) { TgRecipe *r; @@ -690,7 +688,7 @@ fillTgRecipe(PortalBuffer * pbuf, int tupno) retrieveRecipe find the recipe with the given name ------------------------------------ */ -TgRecipe * +TgRecipe * retrieveRecipe(char *name) { char qbuf[MAX_QBUF_LENGTH]; diff --git a/src/backend/tioga/tgRecipe.h b/src/backend/tioga/tgRecipe.h index 52868554a1..f22e4bc8b5 100644 --- a/src/backend/tioga/tgRecipe.h +++ b/src/backend/tioga/tgRecipe.h @@ -12,7 +12,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: tgRecipe.h,v 1.17 2001/03/22 06:16:17 momjian Exp $ + * $Id: tgRecipe.h,v 1.18 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -42,31 +42,31 @@ typedef struct * * * + * * geo-decls.h */ - #endif /* TIOGA_FRONTEND */ typedef enum { - TG_INGRED, - TG_EYE, - TG_RECIPE + TG_INGRED, + TG_EYE, + TG_RECIPE } TgElemType; typedef enum { - TG_SQL, - TG_C, - TG_RECIPE_GRAPH, - TG_COMPILED + TG_SQL, + TG_C, + TG_RECIPE_GRAPH, + TG_COMPILED } TgSrcLangType; typedef enum { - TG_INGRED_NODE, - TG_EYE_NODE, - TG_RECIPE_NODE, - TG_TEE_NODE /* tee nodes are not stored in the db we + TG_INGRED_NODE, + TG_EYE_NODE, + TG_RECIPE_NODE, + TG_TEE_NODE /* tee nodes are not stored in the db we * create them when we read the recipe * back */ } TgNodeType; diff --git a/src/backend/utils/adt/acl.c b/src/backend/utils/adt/acl.c index 4a21630b06..11f4dc52bf 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.64 2001/06/14 01:09:22 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/acl.c,v 1.65 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -38,11 +38,11 @@ static bool aclitemgt(const AclItem *a1, const AclItem *a2); static AclMode convert_priv_string(text *priv_type_text); static bool has_table_privilege_cname_cname(char *username, char *relname, - text *priv_type_text); + text *priv_type_text); static bool has_table_privilege_cname_id(char *username, Oid reloid, - text *priv_type_text); + text *priv_type_text); static bool has_table_privilege_id_cname(int32 usesysid, char *relname, - text *priv_type_text); + text *priv_type_text); /* @@ -394,7 +394,7 @@ acldefault(const char *relname, AclId ownerid) /* - * Add or replace an item in an ACL array. The result is a modified copy; + * Add or replace an item in an ACL array. The result is a modified copy; * the input object is not changed. * * NB: caller is responsible for having detoasted the input ACL, if needed. @@ -622,7 +622,7 @@ aclmakepriv(const char *old_privlist, char new_priv) int l; Assert(strlen(old_privlist) <= strlen(ACL_MODE_STR)); - priv = palloc(strlen(ACL_MODE_STR)+1); + priv = palloc(strlen(ACL_MODE_STR) + 1); if (old_privlist == NULL || old_privlist[0] == '\0') { @@ -687,7 +687,7 @@ char * makeAclString(const char *privileges, const char *grantee, char grant_or_revoke) { StringInfoData str; - char *ret; + char *ret; initStringInfo(&str); @@ -731,7 +731,7 @@ has_table_privilege_name_name(PG_FUNCTION_ARGS) { Name username = PG_GETARG_NAME(0); Name relname = PG_GETARG_NAME(1); - text *priv_type_text = PG_GETARG_TEXT_P(2); + text *priv_type_text = PG_GETARG_TEXT_P(2); bool result; result = has_table_privilege_cname_cname(NameStr(*username), @@ -757,7 +757,7 @@ Datum has_table_privilege_name(PG_FUNCTION_ARGS) { Name relname = PG_GETARG_NAME(0); - text *priv_type_text = PG_GETARG_TEXT_P(1); + text *priv_type_text = PG_GETARG_TEXT_P(1); int32 usesysid; bool result; @@ -786,7 +786,7 @@ has_table_privilege_name_id(PG_FUNCTION_ARGS) { Name username = PG_GETARG_NAME(0); Oid reloid = PG_GETARG_OID(1); - text *priv_type_text = PG_GETARG_TEXT_P(2); + text *priv_type_text = PG_GETARG_TEXT_P(2); bool result; result = has_table_privilege_cname_id(NameStr(*username), @@ -812,7 +812,7 @@ Datum has_table_privilege_id(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); - text *priv_type_text = PG_GETARG_TEXT_P(1); + text *priv_type_text = PG_GETARG_TEXT_P(1); char *relname; int32 usesysid; AclMode mode; @@ -828,12 +828,12 @@ has_table_privilege_id(PG_FUNCTION_ARGS) elog(ERROR, "has_table_privilege: invalid relation oid %u", reloid); - /* + /* * Convert priv_type_text to an AclMode */ mode = convert_priv_string(priv_type_text); - /* + /* * Finally, check for the privilege */ result = pg_aclcheck(relname, usesysid, mode); @@ -860,7 +860,7 @@ has_table_privilege_id_name(PG_FUNCTION_ARGS) { int32 usesysid = PG_GETARG_INT32(0); Name relname = PG_GETARG_NAME(1); - text *priv_type_text = PG_GETARG_TEXT_P(2); + text *priv_type_text = PG_GETARG_TEXT_P(2); bool result; result = has_table_privilege_id_cname(usesysid, @@ -886,8 +886,8 @@ has_table_privilege_id_id(PG_FUNCTION_ARGS) { int32 usesysid = PG_GETARG_INT32(0); Oid reloid = PG_GETARG_OID(1); - text *priv_type_text = PG_GETARG_TEXT_P(2); - char *relname; + text *priv_type_text = PG_GETARG_TEXT_P(2); + char *relname; AclMode mode; int32 result; @@ -899,12 +899,12 @@ has_table_privilege_id_id(PG_FUNCTION_ARGS) elog(ERROR, "has_table_privilege: invalid relation oid %u", reloid); - /* + /* * Convert priv_type_text to an AclMode */ mode = convert_priv_string(priv_type_text); - /* + /* * Finally, check for the privilege */ result = pg_aclcheck(relname, usesysid, mode); @@ -931,7 +931,7 @@ has_table_privilege_id_id(PG_FUNCTION_ARGS) static AclMode convert_priv_string(text *priv_type_text) { - char *priv_type = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(priv_type_text))); + char *priv_type = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(priv_type_text))); /* * Return mode from priv_type string @@ -958,6 +958,7 @@ convert_priv_string(text *priv_type_text) return ACL_TRIGGER; elog(ERROR, "has_table_privilege: invalid privilege type %s", priv_type); + /* * We should never get here, but stop the compiler from complaining */ @@ -986,8 +987,8 @@ has_table_privilege_cname_cname(char *username, char *relname, usesysid = get_usesysid(username); /* - * Make use of has_table_privilege_id_cname. - * It accepts the arguments we now have. + * Make use of has_table_privilege_id_cname. It accepts the arguments + * we now have. */ return has_table_privilege_id_cname(usesysid, relname, priv_type_text); } @@ -1008,7 +1009,7 @@ has_table_privilege_cname_id(char *username, Oid reloid, text *priv_type_text) { int32 usesysid; - char *relname; + char *relname; /* * Lookup userid based on username @@ -1024,8 +1025,8 @@ has_table_privilege_cname_id(char *username, Oid reloid, reloid); /* - * Make use of has_table_privilege_id_cname. - * It accepts the arguments we now have. + * Make use of has_table_privilege_id_cname. It accepts the arguments + * we now have. */ return has_table_privilege_id_cname(usesysid, relname, priv_type_text); } @@ -1050,10 +1051,9 @@ has_table_privilege_id_cname(int32 usesysid, char *relname, int32 result; /* - * Check relname is valid. - * This is needed to deal with the case when usename is a superuser - * in which case pg_aclcheck simply returns ACLCHECK_OK - * without validating relname + * Check relname is valid. This is needed to deal with the case when + * usename is a superuser in which case pg_aclcheck simply returns + * ACLCHECK_OK without validating relname */ tuple = SearchSysCache(RELNAME, PointerGetDatum(relname), @@ -1063,12 +1063,12 @@ has_table_privilege_id_cname(int32 usesysid, char *relname, relname); ReleaseSysCache(tuple); - /* + /* * Convert priv_type_text to an AclMode */ mode = convert_priv_string(priv_type_text); - /* + /* * Finally, check for the privilege */ result = pg_aclcheck(relname, usesysid, mode); diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index 84c674071c..f668784714 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.70 2001/03/22 03:59:49 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/arrayfuncs.c,v 1.71 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -764,7 +764,6 @@ array_ref(ArrayType *array, if (arraylen > 0) { - /* * fixed-length arrays -- these are assumed to be 1-d, 0-based */ @@ -815,7 +814,7 @@ array_ref(ArrayType *array, * lowerIndx[] and upperIndx[]. These are generally just temporaries. *----------------------------------------------------------------------------- */ -ArrayType * +ArrayType * array_get_slice(ArrayType *array, int nSubscripts, int *upperIndx, @@ -841,7 +840,6 @@ array_get_slice(ArrayType *array, if (arraylen > 0) { - /* * fixed-length arrays -- currently, cannot slice these because * parser labels output as being of the fixed-length array type! @@ -926,7 +924,7 @@ array_get_slice(ArrayType *array, * with NULL, which will probably not make him happy. *----------------------------------------------------------------------------- */ -ArrayType * +ArrayType * array_set(ArrayType *array, int nSubscripts, int *indx, @@ -958,7 +956,6 @@ array_set(ArrayType *array, if (arraylen > 0) { - /* * fixed-length arrays -- these are assumed to be 1-d, 0-based. We * cannot extend them, either. @@ -1090,7 +1087,7 @@ array_set(ArrayType *array, * with NULL, which will probably not make him happy. *---------------------------------------------------------------------------- */ -ArrayType * +ArrayType * array_set_slice(ArrayType *array, int nSubscripts, int *upperIndx, @@ -1123,7 +1120,6 @@ array_set_slice(ArrayType *array, if (arraylen > 0) { - /* * fixed-length arrays -- not got round to doing this... */ @@ -1192,7 +1188,6 @@ array_set_slice(ArrayType *array, olddatasize = ARR_SIZE(array) - overheadlen; if (ndim > 1) { - /* * here we do not need to cope with extension of the array; it * would be a lot more complicated if we had to do so... @@ -1203,7 +1198,6 @@ array_set_slice(ArrayType *array, } else { - /* * here we must allow for possibility of slice larger than orig * array @@ -1237,7 +1231,6 @@ array_set_slice(ArrayType *array, if (ndim > 1) { - /* * here we do not need to cope with extension of the array; it * would be a lot more complicated if we had to do so... @@ -1401,7 +1394,7 @@ array_map(FunctionCallInfo fcinfo, Oid inpType, Oid retType) * NULL element values are not supported. *---------- */ -ArrayType * +ArrayType * construct_array(Datum *elems, int nelems, bool elmbyval, int elmlen, char elmalign) { diff --git a/src/backend/utils/adt/ascii.c b/src/backend/utils/adt/ascii.c index 99bafca1ba..c08960ca20 100644 --- a/src/backend/utils/adt/ascii.c +++ b/src/backend/utils/adt/ascii.c @@ -1,7 +1,7 @@ /* ----------------------------------------------------------------------- * ascii.c * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/ascii.c,v 1.9 2001/09/06 04:57:29 ishii Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/ascii.c,v 1.10 2001/10/25 05:49:43 momjian Exp $ * * Portions Copyright (c) 1999-2000, PostgreSQL Global Development Group * @@ -80,7 +80,6 @@ pg_to_ascii(unsigned char *src, unsigned char *src_end, unsigned char *desc, int if (enc == PG_LATIN1) { - /* * ISO-8859-1 <range: 160 -- 255> */ @@ -89,7 +88,6 @@ pg_to_ascii(unsigned char *src, unsigned char *src_end, unsigned char *desc, int } else if (enc == PG_LATIN2) { - /* * ISO-8859-2 <range: 160 -- 255> */ @@ -98,7 +96,6 @@ pg_to_ascii(unsigned char *src, unsigned char *src_end, unsigned char *desc, int } else if (enc == PG_WIN1250) { - /* * Window CP1250 <range: 128 -- 255> */ @@ -151,13 +148,13 @@ Datum to_ascii_encname(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P - ( - encode_to_ascii - ( - PG_GETARG_TEXT_P_COPY(0), - pg_char_to_encoding(NameStr(*PG_GETARG_NAME(1))) - ) - ); + ( + encode_to_ascii + ( + PG_GETARG_TEXT_P_COPY(0), + pg_char_to_encoding(NameStr(*PG_GETARG_NAME(1))) + ) + ); } /* ---------- @@ -168,13 +165,13 @@ Datum to_ascii_enc(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P - ( - encode_to_ascii - ( - PG_GETARG_TEXT_P_COPY(0), - PG_GETARG_INT32(1) - ) - ); + ( + encode_to_ascii + ( + PG_GETARG_TEXT_P_COPY(0), + PG_GETARG_INT32(1) + ) + ); } /* ---------- @@ -185,13 +182,12 @@ Datum to_ascii_default(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P - ( - encode_to_ascii - ( - PG_GETARG_TEXT_P_COPY(0), - GetDatabaseEncoding() - ) - ); + ( + encode_to_ascii + ( + PG_GETARG_TEXT_P_COPY(0), + GetDatabaseEncoding() + ) + ); } - #endif /* MULTIBYTE */ diff --git a/src/backend/utils/adt/cash.c b/src/backend/utils/adt/cash.c index dbcf881bf6..7ffa8a82c3 100644 --- a/src/backend/utils/adt/cash.c +++ b/src/backend/utils/adt/cash.c @@ -9,7 +9,7 @@ * workings can be found in the book "Software Solutions in C" by * Dale Schumacher, Academic Press, ISBN: 0-12-632360-7. * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/cash.c,v 1.50 2001/03/22 03:59:49 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/cash.c,v 1.51 2001/10/25 05:49:43 momjian Exp $ */ #include "postgres.h" @@ -85,7 +85,6 @@ cash_in(PG_FUNCTION_ARGS) #ifdef USE_LOCALE struct lconv *lconvert = PGLC_localeconv(); - #endif #ifdef USE_LOCALE @@ -244,7 +243,6 @@ cash_out(PG_FUNCTION_ARGS) #ifdef USE_LOCALE struct lconv *lconvert = PGLC_localeconv(); - #endif #ifdef USE_LOCALE diff --git a/src/backend/utils/adt/char.c b/src/backend/utils/adt/char.c index dc6bd5e976..fa2cc09321 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.31 2001/05/28 21:58:32 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/char.c,v 1.32 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -161,9 +161,9 @@ text_char(PG_FUNCTION_ARGS) char result; /* - * An empty input string is converted to \0 (for consistency with charin). - * If the input is longer than one character, the excess data is silently - * discarded. + * An empty input string is converted to \0 (for consistency with + * charin). If the input is longer than one character, the excess data + * is silently discarded. */ if (VARSIZE(arg1) > VARHDRSZ) result = *(VARDATA(arg1)); @@ -189,9 +189,7 @@ char_text(PG_FUNCTION_ARGS) *(VARDATA(result)) = arg1; } else - { VARATT_SIZEP(result) = VARHDRSZ; - } PG_RETURN_TEXT_P(result); } diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c index d59d9f9e11..8fb2bbad29 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.62 2001/10/18 17:30:15 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/date.c,v 1.63 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -268,7 +268,7 @@ Datum date_timestamptz(PG_FUNCTION_ARGS) { DateADT dateVal = PG_GETARG_DATEADT(0); - TimestampTz result; + TimestampTz result; struct tm tt, *tm = &tt; time_t utime; @@ -310,7 +310,7 @@ date_timestamptz(PG_FUNCTION_ARGS) Datum timestamptz_date(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); DateADT result; struct tm tt, *tm = &tt; @@ -427,6 +427,7 @@ Datum time_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif @@ -506,7 +507,7 @@ AdjustTimeForTypmod(TimeADT *time, int32 typmod) TimeTypmod = typmod; } - *time = (rint(((double) *time)*TimeScale)/TimeScale); + *time = (rint(((double) *time) * TimeScale) / TimeScale); if (*time >= 86400) *time -= 86400; @@ -610,7 +611,6 @@ time_smaller(PG_FUNCTION_ARGS) Datum overlaps_time(PG_FUNCTION_ARGS) { - /* * The arguments are TimeADT, but we leave them as generic Datums to * avoid dereferencing nulls (TimeADT is pass-by-reference!) @@ -679,7 +679,6 @@ overlaps_time(PG_FUNCTION_ARGS) */ if (TIMEADT_GT(ts1, ts2)) { - /* * This case is ts1 < te2 OR te1 < te2, which may look redundant * but in the presence of nulls it's not quite completely so. @@ -715,7 +714,6 @@ overlaps_time(PG_FUNCTION_ARGS) } else { - /* * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a * rather silly way of saying "true if both are nonnull, else @@ -937,6 +935,7 @@ Datum timetz_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif @@ -1199,7 +1198,6 @@ timetz_mi_interval(PG_FUNCTION_ARGS) Datum overlaps_timetz(PG_FUNCTION_ARGS) { - /* * The arguments are TimeTzADT *, but we leave them as generic Datums * for convenience of notation --- and to avoid dereferencing nulls. @@ -1268,7 +1266,6 @@ overlaps_timetz(PG_FUNCTION_ARGS) */ if (TIMETZ_GT(ts1, ts2)) { - /* * This case is ts1 < te2 OR te1 < te2, which may look redundant * but in the presence of nulls it's not quite completely so. @@ -1304,7 +1301,6 @@ overlaps_timetz(PG_FUNCTION_ARGS) } else { - /* * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a * rather silly way of saying "true if both are nonnull, else @@ -1360,7 +1356,7 @@ time_timetz(PG_FUNCTION_ARGS) Datum timestamptz_timetz(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); TimeTzADT *result; struct tm tt, *tm = &tt; @@ -1394,7 +1390,7 @@ datetimetz_timestamptz(PG_FUNCTION_ARGS) { DateADT date = PG_GETARG_DATEADT(0); TimeTzADT *time = PG_GETARG_TIMETZADT_P(1); - TimestampTz result; + TimestampTz result; result = date * 86400.0 + time->time + time->zone; @@ -1477,7 +1473,7 @@ timetz_part(PG_FUNCTION_ARGS) if (VARSIZE(units) - VARHDRSZ > MAXDATELEN) elog(ERROR, "TIMETZ units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -1550,19 +1546,17 @@ timetz_part(PG_FUNCTION_ARGS) default: elog(ERROR, "TIMETZ units '%s' not supported", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); result = 0; } } else if ((type == RESERV) && (val == DTK_EPOCH)) - { result = time->time - time->zone; - } else { elog(ERROR, "TIMETZ units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); result = 0; } diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c index 6d6fbd6b45..06b249a8e1 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.74 2001/10/20 01:02:18 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/datetime.c,v 1.75 2001/10/25 05:49:43 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -27,29 +27,29 @@ static int DecodeNumber(int flen, char *field, - int fmask, int *tmask, - struct tm * tm, double *fsec, int *is2digits); + int fmask, int *tmask, + struct tm * tm, double *fsec, int *is2digits); static int DecodeNumberField(int len, char *str, - int fmask, int *tmask, - struct tm * tm, double *fsec, int *is2digits); + int fmask, int *tmask, + struct tm * tm, double *fsec, int *is2digits); static int DecodeTime(char *str, int fmask, int *tmask, - struct tm * tm, double *fsec); + struct tm * tm, double *fsec); static int DecodeTimezone(char *str, int *tzp); static datetkn *datebsearch(char *key, datetkn *base, unsigned int nel); static int DecodeDate(char *str, int fmask, int *tmask, struct tm * tm); static int DecodePosixTimezone(char *str, int *val); -void TrimTrailingZeros(char *str); +void TrimTrailingZeros(char *str); 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}}; +{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}}; char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL}; +"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL}; char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", - "Thursday", "Friday", "Saturday", NULL}; +"Thursday", "Friday", "Saturday", NULL}; /***************************************************************************** @@ -237,7 +237,7 @@ static datetkn australian_datetktbl[] = { }; static unsigned int australian_szdatetktbl = sizeof australian_datetktbl / - sizeof australian_datetktbl[0]; +sizeof australian_datetktbl[0]; static datetkn deltatktbl[] = { /* text, token, lexval */ @@ -247,41 +247,41 @@ static datetkn deltatktbl[] = { {"cent", UNITS, DTK_CENTURY}, /* "century" relative */ {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */ {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */ - {"d", UNITS, DTK_DAY}, /* "day" relative */ - {DDAY, UNITS, DTK_DAY}, /* "day" relative */ - {"days", UNITS, DTK_DAY}, /* "days" relative */ - {"dec", UNITS, DTK_DECADE}, /* "decade" relative */ - {"decs", UNITS, DTK_DECADE}, /* "decades" relative */ + {"d", UNITS, DTK_DAY}, /* "day" relative */ + {DDAY, UNITS, DTK_DAY}, /* "day" relative */ + {"days", UNITS, DTK_DAY}, /* "days" relative */ + {"dec", UNITS, DTK_DECADE}, /* "decade" relative */ + {"decs", UNITS, DTK_DECADE},/* "decades" relative */ {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */ {"decades", UNITS, DTK_DECADE}, /* "decades" relative */ - {"h", UNITS, DTK_HOUR}, /* "hour" relative */ - {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */ - {"hours", UNITS, DTK_HOUR}, /* "hours" relative */ - {"hr", UNITS, DTK_HOUR}, /* "hour" relative */ - {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */ + {"h", UNITS, DTK_HOUR}, /* "hour" relative */ + {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */ + {"hours", UNITS, DTK_HOUR}, /* "hours" relative */ + {"hr", UNITS, DTK_HOUR}, /* "hour" relative */ + {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */ {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */ - {"m", UNITS, DTK_MINUTE}, /* "minute" relative */ - {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */ - {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */ - {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */ - {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */ - {"millisecon", UNITS, DTK_MILLISEC}, /* relative */ + {"m", UNITS, DTK_MINUTE}, /* "minute" relative */ + {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */ + {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */ + {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */ + {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */ + {"millisecon", UNITS, DTK_MILLISEC}, /* relative */ {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */ - {"min", UNITS, DTK_MINUTE}, /* "minute" relative */ - {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */ - {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */ + {"min", UNITS, DTK_MINUTE}, /* "minute" relative */ + {"mins", UNITS, DTK_MINUTE},/* "minutes" relative */ + {"mins", UNITS, DTK_MINUTE},/* "minutes" relative */ {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */ {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */ - {"mon", UNITS, DTK_MONTH}, /* "months" relative */ - {"mons", UNITS, DTK_MONTH}, /* "months" relative */ - {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */ + {"mon", UNITS, DTK_MONTH}, /* "months" relative */ + {"mons", UNITS, DTK_MONTH}, /* "months" relative */ + {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */ {"months", UNITS, DTK_MONTH}, {"ms", UNITS, DTK_MILLISEC}, {"msec", UNITS, DTK_MILLISEC}, {DMILLISEC, UNITS, DTK_MILLISEC}, {"mseconds", UNITS, DTK_MILLISEC}, {"msecs", UNITS, DTK_MILLISEC}, - {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */ + {"qtr", UNITS, DTK_QUARTER},/* "quarter" relative */ {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */ {"reltime", IGNORE, 0}, /* pre-v6.1 "Undefined Reltime" */ {"s", UNITS, DTK_SECOND}, @@ -289,12 +289,12 @@ static datetkn deltatktbl[] = { {DSECOND, UNITS, DTK_SECOND}, {"seconds", UNITS, DTK_SECOND}, {"secs", UNITS, DTK_SECOND}, - {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */ - {"timezone", UNITS, DTK_TZ}, /* "timezone" time offset */ - {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */ - {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */ + {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */ + {"timezone", UNITS, DTK_TZ},/* "timezone" time offset */ + {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */ + {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */ {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */ - {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */ + {"us", UNITS, DTK_MICROSEC},/* "microsecond" relative */ {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */ {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */ {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */ @@ -391,7 +391,7 @@ j2day(int date) void TrimTrailingZeros(char *str) { - int len = strlen(str); + int len = strlen(str); #if 0 /* chop off trailing one to cope with interval rounding */ @@ -585,7 +585,8 @@ DecodeDateTime(char **field, int *ftype, int nf, int fmask = 0, tmask, type; - int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */ + int ptype = 0; /* "prefix type" for ISO y2001m02d04 + * format */ int i; int flen, val; @@ -594,16 +595,17 @@ DecodeDateTime(char **field, int *ftype, int nf, int is2digits = FALSE; int bc = FALSE; - /* We'll insist on at least all of the date fields, - * but initialize the remaining fields in case they are not - * set later... + /* + * We'll insist on at least all of the date fields, but initialize the + * remaining fields in case they are not set later... */ *dtype = DTK_DATE; tm->tm_hour = 0; tm->tm_min = 0; tm->tm_sec = 0; *fsec = 0; - tm->tm_isdst = -1; /* don't know daylight savings time status apriori */ + tm->tm_isdst = -1; /* don't know daylight savings time status + * apriori */ if (tzp != NULL) *tzp = 0; @@ -612,13 +614,17 @@ DecodeDateTime(char **field, int *ftype, int nf, switch (ftype[i]) { case DTK_DATE: - /* Previous field was a label for "julian date"? - * then this should be a julian date with fractional day... + + /* + * Previous field was a label for "julian date"? then this + * should be a julian date with fractional day... */ if (ptype == JULIAN) { - char *cp; - double dt, date, time; + char *cp; + double dt, + date, + time; dt = strtod(field[i], &cp); if (*cp != '\0') @@ -633,9 +639,10 @@ DecodeDateTime(char **field, int *ftype, int nf, *dtype = DTK_DATE; } - /* Already have a date? Then this might be a POSIX time - * zone with an embedded dash (e.g. "PST-3" == "EST") - * - thomas 2000-03-15 + /* + * Already have a date? Then this might be a POSIX time + * zone with an embedded dash (e.g. "PST-3" == "EST") - + * thomas 2000-03-15 */ else if ((fmask & DTK_DATE_M) == DTK_DATE_M) { @@ -647,16 +654,15 @@ DecodeDateTime(char **field, int *ftype, int nf, tmask = DTK_M(TZ); } else if (DecodeDate(field[i], fmask, &tmask, tm) != 0) - { return -1; - } break; case DTK_TIME: if (DecodeTime(field[i], fmask, &tmask, tm, fsec) != 0) return -1; - /* Check upper limit on hours; other limits checked in + /* + * Check upper limit on hours; other limits checked in * DecodeTime() */ if (tm->tm_hour > 23) @@ -696,19 +702,21 @@ DecodeDateTime(char **field, int *ftype, int nf, case DTK_NUMBER: flen = strlen(field[i]); - /* Was this an "ISO date" with embedded field labels? - * An example is "y2001m02d04" - thomas 2001-02-04 + /* + * Was this an "ISO date" with embedded field labels? An + * example is "y2001m02d04" - thomas 2001-02-04 */ if (ptype != 0) { - char *cp; - int val; + char *cp; + int val; val = strtol(field[i], &cp, 10); if (*cp != '\0') return -1; - switch (ptype) { + switch (ptype) + { case YEAR: tm->tm_year = val; tmask = DTK_M(ptype); @@ -740,9 +748,12 @@ DecodeDateTime(char **field, int *ftype, int nf, break; case JULIAN: - /* previous field was a label for "julian date"? - * then this is a julian day with no fractional part - * (see DTK_DATE for cases involving fractional parts) + + /* + * previous field was a label for "julian + * date"? then this is a julian day with no + * fractional part (see DTK_DATE for cases + * involving fractional parts) */ j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday); @@ -757,6 +768,7 @@ DecodeDateTime(char **field, int *ftype, int nf, ptype = 0; *dtype = DTK_DATE; } + /* * long numeric string and either no date or no time read * yet? then interpret as a concatenated date or time... @@ -769,9 +781,7 @@ DecodeDateTime(char **field, int *ftype, int nf, } /* otherwise it is a single date/time field... */ else if (DecodeNumber(flen, field[i], fmask, &tmask, tm, fsec, &is2digits) != 0) - { return -1; - } break; case DTK_STRING: @@ -916,9 +926,9 @@ DecodeDateTime(char **field, int *ftype, int nf, case DTK_ISO_TIME: tmask = 0; - if ((i < 1) || (i >= (nf-1)) - || (ftype[i-1] != DTK_DATE) - || (ftype[i+1] != DTK_TIME)) + if ((i < 1) || (i >= (nf - 1)) + || (ftype[i - 1] != DTK_DATE) + || (ftype[i + 1] != DTK_TIME)) return -1; break; @@ -977,7 +987,6 @@ DecodeDateTime(char **field, int *ftype, int nf, if (((fmask & DTK_DATE_M) == DTK_DATE_M) && (tzp != NULL) && (!(fmask & DTK_M(TZ)))) { - /* * daylight savings time modifier but no standard timezone? * then error @@ -1008,16 +1017,16 @@ DetermineLocalTimeZone(struct tm * tm) int tz; if (HasCTZSet) - { tz = CTimeZone; - } else if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday)) { #if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE) + /* - * Some buggy mktime() implementations may change the year/month/day - * when given a time right at a DST boundary. To prevent corruption - * of the caller's data, give mktime() a copy... + * Some buggy mktime() implementations may change the + * year/month/day when given a time right at a DST boundary. To + * prevent corruption of the caller's data, give mktime() a + * copy... */ struct tm tt, *tmp = &tt; @@ -1500,9 +1509,8 @@ DecodeNumber(int flen, char *str, int fmask, /* * Enough digits to be unequivocal year? Used to test for 4 digits or * more, but we now test first for a three-digit doy so anything - * bigger than two digits had better be an explicit year. - * - thomas 1999-01-09 - * Back to requiring a 4 digit year. We accept a two digit + * bigger than two digits had better be an explicit year. - thomas + * 1999-01-09 Back to requiring a 4 digit year. We accept a two digit * year farther down. - thomas 2000-03-28 */ else if (flen >= 4) @@ -1745,7 +1753,7 @@ DecodeSpecial(int field, char *lowtoken, int *val) tp = NULL; if (Australian_timezones) tp = datebsearch(lowtoken, australian_datetktbl, - australian_szdatetktbl); + australian_szdatetktbl); if (!tp) tp = datebsearch(lowtoken, datetktbl, szdatetktbl); } @@ -1863,7 +1871,6 @@ DecodeDateDelta(char **field, int *ftype, int nf, int *dtype, struct tm * tm, do { if (*cp == '.') { - /* * Got a decimal point? Then assume some sort of * seconds specification @@ -1872,7 +1879,6 @@ DecodeDateDelta(char **field, int *ftype, int nf, int *dtype, struct tm * tm, do } else if (*cp == '\0') { - /* * Only a signed integer? Then must assume a * timezone-like usage @@ -2062,9 +2068,7 @@ DecodeUnits(int field, char *lowtoken, int *val) && (strncmp(lowtoken, deltacache[field]->token, TOKMAXLEN) == 0)) tp = deltacache[field]; else - { tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl); - } deltacache[field] = tp; if (tp == NULL) { @@ -2189,25 +2193,23 @@ EncodeTimeOnly(struct tm * tm, double fsec, int *tzp, int style, char *str) sprintf(str, "%02d:%02d", tm->tm_hour, tm->tm_min); - /* If we have fractional seconds, then include a decimal point - * We will do up to 6 fractional digits, and we have rounded any inputs - * to eliminate anything to the right of 6 digits anyway. - * If there are no fractional seconds, then do not bother printing - * a decimal point at all. - thomas 2001-09-29 + /* + * If we have fractional seconds, then include a decimal point We will + * do up to 6 fractional digits, and we have rounded any inputs to + * eliminate anything to the right of 6 digits anyway. If there are no + * fractional seconds, then do not bother printing a decimal point at + * all. - thomas 2001-09-29 */ - if (fsec != 0) { + if (fsec != 0) + { sprintf((str + strlen(str)), ":%013.10f", sec); /* chop off trailing pairs of zeros... */ while ((strcmp((str + strlen(str) - 2), "00") == 0) && (*(str + strlen(str) - 3) != '.')) - { *(str + strlen(str) - 2) = '\0'; - } } else - { sprintf((str + strlen(str)), ":%02.0f", sec); - } if (tzp != NULL) { @@ -2257,24 +2259,28 @@ EncodeDateTime(struct tm * tm, double fsec, int *tzp, char **tzn, int style, cha sprintf(str, "%04d-%02d-%02d %02d:%02d", tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min); - /* If we have fractional seconds, then include a decimal point - * We will do up to 6 fractional digits, and we have rounded any inputs - * to eliminate anything to the right of 6 digits anyway. - * If there are no fractional seconds, then do not bother printing - * a decimal point at all. - thomas 2001-09-29 + /* + * If we have fractional seconds, then include a decimal + * point We will do up to 6 fractional digits, and we have + * rounded any inputs to eliminate anything to the right + * of 6 digits anyway. If there are no fractional seconds, + * then do not bother printing a decimal point at all. - + * thomas 2001-09-29 */ - if (fsec != 0) { + if (fsec != 0) + { sprintf((str + strlen(str)), ":%013.10f", sec); TrimTrailingZeros(str); } else - { sprintf((str + strlen(str)), ":%02.0f", sec); - } - /* tzp == NULL indicates that we don't want *any* time zone info in the output string. - * *tzn != NULL indicates that we have alpha time zone info available. - * tm_isdst != -1 indicates that we have a valid time zone translation. + /* + * tzp == NULL indicates that we don't want *any* time + * zone info in the output string. *tzn != NULL indicates + * that we have alpha time zone info available. tm_isdst + * != -1 indicates that we have a valid time zone + * translation. */ if ((tzp != NULL) && (tm->tm_isdst >= 0)) { @@ -2306,27 +2312,26 @@ EncodeDateTime(struct tm * tm, double fsec, int *tzp, char **tzn, int style, cha sprintf((str + 5), "/%04d %02d:%02d", tm->tm_year, tm->tm_hour, tm->tm_min); - /* If we have fractional seconds, then include a decimal point - * We will do up to 6 fractional digits, and we have rounded any inputs - * to eliminate anything to the right of 6 digits anyway. - * If there are no fractional seconds, then do not bother printing - * a decimal point at all. - thomas 2001-09-29 + /* + * If we have fractional seconds, then include a decimal + * point We will do up to 6 fractional digits, and we have + * rounded any inputs to eliminate anything to the right + * of 6 digits anyway. If there are no fractional seconds, + * then do not bother printing a decimal point at all. - + * thomas 2001-09-29 */ - if (fsec != 0) { + if (fsec != 0) + { sprintf((str + strlen(str)), ":%013.10f", sec); TrimTrailingZeros(str); } else - { sprintf((str + strlen(str)), ":%02.0f", sec); - } if ((tzp != NULL) && (tm->tm_isdst >= 0)) { if (*tzn != NULL) - { sprintf((str + strlen(str)), " %.*s", MAXTZLEN, *tzn); - } else { hour = -(*tzp / 3600); @@ -2348,27 +2353,26 @@ EncodeDateTime(struct tm * tm, double fsec, int *tzp, char **tzn, int style, cha sprintf((str + 5), ".%04d %02d:%02d", tm->tm_year, tm->tm_hour, tm->tm_min); - /* If we have fractional seconds, then include a decimal point - * We will do up to 6 fractional digits, and we have rounded any inputs - * to eliminate anything to the right of 6 digits anyway. - * If there are no fractional seconds, then do not bother printing - * a decimal point at all. - thomas 2001-09-29 + /* + * If we have fractional seconds, then include a decimal + * point We will do up to 6 fractional digits, and we have + * rounded any inputs to eliminate anything to the right + * of 6 digits anyway. If there are no fractional seconds, + * then do not bother printing a decimal point at all. - + * thomas 2001-09-29 */ - if (fsec != 0) { + if (fsec != 0) + { sprintf((str + strlen(str)), ":%013.10f", sec); TrimTrailingZeros(str); } else - { sprintf((str + strlen(str)), ":%02.0f", sec); - } if ((tzp != NULL) && (tm->tm_isdst >= 0)) { if (*tzn != NULL) - { sprintf((str + strlen(str)), " %.*s", MAXTZLEN, *tzn); - } else { hour = -(*tzp / 3600); @@ -2400,35 +2404,36 @@ EncodeDateTime(struct tm * tm, double fsec, int *tzp, char **tzn, int style, cha { sprintf((str + 10), " %02d:%02d", tm->tm_hour, tm->tm_min); - /* If we have fractional seconds, then include a decimal point - * We will do up to 6 fractional digits, and we have rounded any inputs - * to eliminate anything to the right of 6 digits anyway. - * If there are no fractional seconds, then do not bother printing - * a decimal point at all. - thomas 2001-09-29 + /* + * If we have fractional seconds, then include a decimal + * point We will do up to 6 fractional digits, and we have + * rounded any inputs to eliminate anything to the right + * of 6 digits anyway. If there are no fractional seconds, + * then do not bother printing a decimal point at all. - + * thomas 2001-09-29 */ - if (fsec != 0) { + if (fsec != 0) + { sprintf((str + strlen(str)), ":%013.10f", sec); TrimTrailingZeros(str); } else - { sprintf((str + strlen(str)), ":%02.0f", sec); - } sprintf((str + strlen(str)), " %04d", tm->tm_year); if ((tzp != NULL) && (tm->tm_isdst >= 0)) { if (*tzn != NULL) - { sprintf((str + strlen(str)), " %.*s", MAXTZLEN, *tzn); - } else { - /* We have a time zone, but no string version. - * Use the numeric form, but be sure to include a leading space - * to avoid formatting something which would be rejected by the - * date/time parser later. - thomas 2001-10-19 + /* + * We have a time zone, but no string version. Use + * the numeric form, but be sure to include a + * leading space to avoid formatting something + * which would be rejected by the date/time parser + * later. - thomas 2001-10-19 */ hour = -(*tzp / 3600); min = ((abs(*tzp) / 60) % 60); @@ -2663,10 +2668,11 @@ EncodeTimeSpan(struct tm * tm, double fsec, int style, char *str) } /* EncodeTimeSpan() */ -void ClearDateCache(bool dummy) +void +ClearDateCache(bool dummy) { - int i; + int i; - for (i=0; i < MAXDATEFIELDS; i++) + for (i = 0; i < MAXDATEFIELDS; i++) datecache[i] = NULL; } diff --git a/src/backend/utils/adt/datum.c b/src/backend/utils/adt/datum.c index 4e278c0489..bb3fafdafb 100644 --- a/src/backend/utils/adt/datum.c +++ b/src/backend/utils/adt/datum.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/datum.c,v 1.21 2001/07/15 22:48:18 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/datum.c,v 1.22 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -133,7 +133,6 @@ datumFree(Datum value, bool typByVal, int typLen) pfree(s); } } - #endif /*------------------------------------------------------------------------- @@ -157,7 +156,6 @@ datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen) if (typByVal) { - /* * just compare the two datums. NOTE: just comparing "len" bytes * will not do the work, because we do not know how these bytes diff --git a/src/backend/utils/adt/encode.c b/src/backend/utils/adt/encode.c index ce197bd19f..e5308aca27 100644 --- a/src/backend/utils/adt/encode.c +++ b/src/backend/utils/adt/encode.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/encode.c,v 1.3 2001/09/30 22:03:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/encode.c,v 1.4 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -20,13 +20,13 @@ struct pg_encoding { - unsigned (*encode_len) (const uint8 *data, unsigned dlen); - unsigned (*decode_len) (const uint8 *data, unsigned dlen); - unsigned (*encode) (const uint8 *data, unsigned dlen, uint8 *res); - unsigned (*decode) (const uint8 *data, unsigned dlen, uint8 *res); + unsigned (*encode_len) (const uint8 *data, unsigned dlen); + unsigned (*decode_len) (const uint8 *data, unsigned dlen); + unsigned (*encode) (const uint8 *data, unsigned dlen, uint8 *res); + unsigned (*decode) (const uint8 *data, unsigned dlen, uint8 *res); }; -static struct pg_encoding * pg_find_encoding(const char *name); +static struct pg_encoding *pg_find_encoding(const char *name); /* * SQL functions. @@ -39,7 +39,9 @@ binary_encode(PG_FUNCTION_ARGS) Datum name = PG_GETARG_DATUM(1); text *result; char *namebuf; - int datalen, resultlen, res; + int datalen, + resultlen, + res; struct pg_encoding *enc; datalen = VARSIZE(data) - VARHDRSZ; @@ -70,8 +72,10 @@ binary_decode(PG_FUNCTION_ARGS) text *data = PG_GETARG_TEXT_P(0); Datum name = PG_GETARG_DATUM(1); bytea *result; - char *namebuf; - int datalen, resultlen, res; + char *namebuf; + int datalen, + resultlen, + res; struct pg_encoding *enc; datalen = VARSIZE(data) - VARHDRSZ; @@ -115,9 +119,9 @@ static const int8 hexlookup[128] = { }; static unsigned -hex_encode(const uint8 * src, unsigned len, uint8 * dst) +hex_encode(const uint8 *src, unsigned len, uint8 *dst) { - const uint8 *end = src + len; + const uint8 *end = src + len; while (src < end) { @@ -131,7 +135,7 @@ hex_encode(const uint8 * src, unsigned len, uint8 * dst) static uint8 get_hex(unsigned c) { - int res = -1; + int res = -1; if (c > 0 && c < 127) res = hexlookup[c]; @@ -139,11 +143,11 @@ get_hex(unsigned c) if (res < 0) elog(ERROR, "Bad hex code: '%c'", c); - return (uint8)res; + return (uint8) res; } static unsigned -hex_decode(const uint8 * src, unsigned len, uint8 * dst) +hex_decode(const uint8 *src, unsigned len, uint8 *dst) { const uint8 *s, *srcend; @@ -172,13 +176,13 @@ hex_decode(const uint8 * src, unsigned len, uint8 * dst) } static unsigned -hex_enc_len(const uint8 * src, unsigned srclen) +hex_enc_len(const uint8 *src, unsigned srclen) { return srclen << 1; } static unsigned -hex_dec_len(const uint8 * src, unsigned srclen) +hex_dec_len(const uint8 *src, unsigned srclen) { return srclen >> 1; } @@ -202,7 +206,7 @@ static const int8 b64lookup[128] = { }; static unsigned -b64_encode(const uint8 * src, unsigned len, uint8 * dst) +b64_encode(const uint8 *src, unsigned len, uint8 *dst) { uint8 *p, *lend = dst + 76; @@ -249,9 +253,9 @@ b64_encode(const uint8 * src, unsigned len, uint8 * dst) } static unsigned -b64_decode(const uint8 * src, unsigned len, uint8 * dst) +b64_decode(const uint8 *src, unsigned len, uint8 *dst) { - const char *srcend = src + len, + const char *srcend = src + len, *s = src; uint8 *p = dst; unsigned c; @@ -281,7 +285,8 @@ b64_decode(const uint8 * src, unsigned len, uint8 * dst) } b = 0; } - else { + else + { b = -1; if (c > 0 && c < 127) b = b64lookup[c]; @@ -311,14 +316,14 @@ b64_decode(const uint8 * src, unsigned len, uint8 * dst) static unsigned -b64_enc_len(const uint8 * src, unsigned srclen) +b64_enc_len(const uint8 *src, unsigned srclen) { /* 3 bytes will be converted to 4, linefeed after 76 chars */ return (srclen + 2) * 4 / 3 + srclen / (76 * 3 / 4); } static unsigned -b64_dec_len(const uint8 * src, unsigned srclen) +b64_dec_len(const uint8 *src, unsigned srclen) { return (srclen * 3) >> 2; } @@ -327,10 +332,10 @@ b64_dec_len(const uint8 * src, unsigned srclen) * Escape * Minimally escape bytea to text. * De-escape text to bytea. - * + * * Only two characters are escaped: * \0 (null) and \\ (backslash) - * + * * De-escapes \\ and any \### octal */ @@ -340,9 +345,9 @@ b64_dec_len(const uint8 * src, unsigned srclen) static unsigned esc_encode(const uint8 *src, unsigned srclen, uint8 *dst) { - const uint8 *end = src + srclen; - uint8 *rp = dst; - int len = 0; + const uint8 *end = src + srclen; + uint8 *rp = dst; + int len = 0; while (src < end) { @@ -377,22 +382,20 @@ esc_encode(const uint8 *src, unsigned srclen, uint8 *dst) static unsigned esc_decode(const uint8 *src, unsigned srclen, uint8 *dst) { - const uint8 *end = src + srclen; - uint8 *rp = dst; - int len = 0; + const uint8 *end = src + srclen; + uint8 *rp = dst; + int len = 0; while (src < end) { if (src[0] != '\\') - { *rp++ = *src++; - } - else if ( src+3 < end && - (src[1] >= '0' && src[1] <= '3') && - (src[2] >= '0' && src[2] <= '7') && - (src[3] >= '0' && src[3] <= '7') ) + else if (src + 3 < end && + (src[1] >= '0' && src[1] <= '3') && + (src[2] >= '0' && src[2] <= '7') && + (src[3] >= '0' && src[3] <= '7')) { - int val; + int val; val = VAL(src[1]); val <<= 3; @@ -401,8 +404,8 @@ esc_decode(const uint8 *src, unsigned srclen, uint8 *dst) *rp++ = val + VAL(src[3]); src += 4; } - else if ( src+1 < end && - (src[1] == '\\') ) + else if (src + 1 < end && + (src[1] == '\\')) { *rp++ = '\\'; src += 2; @@ -410,8 +413,8 @@ esc_decode(const uint8 *src, unsigned srclen, uint8 *dst) else { /* - * One backslash, not followed by ### valid octal. - * Should never get here, since esc_dec_len does same check. + * One backslash, not followed by ### valid octal. Should + * never get here, since esc_dec_len does same check. */ elog(ERROR, "decode: Bad input string for type bytea"); } @@ -425,8 +428,8 @@ esc_decode(const uint8 *src, unsigned srclen, uint8 *dst) static unsigned esc_enc_len(const uint8 *src, unsigned srclen) { - const uint8 *end = src + srclen; - int len = 0; + const uint8 *end = src + srclen; + int len = 0; while (src < end) { @@ -446,27 +449,25 @@ esc_enc_len(const uint8 *src, unsigned srclen) static unsigned esc_dec_len(const uint8 *src, unsigned srclen) { - const uint8 *end = src + srclen; - int len = 0; + const uint8 *end = src + srclen; + int len = 0; while (src < end) { if (src[0] != '\\') - { src++; - } - else if ( src+3 < end && - (src[1] >= '0' && src[1] <= '3') && - (src[2] >= '0' && src[2] <= '7') && - (src[3] >= '0' && src[3] <= '7') ) + else if (src + 3 < end && + (src[1] >= '0' && src[1] <= '3') && + (src[2] >= '0' && src[2] <= '7') && + (src[3] >= '0' && src[3] <= '7')) { /* * backslash + valid octal */ src += 4; } - else if ( src+1 < end && - (src[1] == '\\') ) + else if (src + 1 < end && + (src[1] == '\\')) { /* * two backslashes = backslash @@ -490,20 +491,43 @@ esc_dec_len(const uint8 *src, unsigned srclen) * Common */ -static struct { +static struct +{ const char *name; struct pg_encoding enc; -} enclist[] = { - {"hex", { hex_enc_len, hex_dec_len, hex_encode, hex_decode }}, - {"base64", { b64_enc_len, b64_dec_len, b64_encode, b64_decode }}, - {"escape", { esc_enc_len, esc_dec_len, esc_encode, esc_decode }}, - {NULL, { NULL, NULL, NULL, NULL } } +} enclist[] = + +{ + { + "hex", + { + hex_enc_len, hex_dec_len, hex_encode, hex_decode + } + }, + { + "base64", + { + b64_enc_len, b64_dec_len, b64_encode, b64_decode + } + }, + { + "escape", + { + esc_enc_len, esc_dec_len, esc_encode, esc_decode + } + }, + { + NULL, + { + NULL, NULL, NULL, NULL + } + } }; static struct pg_encoding * pg_find_encoding(const char *name) { - int i; + int i; for (i = 0; enclist[i].name; i++) if (strcasecmp(enclist[i].name, name) == 0) diff --git a/src/backend/utils/adt/float.c b/src/backend/utils/adt/float.c index 8e5408af31..c7dc220d07 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.74 2001/06/07 00:09:29 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/float.c,v 1.75 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -71,7 +71,6 @@ #ifndef atof extern double atof(const char *p); - #endif #ifndef HAVE_CBRT @@ -81,7 +80,6 @@ static double cbrt(double x); #else #if !defined(nextstep) extern double cbrt(double x); - #endif #endif /* HAVE_CBRT */ @@ -91,9 +89,7 @@ static double rint(double x); #else extern double rint(double x); - #endif /* HAVE_RINT */ - #endif /* NeXT check */ @@ -140,7 +136,6 @@ static void CheckFloat8Val(double val); static void CheckFloat4Val(double val) { - /* * defining unsafe floats's will make float4 and float8 ops faster at * the cost of safety, of course! @@ -165,7 +160,6 @@ CheckFloat4Val(double val) static void CheckFloat8Val(double val) { - /* * defining unsafe floats's will make float4 and float8 ops faster at * the cost of safety, of course! @@ -344,6 +338,7 @@ Datum float4up(PG_FUNCTION_ARGS) { float4 arg = PG_GETARG_FLOAT4(0); + PG_RETURN_FLOAT4(arg); } @@ -410,6 +405,7 @@ Datum float8up(PG_FUNCTION_ARGS) { float8 arg = PG_GETARG_FLOAT8(0); + PG_RETURN_FLOAT8(arg); } @@ -578,9 +574,9 @@ static int float4_cmp_internal(float4 a, float4 b) { /* - * We consider all NANs to be equal and larger than any non-NAN. - * This is somewhat arbitrary; the important thing is to have a - * consistent sort order. + * We consider all NANs to be equal and larger than any non-NAN. This + * is somewhat arbitrary; the important thing is to have a consistent + * sort order. */ if (isnan(a)) { @@ -674,9 +670,9 @@ static int float8_cmp_internal(float8 a, float8 b) { /* - * We consider all NANs to be equal and larger than any non-NAN. - * This is somewhat arbitrary; the important thing is to have a - * consistent sort order. + * We consider all NANs to be equal and larger than any non-NAN. This + * is somewhat arbitrary; the important thing is to have a consistent + * sort order. */ if (isnan(a)) { @@ -1479,7 +1475,6 @@ setseed(PG_FUNCTION_ARGS) static float8 * check_float8_array(ArrayType *transarray, const char *caller) { - /* * We expect the input to be a 3-element float array; verify that. We * don't need to use deconstruct_array() since the array data is just @@ -1974,7 +1969,6 @@ rint(double x) w = TWO52[sx] + x; return w - TWO52[sx]; } - #endif /* !HAVE_RINT */ #ifndef HAVE_CBRT @@ -1987,5 +1981,4 @@ cbrt(double x) return isneg ? -tmpres : tmpres; } - #endif /* !HAVE_CBRT */ diff --git a/src/backend/utils/adt/format_type.c b/src/backend/utils/adt/format_type.c index f2cf46200d..af928933dd 100644 --- a/src/backend/utils/adt/format_type.c +++ b/src/backend/utils/adt/format_type.c @@ -8,7 +8,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/format_type.c,v 1.20 2001/10/23 20:12:54 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/format_type.c,v 1.21 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -216,8 +216,8 @@ format_type_internal(Oid type_oid, int32 typemod, bool allow_invalid) case INTERVALOID: if (with_typemod) { - int fields = typemod >> 16; - int precision = typemod & 0xFFFF; + int fields = typemod >> 16; + int precision = typemod & 0xFFFF; const char *fieldstr; switch (fields) diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c index d517eb6818..0957783a4a 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.41 2001/09/28 08:09:11 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/formatting.c,v 1.42 2001/10/25 05:49:44 momjian Exp $ * * * Portions Copyright (c) 1999-2000, PostgreSQL Global Development Group @@ -44,9 +44,9 @@ * * Karel Zak * - * TODO - * - better number building (formatting) / parsing, now it isn't - * ideal code + * TODO + * - better number building (formatting) / parsing, now it isn't + * ideal code * - use Assert() * - add support for abstime * - add support for roman number to standard number conversion @@ -374,11 +374,11 @@ typedef struct yyyy, yyy, yy, - y, + y, bc, iw, ww, - w, + w, cc, q, j, @@ -414,13 +414,13 @@ typedef struct */ typedef struct TmToChar { - struct tm tm; /* classic 'tm' struct */ - double fsec; /* milliseconds */ - char *tzn; /* timezone */ + struct tm tm; /* classic 'tm' struct */ + double fsec; /* milliseconds */ + char *tzn; /* timezone */ } TmToChar; #define tmtcTm(_X) (&(_X)->tm) -#define tmtcTzn(_X) ((_X)->tzn) +#define tmtcTzn(_X) ((_X)->tzn) #define tmtcFsec(_X) ((_X)->fsec) #define ZERO_tm( _X ) \ @@ -521,132 +521,132 @@ static KeySuffix DCH_suff[] = { typedef enum { - DCH_A_D, - DCH_A_M, - DCH_AD, - DCH_AM, - DCH_B_C, - DCH_BC, - DCH_CC, - DCH_DAY, - DCH_DDD, - DCH_DD, - DCH_DY, - DCH_Day, - DCH_Dy, - DCH_D, - DCH_FX, /* global suffix */ - DCH_HH24, - DCH_HH12, - DCH_HH, - DCH_IW, - DCH_J, - DCH_MI, - DCH_MM, - DCH_MONTH, - DCH_MON, - DCH_MS, - DCH_Month, - DCH_Mon, - DCH_P_M, - DCH_PM, - DCH_Q, - DCH_RM, - DCH_SSSS, - DCH_SS, - DCH_TZ, - DCH_US, - DCH_WW, - DCH_W, - DCH_Y_YYY, - DCH_YYYY, - DCH_YYY, - DCH_YY, - DCH_Y, - DCH_a_d, - DCH_a_m, - DCH_ad, - DCH_am, - DCH_b_c, - DCH_bc, - DCH_cc, - DCH_day, - DCH_ddd, - DCH_dd, - DCH_dy, - DCH_d, - DCH_fx, - DCH_hh24, - DCH_hh12, - DCH_hh, - DCH_iw, - DCH_j, - DCH_mi, - DCH_mm, - DCH_month, - DCH_mon, - DCH_ms, - DCH_p_m, - DCH_pm, - DCH_q, - DCH_rm, - DCH_ssss, - DCH_ss, - DCH_tz, - DCH_us, - DCH_ww, - DCH_w, - DCH_y_yyy, - DCH_yyyy, - DCH_yyy, - DCH_yy, - DCH_y, + DCH_A_D, + DCH_A_M, + DCH_AD, + DCH_AM, + DCH_B_C, + DCH_BC, + DCH_CC, + DCH_DAY, + DCH_DDD, + DCH_DD, + DCH_DY, + DCH_Day, + DCH_Dy, + DCH_D, + DCH_FX, /* global suffix */ + DCH_HH24, + DCH_HH12, + DCH_HH, + DCH_IW, + DCH_J, + DCH_MI, + DCH_MM, + DCH_MONTH, + DCH_MON, + DCH_MS, + DCH_Month, + DCH_Mon, + DCH_P_M, + DCH_PM, + DCH_Q, + DCH_RM, + DCH_SSSS, + DCH_SS, + DCH_TZ, + DCH_US, + DCH_WW, + DCH_W, + DCH_Y_YYY, + DCH_YYYY, + DCH_YYY, + DCH_YY, + DCH_Y, + DCH_a_d, + DCH_a_m, + DCH_ad, + DCH_am, + DCH_b_c, + DCH_bc, + DCH_cc, + DCH_day, + DCH_ddd, + DCH_dd, + DCH_dy, + DCH_d, + DCH_fx, + DCH_hh24, + DCH_hh12, + DCH_hh, + DCH_iw, + DCH_j, + DCH_mi, + DCH_mm, + DCH_month, + DCH_mon, + DCH_ms, + DCH_p_m, + DCH_pm, + DCH_q, + DCH_rm, + DCH_ssss, + DCH_ss, + DCH_tz, + DCH_us, + DCH_ww, + DCH_w, + DCH_y_yyy, + DCH_yyyy, + DCH_yyy, + DCH_yy, + DCH_y, /* last */ - _DCH_last_ + _DCH_last_ } DCH_poz; typedef enum { - NUM_COMMA, - NUM_DEC, - NUM_0, - NUM_9, - NUM_B, - NUM_C, - NUM_D, - NUM_E, - NUM_FM, - NUM_G, - NUM_L, - NUM_MI, - NUM_PL, - NUM_PR, - NUM_RN, - NUM_SG, - NUM_SP, - NUM_S, - NUM_TH, - NUM_V, - NUM_b, - NUM_c, - NUM_d, - NUM_e, - NUM_fm, - NUM_g, - NUM_l, - NUM_mi, - NUM_pl, - NUM_pr, - NUM_rn, - NUM_sg, - NUM_sp, - NUM_s, - NUM_th, - NUM_v, + NUM_COMMA, + NUM_DEC, + NUM_0, + NUM_9, + NUM_B, + NUM_C, + NUM_D, + NUM_E, + NUM_FM, + NUM_G, + NUM_L, + NUM_MI, + NUM_PL, + NUM_PR, + NUM_RN, + NUM_SG, + NUM_SP, + NUM_S, + NUM_TH, + NUM_V, + NUM_b, + NUM_c, + NUM_d, + NUM_e, + NUM_fm, + NUM_g, + NUM_l, + NUM_mi, + NUM_pl, + NUM_pr, + NUM_rn, + NUM_sg, + NUM_sp, + NUM_s, + NUM_th, + NUM_v, /* last */ - _NUM_last_ + _NUM_last_ } NUM_poz; /* ---------- @@ -689,7 +689,7 @@ static KeyWord DCH_keywords[] = { {"SSSS", 4, dch_time, DCH_SSSS, TRUE}, /* S */ {"SS", 2, dch_time, DCH_SS, TRUE}, {"TZ", 2, dch_time, DCH_TZ, FALSE}, /* T */ - {"US", 2, dch_time, DCH_US, TRUE}, /* U */ + {"US", 2, dch_time, DCH_US, TRUE}, /* U */ {"WW", 2, dch_date, DCH_WW, TRUE}, /* W */ {"W", 1, dch_date, DCH_W, TRUE}, {"Y,YYY", 5, dch_date, DCH_Y_YYY, TRUE}, /* Y */ @@ -883,12 +883,11 @@ static char *DCH_processor(FormatNode *node, char *inout, int flag, void *data); #ifdef DEBUG_TO_FROM_CHAR static void dump_index(KeyWord *k, int *index); static void dump_node(FormatNode *node, int max); - #endif static char *get_th(char *num, int type); static char *str_numth(char *dest, char *num, int type); -static int strdigits_len(char *str); +static int strdigits_len(char *str); static char *str_toupper(char *buff); static char *str_tolower(char *buff); @@ -1196,7 +1195,6 @@ parse_format(FormatNode *node, char *str, KeyWord *kw, } else if (*str) { - /* * Special characters '\' and '"' */ @@ -1299,7 +1297,6 @@ DCH_processor(FormatNode *node, char *inout, int flag, void *data) } else { - /* * Remove to output char from input in TO_CHAR */ @@ -1308,7 +1305,6 @@ DCH_processor(FormatNode *node, char *inout, int flag, void *data) else { - /* * Skip blank space in FROM_CHAR's input */ @@ -1364,8 +1360,7 @@ dump_node(FormatNode *node, int max) } } - -#endif /* DEBUG */ +#endif /* DEBUG */ /***************************************************************************** * Private utils @@ -1571,8 +1566,7 @@ dump_index(KeyWord *k, int *index) elog(DEBUG_elog_output, "\n\t\tUsed positions: %d,\n\t\tFree positions: %d", count, free_i); } - -#endif /* DEBUG */ +#endif /* DEBUG */ /* ---------- * Skip TM / th in FROM_CHAR @@ -1630,10 +1624,10 @@ is_next_separator(FormatNode *n) static int strdigits_len(char *str) { - char *p = str; - int len = 0; - - while (*p && isdigit((unsigned char ) *p) && len <= DCH_MAX_ITEM_SIZ) + char *p = str; + int len = 0; + + while (*p && isdigit((unsigned char) *p) && len <= DCH_MAX_ITEM_SIZ) { len++; p++; @@ -1652,12 +1646,12 @@ strdigits_len(char *str) static int dch_time(int arg, char *inout, int suf, int flag, FormatNode *node, void *data) { - char *p_inout = inout; - struct tm *tm = NULL; - TmFromChar *tmfc = NULL; - TmToChar *tmtc = NULL; + char *p_inout = inout; + struct tm *tm = NULL; + TmFromChar *tmfc = NULL; + TmToChar *tmtc = NULL; - if (flag==TO_CHAR) + if (flag == TO_CHAR) { tmtc = (TmToChar *) data; tm = tmtcTm(tmtc); @@ -1850,7 +1844,7 @@ dch_time(int arg, char *inout, int suf, int flag, FormatNode *node, void *data) } } break; - case DCH_MS: /* millisecond */ + case DCH_MS: /* millisecond */ if (flag == TO_CHAR) { sprintf(inout, "%03d", (int) rint(tmtc->fsec * 1000)); @@ -1864,34 +1858,39 @@ dch_time(int arg, char *inout, int suf, int flag, FormatNode *node, void *data) } else if (flag == FROM_CHAR) { - int len, x; - + int len, + x; + if (is_next_separator(node)) { sscanf(inout, "%d", &tmfc->ms); len = x = strdigits_len(inout); } - else + else { sscanf(inout, "%03d", &tmfc->ms); x = strdigits_len(inout); - len = x = x > 3 ? 3 : x; - } - - /* 25 is 0.25 and 250 is 0.25 too; - * 025 is 0.025 and not 0.25 + len = x = x > 3 ? 3 : x; + } + + /* + * 25 is 0.25 and 250 is 0.25 too; 025 is 0.025 and not + * 0.25 + */ + tmfc->ms *= x == 1 ? 100 : + x == 2 ? 10 : 1; + + /* + * elog(NOTICE, "X: %d, MS: %d, LEN: %d", x, tmfc->ms, + * len); */ - tmfc->ms *= x==1 ? 100 : - x==2 ? 10 : 1; - - /* elog(NOTICE, "X: %d, MS: %d, LEN: %d", x, tmfc->ms, len); */ return len - 1 + SKIP_THth(suf); } break; - case DCH_US: /* microsecond */ + case DCH_US: /* microsecond */ if (flag == TO_CHAR) { - sprintf(inout, "%06d", (int)rint(tmtc->fsec * 1000000)); + sprintf(inout, "%06d", (int) rint(tmtc->fsec * 1000000)); if (S_THth(suf)) str_numth(p_inout, inout, S_TH_TYPE(suf)); if (S_THth(suf)) @@ -1901,27 +1900,31 @@ dch_time(int arg, char *inout, int suf, int flag, FormatNode *node, void *data) } else if (flag == FROM_CHAR) { - int len, x; - + int len, + x; + if (is_next_separator(node)) { sscanf(inout, "%d", &tmfc->us); len = x = strdigits_len(inout); } - else + else { sscanf(inout, "%06d", &tmfc->us); x = strdigits_len(inout); - len = x = x > 6 ? 6 : x; - } - - tmfc->us *= x==1 ? 100000 : - x==2 ? 10000 : - x==3 ? 1000 : - x==4 ? 100 : - x==5 ? 10 : 1; - - /* elog(NOTICE, "X: %d, US: %d, LEN: %d", x, tmfc->us, len); */ + len = x = x > 6 ? 6 : x; + } + + tmfc->us *= x == 1 ? 100000 : + x == 2 ? 10000 : + x == 3 ? 1000 : + x == 4 ? 100 : + x == 5 ? 10 : 1; + + /* + * elog(NOTICE, "X: %d, US: %d, LEN: %d", x, tmfc->us, + * len); + */ return len - 1 + SKIP_THth(suf); } break; @@ -1953,7 +1956,7 @@ dch_time(int arg, char *inout, int suf, int flag, FormatNode *node, void *data) case DCH_TZ: if (flag == TO_CHAR && tmtcTzn(tmtc)) { - int siz = strlen(tmtcTzn(tmtc)); + int siz = strlen(tmtcTzn(tmtc)); if (arg == DCH_TZ) strcpy(inout, tmtcTzn(tmtc)); @@ -1990,13 +1993,15 @@ do { \ static int dch_date(int arg, char *inout, int suf, int flag, FormatNode *node, void *data) { - char buff[DCH_CACHE_SIZE], *p_inout; - int i, len; - struct tm *tm = NULL; - TmFromChar *tmfc = NULL; - TmToChar *tmtc = NULL; + char buff[DCH_CACHE_SIZE], + *p_inout; + int i, + len; + struct tm *tm = NULL; + TmFromChar *tmfc = NULL; + TmToChar *tmtc = NULL; - if (flag==TO_CHAR) + if (flag == TO_CHAR) { tmtc = (TmToChar *) data; tm = tmtcTm(tmtc); @@ -2394,7 +2399,7 @@ dch_date(int arg, char *inout, int suf, int flag, FormatNode *node, void *data) sscanf(inout, "%d,%03d", &cc, &tmfc->yyyy); tmfc->yyyy += (cc * 1000); - return strdigits_len(inout) + 3 + SKIP_THth(suf); + return strdigits_len(inout) + 3 + SKIP_THth(suf); } break; case DCH_YYYY: @@ -2648,10 +2653,11 @@ static text * datetime_to_char_body(TmToChar *tmtc, text *fmt) { FormatNode *format; - struct tm *tm = NULL; - char *str_fmt, *result; - bool incache; - int len = VARSIZE(fmt) - VARHDRSZ; + struct tm *tm = NULL; + char *str_fmt, + *result; + bool incache; + int len = VARSIZE(fmt) - VARHDRSZ; tm = tmtcTm(tmtc); tm->tm_wday = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1) % 7; @@ -2671,7 +2677,8 @@ datetime_to_char_body(TmToChar *tmtc, text *fmt) /* * Allocate new memory if format picture is bigger than static cache - * and not use cache (call parser always) - incache=FALSE show this variant + * and not use cache (call parser always) - incache=FALSE show this + * variant */ if (len > DCH_CACHE_SIZE) { @@ -2686,11 +2693,11 @@ datetime_to_char_body(TmToChar *tmtc, text *fmt) } else { - /* * Use cache buffers */ DCHCacheEntry *ent; + incache = TRUE; if ((ent = DCH_cache_search(str_fmt)) == NULL) @@ -2730,7 +2737,7 @@ datetime_to_char_body(TmToChar *tmtc, text *fmt) pfree(result); else { - text *res = (text *) palloc(len + 1 + VARHDRSZ); + text *res = (text *) palloc(len + 1 + VARHDRSZ); memcpy(VARDATA(res), result, len); VARATT_SIZEP(res) = len + VARHDRSZ; @@ -2750,12 +2757,13 @@ datetime_to_char_body(TmToChar *tmtc, text *fmt) Datum timestamp_to_char(PG_FUNCTION_ARGS) { - Timestamp dt = PG_GETARG_TIMESTAMP(0); - text *fmt = PG_GETARG_TEXT_P(1), *res; - TmToChar tmtc; - int r = 0; + Timestamp dt = PG_GETARG_TIMESTAMP(0); + text *fmt = PG_GETARG_TEXT_P(1), + *res; + TmToChar tmtc; + int r = 0; - if ((VARSIZE(fmt) - VARHDRSZ) <=0 || TIMESTAMP_NOT_FINITE(dt)) + if ((VARSIZE(fmt) - VARHDRSZ) <= 0 || TIMESTAMP_NOT_FINITE(dt)) PG_RETURN_NULL(); ZERO_tmtc(&tmtc); @@ -2765,7 +2773,7 @@ timestamp_to_char(PG_FUNCTION_ARGS) if (r != 0) elog(ERROR, "to_char(): Unable to convert timestamp to tm"); - if (!(res=datetime_to_char_body(&tmtc, fmt))) + if (!(res = datetime_to_char_body(&tmtc, fmt))) PG_RETURN_NULL(); PG_RETURN_TEXT_P(res); @@ -2775,11 +2783,13 @@ Datum timestamptz_to_char(PG_FUNCTION_ARGS) { TimestampTz dt = PG_GETARG_TIMESTAMP(0); - text *fmt = PG_GETARG_TEXT_P(1), *res; - TmToChar tmtc; - int tz, r = 0; + text *fmt = PG_GETARG_TEXT_P(1), + *res; + TmToChar tmtc; + int tz, + r = 0; - if ((VARSIZE(fmt) - VARHDRSZ) <=0 || TIMESTAMP_NOT_FINITE(dt)) + if ((VARSIZE(fmt) - VARHDRSZ) <= 0 || TIMESTAMP_NOT_FINITE(dt)) PG_RETURN_NULL(); ZERO_tmtc(&tmtc); @@ -2789,7 +2799,7 @@ timestamptz_to_char(PG_FUNCTION_ARGS) if (r != 0) elog(ERROR, "to_char(): Unable to convert timestamp to tm"); - if (!(res=datetime_to_char_body(&tmtc, fmt))) + if (!(res = datetime_to_char_body(&tmtc, fmt))) PG_RETURN_NULL(); PG_RETURN_TEXT_P(res); @@ -2803,9 +2813,10 @@ timestamptz_to_char(PG_FUNCTION_ARGS) Datum interval_to_char(PG_FUNCTION_ARGS) { - Interval *it = PG_GETARG_INTERVAL_P(0); - text *fmt = PG_GETARG_TEXT_P(1), *res; - TmToChar tmtc; + Interval *it = PG_GETARG_INTERVAL_P(0); + text *fmt = PG_GETARG_TEXT_P(1), + *res; + TmToChar tmtc; if ((VARSIZE(fmt) - VARHDRSZ) <= 0) PG_RETURN_NULL(); @@ -2815,7 +2826,7 @@ interval_to_char(PG_FUNCTION_ARGS) if (interval2tm(*it, tmtcTm(&tmtc), &tmtcFsec(&tmtc)) != 0) PG_RETURN_NULL(); - if (!(res=datetime_to_char_body(&tmtc, fmt))) + if (!(res = datetime_to_char_body(&tmtc, fmt))) PG_RETURN_NULL(); PG_RETURN_TEXT_P(res); @@ -2831,19 +2842,21 @@ interval_to_char(PG_FUNCTION_ARGS) Datum to_timestamp(PG_FUNCTION_ARGS) { - text *date_txt = PG_GETARG_TEXT_P(0); - text *fmt = PG_GETARG_TEXT_P(1); - - Timestamp result; + text *date_txt = PG_GETARG_TEXT_P(0); + text *fmt = PG_GETARG_TEXT_P(1); + + Timestamp result; FormatNode *format; - TmFromChar tmfc; - - bool incache; - char *str; - char *date_str; - int len, date_len, tz = 0; - struct tm tm; - double fsec = 0; + TmFromChar tmfc; + + bool incache; + char *str; + char *date_str; + int len, + date_len, + tz = 0; + struct tm tm; + double fsec = 0; ZERO_tm(&tm); ZERO_tmfc(&tmfc); @@ -2858,7 +2871,7 @@ to_timestamp(PG_FUNCTION_ARGS) /* * Allocate new memory if format picture is bigger than static - * cache and not use cache (call parser always) - incache=FALSE + * cache and not use cache (call parser always) - incache=FALSE * show this variant */ if (len > DCH_CACHE_SIZE) @@ -2873,11 +2886,11 @@ to_timestamp(PG_FUNCTION_ARGS) } else { - /* * Use cache buffers */ DCHCacheEntry *ent; + incache = 0; if ((ent = DCH_cache_search(str)) == NULL) @@ -2924,7 +2937,7 @@ to_timestamp(PG_FUNCTION_ARGS) pfree(format); } - DEBUG_TMFC(&tmfc); + DEBUG_TMFC(&tmfc); /* * Convert values that user define for FROM_CHAR @@ -2932,7 +2945,7 @@ to_timestamp(PG_FUNCTION_ARGS) */ if (tmfc.ssss) { - int x = tmfc.ssss; + int x = tmfc.ssss; tm.tm_hour = x / 3600; x %= 3600; @@ -2994,7 +3007,6 @@ to_timestamp(PG_FUNCTION_ARGS) else if (tmfc.y) { - /* * 1-digit year: always +2000 */ @@ -3096,7 +3108,7 @@ to_timestamp(PG_FUNCTION_ARGS) DEBUG_TM(&tm); tz = DetermineLocalTimeZone(&tm); - + if (tm2timestamp(&tm, fsec, &tz, &result) != 0) elog(ERROR, "to_timestamp(): can't convert 'tm' to timestamp."); @@ -3111,7 +3123,6 @@ to_timestamp(PG_FUNCTION_ARGS) Datum to_date(PG_FUNCTION_ARGS) { - /* * Quick hack: since our inputs are just like to_timestamp, hand over * the whole input info struct... @@ -3173,7 +3184,6 @@ NUM_cache_getnew(char *str) for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++) { - /* * entry removed via NUM_cache_remove() can be used here */ @@ -3291,7 +3301,6 @@ NUM_cache(int len, NUMDesc *Num, char *pars_str, int *flag) } else { - /* * Use cache buffers */ @@ -3453,7 +3462,6 @@ NUM_prepare_locale(NUMProc *Np) } else { - #endif /* @@ -3678,7 +3686,6 @@ NUM_numpart_to_char(NUMProc *Np, int id) #endif if (IS_LSIGN(Np->Num)) { - /* * Write locale SIGN */ @@ -3713,7 +3720,6 @@ NUM_numpart_to_char(NUMProc *Np, int id) (Np->num_curr == Np->num_count + (Np->num_pre ? 1 : 0) + (IS_DECIMAL(Np->Num) ? 1 : 0))) { - /* * Write close BRACKET */ @@ -3734,7 +3740,6 @@ NUM_numpart_to_char(NUMProc *Np, int id) if (Np->num_curr < Np->num_pre && (Np->Num->zero_start > Np->num_curr || !IS_ZERO(Np->Num))) { - /* * Write blank space */ @@ -3752,7 +3757,6 @@ NUM_numpart_to_char(NUMProc *Np, int id) Np->num_curr < Np->num_pre && Np->Num->zero_start <= Np->num_curr) { - /* * Write ZERO */ @@ -3766,7 +3770,6 @@ NUM_numpart_to_char(NUMProc *Np, int id) } else { - /* * Write Decinal point */ @@ -3796,7 +3799,6 @@ NUM_numpart_to_char(NUMProc *Np, int id) } else { - /* * Write Digits */ @@ -3946,7 +3948,6 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, if (!Np->sign_wrote) { - /* * Set SING position */ @@ -4029,7 +4030,6 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, if (Np->type == FROM_CHAR) { - /* * Check non-string inout end */ @@ -4042,7 +4042,6 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, */ if (n->type == NODE_TYPE_ACTION) { - /* * Create/reading digit/zero/blank/sing */ @@ -4143,7 +4142,7 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, else Np->inout_p += sprintf(Np->inout_p, "%15s", Np->number_p) - 1; break; - + case NUM_rn: if (IS_FILLMODE(Np->Num)) { @@ -4228,7 +4227,6 @@ NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number, } else { - /* * Remove to output char from input in TO_CHAR */ diff --git a/src/backend/utils/adt/geo_ops.c b/src/backend/utils/adt/geo_ops.c index 4590500eca..28a04d0725 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.59 2001/10/13 17:40:24 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/geo_ops.c,v 1.60 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -484,11 +484,11 @@ box_ov(BOX *box1, BOX *box2) FPle(box1->low.x, box2->high.x)) || (FPge(box2->high.x, box1->high.x) && FPle(box2->low.x, box1->high.x))) - && - ((FPge(box1->high.y, box2->high.y) && - FPle(box1->low.y, box2->high.y)) || - (FPge(box2->high.y, box1->high.y) && - FPle(box2->low.y, box1->high.y))); + && + ((FPge(box1->high.y, box2->high.y) && + FPle(box1->low.y, box2->high.y)) || + (FPge(box2->high.y, box1->high.y) && + FPle(box2->low.y, box1->high.y))); } /* box_overleft - is the right edge of box1 to the left of @@ -811,7 +811,6 @@ line_in(PG_FUNCTION_ARGS) { #ifdef ENABLE_LINE_TYPE char *str = PG_GETARG_CSTRING(0); - #endif LINE *line; @@ -840,7 +839,6 @@ line_out(PG_FUNCTION_ARGS) { #ifdef ENABLE_LINE_TYPE LINE *line = PG_GETARG_LINE_P(0); - #endif char *result; @@ -1403,28 +1401,28 @@ path_inter(PG_FUNCTION_ARGS) /* pairwise check lseg intersections */ for (i = 0; i < p1->npts; i++) { - int iprev; + int iprev; if (i > 0) - iprev = i-1; + iprev = i - 1; else { if (!p1->closed) continue; - iprev = p1->npts-1; /* include the closure segment */ + iprev = p1->npts - 1; /* include the closure segment */ } for (j = 0; j < p2->npts; j++) { - int jprev; + int jprev; if (j > 0) - jprev = j-1; + jprev = j - 1; else { if (!p2->closed) continue; - jprev = p2->npts-1; /* include the closure segment */ + jprev = p2->npts - 1; /* include the closure segment */ } statlseg_construct(&seg1, &p1->p[iprev], &p1->p[i]); @@ -1457,28 +1455,28 @@ path_distance(PG_FUNCTION_ARGS) for (i = 0; i < p1->npts; i++) { - int iprev; + int iprev; if (i > 0) - iprev = i-1; + iprev = i - 1; else { if (!p1->closed) continue; - iprev = p1->npts-1; /* include the closure segment */ + iprev = p1->npts - 1; /* include the closure segment */ } for (j = 0; j < p2->npts; j++) { - int jprev; + int jprev; if (j > 0) - jprev = j-1; + jprev = j - 1; else { if (!p2->closed) continue; - jprev = p2->npts-1; /* include the closure segment */ + jprev = p2->npts - 1; /* include the closure segment */ } statlseg_construct(&seg1, &p1->p[iprev], &p1->p[i]); @@ -1515,15 +1513,15 @@ path_length(PG_FUNCTION_ARGS) for (i = 0; i < path->npts; i++) { - int iprev; + int iprev; if (i > 0) - iprev = i-1; + iprev = i - 1; else { if (!path->closed) continue; - iprev = path->npts-1; /* include the closure segment */ + iprev = path->npts - 1; /* include the closure segment */ } result += point_dt(&path->p[iprev], &path->p[i]); @@ -2114,7 +2112,7 @@ static double dist_pl_internal(Point *pt, LINE *line) { return (line->A * pt->x + line->B * pt->y + line->C) / - HYPOT(line->A, line->B); + HYPOT(line->A, line->B); } Datum @@ -2216,15 +2214,16 @@ dist_ppath(PG_FUNCTION_ARGS) */ for (i = 0; i < path->npts; i++) { - int iprev; + int iprev; if (i > 0) - iprev = i-1; + iprev = i - 1; else { if (!path->closed) continue; - iprev = path->npts-1; /* include the closure segment */ + iprev = path->npts - 1; /* include the closure + * segment */ } statlseg_construct(&lseg, &path->p[iprev], &path->p[i]); @@ -2307,7 +2306,6 @@ dist_lb(PG_FUNCTION_ARGS) #ifdef NOT_USED LINE *line = PG_GETARG_LINE_P(0); BOX *box = PG_GETARG_BOX_P(1); - #endif /* think about this one for a while */ @@ -2830,7 +2828,6 @@ close_lb(PG_FUNCTION_ARGS) #ifdef NOT_USED LINE *line = PG_GETARG_LINE_P(0); BOX *box = PG_GETARG_BOX_P(1); - #endif /* think about this one for a while */ @@ -3430,7 +3427,6 @@ poly_distance(PG_FUNCTION_ARGS) #ifdef NOT_USED POLYGON *polya = PG_GETARG_POLYGON_P(0); POLYGON *polyb = PG_GETARG_POLYGON_P(1); - #endif elog(ERROR, "poly_distance not implemented"); @@ -3737,7 +3733,6 @@ path_center(PG_FUNCTION_ARGS) { #ifdef NOT_USED PATH *path = PG_GETARG_PATH_P(0); - #endif elog(ERROR, "path_center not implemented"); diff --git a/src/backend/utils/adt/inet_net_ntop.c b/src/backend/utils/adt/inet_net_ntop.c index 7332930095..c0d782ec08 100644 --- a/src/backend/utils/adt/inet_net_ntop.c +++ b/src/backend/utils/adt/inet_net_ntop.c @@ -16,8 +16,7 @@ */ #if defined(LIBC_SCCS) && !defined(lint) -static const char rcsid[] = "$Id: inet_net_ntop.c,v 1.10 2001/03/22 03:59:51 momjian Exp $"; - +static const char rcsid[] = "$Id: inet_net_ntop.c,v 1.11 2001/10/25 05:49:44 momjian Exp $"; #endif #include <sys/types.h> @@ -56,7 +55,7 @@ inet_cidr_ntop(int af, const void *src, int bits, char *dst, size_t size) { switch (af) { - case AF_INET: + case AF_INET: return (inet_cidr_ntop_ipv4(src, bits, dst, size)); default: errno = EAFNOSUPPORT; @@ -157,7 +156,7 @@ inet_net_ntop(int af, const void *src, int bits, char *dst, size_t size) { switch (af) { - case AF_INET: + case AF_INET: return (inet_net_ntop_ipv4(src, bits, dst, size)); default: errno = EAFNOSUPPORT; diff --git a/src/backend/utils/adt/inet_net_pton.c b/src/backend/utils/adt/inet_net_pton.c index 3784bf04be..785d333f9d 100644 --- a/src/backend/utils/adt/inet_net_pton.c +++ b/src/backend/utils/adt/inet_net_pton.c @@ -16,8 +16,7 @@ */ #if defined(LIBC_SCCS) && !defined(lint) -static const char rcsid[] = "$Id: inet_net_pton.c,v 1.12 2000/12/03 20:45:36 tgl Exp $"; - +static const char rcsid[] = "$Id: inet_net_pton.c,v 1.13 2001/10/25 05:49:44 momjian Exp $"; #endif #include <sys/types.h> @@ -64,10 +63,10 @@ inet_net_pton(int af, const char *src, void *dst, size_t size) { switch (af) { - case AF_INET: + case AF_INET: return size == -1 ? - inet_net_pton_ipv4(src, dst) : - inet_cidr_pton_ipv4(src, dst, size); + inet_net_pton_ipv4(src, dst) : + inet_cidr_pton_ipv4(src, dst, size); default: errno = EAFNOSUPPORT; return (-1); diff --git a/src/backend/utils/adt/int8.c b/src/backend/utils/adt/int8.c index 8d8f9ed642..41a6061588 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.33 2001/09/07 01:33:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/int8.c,v 1.34 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -67,7 +67,7 @@ int8in(PG_FUNCTION_ARGS) * Do our own scan, rather than relying on sscanf which might be * broken for long long. */ - while (*ptr && isspace((unsigned char) *ptr)) /* skip leading spaces */ + while (*ptr && isspace((unsigned char) *ptr)) /* skip leading spaces */ ptr++; if (*ptr == '-') /* handle sign */ sign = -1, ptr++; diff --git a/src/backend/utils/adt/like.c b/src/backend/utils/adt/like.c index f3f8b9854e..2969f15891 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.47 2001/10/04 02:15:47 ishii Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/like.c,v 1.48 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -35,14 +35,14 @@ static int MatchText(unsigned char *t, int tlen, static int MatchTextIC(unsigned char *t, int tlen, unsigned char *p, int plen); static int MatchBytea(unsigned char *t, int tlen, - unsigned char *p, int plen); + unsigned char *p, int plen); static text *do_like_escape(text *, text *); #ifdef MULTIBYTE static int MBMatchText(unsigned char *t, int tlen, - unsigned char *p, int plen); -static int MBMatchTextIC(unsigned char *t, int tlen, unsigned char *p, int plen); +static int MBMatchTextIC(unsigned char *t, int tlen, + unsigned char *p, int plen); static text *MB_do_like_escape(text *, text *); /*-------------------- @@ -107,7 +107,6 @@ iwchareq(unsigned char *p1, unsigned char *p2) c2[0] = tolower(c2[0]); return (c1[0] == c2[0]); } - #endif #ifdef MULTIBYTE @@ -123,7 +122,7 @@ iwchareq(unsigned char *p1, unsigned char *p2) } while (0) #define MatchText MBMatchText -#define MatchTextIC MBMatchTextIC +#define MatchTextIC MBMatchTextIC #define do_like_escape MB_do_like_escape #include "like_match.c" #undef CHAREQ @@ -167,11 +166,11 @@ namelike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchText(s, slen, p, plen) == LIKE_TRUE); + result = (MatchText(s, slen, p, plen) == LIKE_TRUE); else - result = (MBMatchText(s, slen, p, plen) == LIKE_TRUE); + result = (MBMatchText(s, slen, p, plen) == LIKE_TRUE); #else - result = (MatchText(s, slen, p, plen) == LIKE_TRUE); + result = (MatchText(s, slen, p, plen) == LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -195,11 +194,11 @@ namenlike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchText(s, slen, p, plen) != LIKE_TRUE); + result = (MatchText(s, slen, p, plen) != LIKE_TRUE); else - result = (MBMatchText(s, slen, p, plen) != LIKE_TRUE); + result = (MBMatchText(s, slen, p, plen) != LIKE_TRUE); #else - result = (MatchText(s, slen, p, plen) != LIKE_TRUE); + result = (MatchText(s, slen, p, plen) != LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -215,6 +214,7 @@ textlike(PG_FUNCTION_ARGS) *p; int slen, plen; + s = VARDATA(str); slen = (VARSIZE(str) - VARHDRSZ); p = VARDATA(pat); @@ -222,11 +222,11 @@ textlike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchText(s, slen, p, plen) == LIKE_TRUE); + result = (MatchText(s, slen, p, plen) == LIKE_TRUE); else - result = (MBMatchText(s, slen, p, plen) == LIKE_TRUE); + result = (MBMatchText(s, slen, p, plen) == LIKE_TRUE); #else - result = (MatchText(s, slen, p, plen) == LIKE_TRUE); + result = (MatchText(s, slen, p, plen) == LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -250,11 +250,11 @@ textnlike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchText(s, slen, p, plen) != LIKE_TRUE); + result = (MatchText(s, slen, p, plen) != LIKE_TRUE); else - result = (MBMatchText(s, slen, p, plen) != LIKE_TRUE); + result = (MBMatchText(s, slen, p, plen) != LIKE_TRUE); #else - result = (MatchText(s, slen, p, plen) != LIKE_TRUE); + result = (MatchText(s, slen, p, plen) != LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -324,11 +324,11 @@ nameiclike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); else - result = (MBMatchTextIC(s, slen, p, plen) == LIKE_TRUE); + result = (MBMatchTextIC(s, slen, p, plen) == LIKE_TRUE); #else - result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -352,11 +352,11 @@ nameicnlike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); else - result = (MBMatchTextIC(s, slen, p, plen) != LIKE_TRUE); + result = (MBMatchTextIC(s, slen, p, plen) != LIKE_TRUE); #else - result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -380,11 +380,11 @@ texticlike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); else - result = (MBMatchTextIC(s, slen, p, plen) == LIKE_TRUE); + result = (MBMatchTextIC(s, slen, p, plen) == LIKE_TRUE); #else - result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) == LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -408,11 +408,11 @@ texticnlike(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); else - result = (MBMatchTextIC(s, slen, p, plen) != LIKE_TRUE); + result = (MBMatchTextIC(s, slen, p, plen) != LIKE_TRUE); #else - result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); + result = (MatchTextIC(s, slen, p, plen) != LIKE_TRUE); #endif PG_RETURN_BOOL(result); @@ -431,9 +431,9 @@ like_escape(PG_FUNCTION_ARGS) #ifdef MULTIBYTE if (pg_database_encoding_max_length() == 1) - result = do_like_escape(pat, esc); + result = do_like_escape(pat, esc); else - result = MB_do_like_escape(pat, esc); + result = MB_do_like_escape(pat, esc); #else result = do_like_escape(pat, esc); #endif @@ -472,7 +472,6 @@ like_escape_bytea(PG_FUNCTION_ARGS) if (elen == 0) { - /* * No escape character is wanted. Double any backslashes in the * pattern to make them act like ordinary characters. @@ -486,7 +485,6 @@ like_escape_bytea(PG_FUNCTION_ARGS) } else { - /* * The specified escape must be only a single character. */ @@ -574,7 +572,6 @@ MatchBytea(unsigned char *t, int tlen, unsigned char *p, int plen) */ while (tlen > 0) { - /* * Optimization to prevent most recursion: don't recurse * unless first pattern char might match this text char. @@ -598,7 +595,6 @@ MatchBytea(unsigned char *t, int tlen, unsigned char *p, int plen) } else if ((*p != '_') && !BYTEA_CHAREQ(t, p)) { - /* * Not the single-character wildcard and no explicit match? * Then time to quit... diff --git a/src/backend/utils/adt/like_match.c b/src/backend/utils/adt/like_match.c index f13b8fea05..f92d424d3e 100644 --- a/src/backend/utils/adt/like_match.c +++ b/src/backend/utils/adt/like_match.c @@ -18,7 +18,7 @@ * Copyright (c) 1996-2001, PostgreSQL Global Development Group * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/like_match.c,v 1.1 2001/10/04 02:15:47 ishii Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/like_match.c,v 1.2 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -101,7 +101,6 @@ MatchText(unsigned char *t, int tlen, unsigned char *p, int plen) */ while (tlen > 0) { - /* * Optimization to prevent most recursion: don't recurse * unless first pattern char might match this text char. @@ -125,7 +124,6 @@ MatchText(unsigned char *t, int tlen, unsigned char *p, int plen) } else if ((*p != '_') && !CHAREQ(t, p)) { - /* * Not the single-character wildcard and no explicit match? * Then time to quit... @@ -189,7 +187,6 @@ MatchTextIC(unsigned char *t, int tlen, unsigned char *p, int plen) */ while (tlen > 0) { - /* * Optimization to prevent most recursion: don't recurse * unless first pattern char might match this text char. @@ -213,7 +210,6 @@ MatchTextIC(unsigned char *t, int tlen, unsigned char *p, int plen) } else if ((*p != '_') && !ICHAREQ(t, p)) { - /* * Not the single-character wildcard and no explicit match? * Then time to quit... @@ -271,7 +267,6 @@ do_like_escape(text *pat, text *esc) if (elen == 0) { - /* * No escape character is wanted. Double any backslashes in the * pattern to make them act like ordinary characters. @@ -285,7 +280,6 @@ do_like_escape(text *pat, text *esc) } else { - /* * The specified escape must be only a single character. */ diff --git a/src/backend/utils/adt/misc.c b/src/backend/utils/adt/misc.c index af08bda878..5bdd5475c3 100644 --- a/src/backend/utils/adt/misc.c +++ b/src/backend/utils/adt/misc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/misc.c,v 1.22 2001/03/22 03:59:51 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/misc.c,v 1.23 2001/10/25 05:49:44 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -66,7 +66,6 @@ oidrand(PG_FUNCTION_ARGS) { #ifdef NOT_USED Oid o = PG_GETARG_OID(0); - #endif int32 X = PG_GETARG_INT32(1); bool result; diff --git a/src/backend/utils/adt/nabstime.c b/src/backend/utils/adt/nabstime.c index 29608aa78d..3bbf5ec7c8 100644 --- a/src/backend/utils/adt/nabstime.c +++ b/src/backend/utils/adt/nabstime.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/nabstime.c,v 1.90 2001/10/20 01:02:18 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/nabstime.c,v 1.91 2001/10/25 05:49:44 momjian Exp $ * * NOTES * @@ -90,7 +90,6 @@ static int sec_tab[] = { 1, 1, 60, 60, 3600, 3600, 86400, 86400, 604800, 604800, 2592000, 2592000, 31536000, 31536000}; - #endif /* @@ -103,7 +102,6 @@ static void reltime2tm(RelativeTime time, struct tm * tm); #ifdef NOT_USED static int correct_unit(char *unit, int *unptr); static int correct_dir(char *direction, int *signptr); - #endif static int istinterval(char *i_string, @@ -188,13 +186,15 @@ GetCurrentAbsoluteTime(void) AbsoluteTime GetCurrentAbsoluteTimeUsec(int *usec) { - time_t now; + time_t now; struct timeval tp; + #ifdef NOT_USED struct timezone tpz; #endif #if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE) struct tm *tm; + #else struct timeb tb; /* the old V7-ism */ #endif @@ -271,7 +271,7 @@ GetCurrentTime(struct tm * tm) void -GetCurrentTimeUsec(struct tm *tm, double *fsec) +GetCurrentTimeUsec(struct tm * tm, double *fsec) { int tz; int usec; @@ -297,15 +297,16 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) ftime(&tb); #endif - /* If HasCTZSet is true then we have a brute force time zone specified. - * Go ahead and rotate to the local time zone since we will later bypass - * any calls which adjust the tm fields. + /* + * If HasCTZSet is true then we have a brute force time zone + * specified. Go ahead and rotate to the local time zone since we will + * later bypass any calls which adjust the tm fields. */ if (HasCTZSet && (tzp != NULL)) time -= CTimeZone; #if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE) - if ((! HasCTZSet) && (tzp != NULL)) + if ((!HasCTZSet) && (tzp != NULL)) { tx = localtime((time_t *) &time); #ifdef NO_MKTIME_BEFORE_1970 @@ -336,9 +337,9 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) if (tzp != NULL) { - /* We have a brute force time zone per SQL99? - * Then use it without change - * since we have already rotated to the time zone. + /* + * We have a brute force time zone per SQL99? Then use it without + * change since we have already rotated to the time zone. */ if (HasCTZSet) { @@ -351,14 +352,18 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) } else { - *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 */ + /* + * 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 + * 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) @@ -367,15 +372,13 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) } } else - { tm->tm_isdst = -1; - } #elif defined(HAVE_INT_TIMEZONE) if (tzp != NULL) { - /* We have a brute force time zone per SQL99? - * Then use it without change - * since we have already rotated to the time zone. + /* + * We have a brute force time zone per SQL99? Then use it without + * change since we have already rotated to the time zone. */ if (HasCTZSet) { @@ -390,10 +393,10 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) 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 + * 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) @@ -402,16 +405,14 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) } } else - { tm->tm_isdst = -1; - } #endif #else /* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */ if (tzp != NULL) { - /* We have a brute force time zone per SQL99? - * Then use it without change - * since we have already rotated to the time zone. + /* + * We have a brute force time zone per SQL99? Then use it without + * change since we have already rotated to the time zone. */ if (HasCTZSet) { @@ -424,20 +425,19 @@ abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn) *tzp = tb.timezone * 60; /* - * XXX does this work to get the local timezone string in V7? - tgl - * 97/03/18 + * XXX does this work to get the local timezone string in V7? + * - tgl 97/03/18 */ if (tzn != NULL) { strftime(*tzn, MAXTZLEN, "%Z", localtime(&now)); - tzn[MAXTZLEN] = '\0'; /* let's just be sure it's null-terminated */ + tzn[MAXTZLEN] = '\0'; /* let's just be sure it's + * null-terminated */ } } } else - { tm->tm_isdst = -1; - } #endif return; @@ -517,8 +517,11 @@ nabstimein(PG_FUNCTION_ARGS) break; case DTK_EPOCH: - /* Don't bother retaining this as a reserved value, - * but instead just set to the actual epoch time (1970-01-01) */ + + /* + * Don't bother retaining this as a reserved value, but + * instead just set to the actual epoch time (1970-01-01) + */ result = 0; break; @@ -562,9 +565,10 @@ nabstimeout(PG_FUNCTION_ARGS) switch (time) { - /* Note that timestamp no longer supports 'invalid'. - * Retain 'invalid' for abstime for now, but dump it someday. - */ + /* + * Note that timestamp no longer supports 'invalid'. Retain + * 'invalid' for abstime for now, but dump it someday. + */ case INVALID_ABSTIME: strcpy(buf, INVALID); break; @@ -611,14 +615,14 @@ abstime_cmp_internal(AbsoluteTime a, AbsoluteTime b) */ if (a == INVALID_ABSTIME) { - if (b == INVALID_ABSTIME) - return 0; /* INVALID = INVALID */ - else - return 1; /* INVALID > non-INVALID */ + if (b == INVALID_ABSTIME) + return 0; /* INVALID = INVALID */ + else + return 1; /* INVALID > non-INVALID */ } if (b == INVALID_ABSTIME) - return -1; /* non-INVALID < INVALID */ + return -1; /* non-INVALID < INVALID */ #if 0 /* CURRENT is no longer stored internally... */ @@ -777,7 +781,7 @@ abstime_timestamp(PG_FUNCTION_ARGS) Datum timestamptz_abstime(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); AbsoluteTime result; double fsec; struct tm tt, @@ -805,7 +809,7 @@ Datum abstime_timestamptz(PG_FUNCTION_ARGS) { AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0); - TimestampTz result; + TimestampTz result; switch (abstime) { @@ -928,7 +932,7 @@ tintervalin(PG_FUNCTION_ARGS) elog(ERROR, "Unable to decode tinterval '%s'", intervalstr); if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME) - interval->status = T_INTERVAL_INVAL; /* undefined */ + interval->status = T_INTERVAL_INVAL; /* undefined */ else interval->status = T_INTERVAL_VALID; @@ -1273,11 +1277,11 @@ tintervalsame(PG_FUNCTION_ARGS) PG_RETURN_BOOL(false); if (DatumGetBool(DirectFunctionCall2(abstimeeq, - AbsoluteTimeGetDatum(i1->data[0]), - AbsoluteTimeGetDatum(i2->data[0]))) && + AbsoluteTimeGetDatum(i1->data[0]), + AbsoluteTimeGetDatum(i2->data[0]))) && DatumGetBool(DirectFunctionCall2(abstimeeq, - AbsoluteTimeGetDatum(i1->data[1]), - AbsoluteTimeGetDatum(i2->data[1])))) + AbsoluteTimeGetDatum(i1->data[1]), + AbsoluteTimeGetDatum(i2->data[1])))) PG_RETURN_BOOL(true); PG_RETURN_BOOL(false); } @@ -1293,9 +1297,9 @@ tintervaleq(PG_FUNCTION_ARGS) TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0); TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1); AbsoluteTime t10, - t11, - t20, - t21; + t11, + t20, + t21; if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL) PG_RETURN_BOOL(false); @@ -1318,9 +1322,9 @@ tintervalne(PG_FUNCTION_ARGS) TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0); TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1); AbsoluteTime t10, - t11, - t20, - t21; + t11, + t20, + t21; if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL) PG_RETURN_BOOL(false); @@ -1343,9 +1347,9 @@ tintervallt(PG_FUNCTION_ARGS) TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0); TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1); AbsoluteTime t10, - t11, - t20, - t21; + t11, + t20, + t21; if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL) PG_RETURN_BOOL(false); @@ -1368,9 +1372,9 @@ tintervalle(PG_FUNCTION_ARGS) TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0); TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1); AbsoluteTime t10, - t11, - t20, - t21; + t11, + t20, + t21; if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL) PG_RETURN_BOOL(false); @@ -1462,7 +1466,7 @@ tintervalleneq(PG_FUNCTION_ARGS) if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME) PG_RETURN_BOOL(false); rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel, - TimeIntervalGetDatum(i))); + TimeIntervalGetDatum(i))); PG_RETURN_BOOL((rt != INVALID_RELTIME) && (rt == t)); } @@ -1569,11 +1573,11 @@ tintervalov(PG_FUNCTION_ARGS) if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL) PG_RETURN_BOOL(false); if (DatumGetBool(DirectFunctionCall2(abstimelt, - AbsoluteTimeGetDatum(i1->data[1]), - AbsoluteTimeGetDatum(i2->data[0]))) || + AbsoluteTimeGetDatum(i1->data[1]), + AbsoluteTimeGetDatum(i2->data[0]))) || DatumGetBool(DirectFunctionCall2(abstimegt, - AbsoluteTimeGetDatum(i1->data[0]), - AbsoluteTimeGetDatum(i2->data[1])))) + AbsoluteTimeGetDatum(i1->data[0]), + AbsoluteTimeGetDatum(i2->data[1])))) PG_RETURN_BOOL(false); PG_RETURN_BOOL(true); } diff --git a/src/backend/utils/adt/name.c b/src/backend/utils/adt/name.c index 532a9d863a..cc3c8a791f 100644 --- a/src/backend/utils/adt/name.c +++ b/src/backend/utils/adt/name.c @@ -12,7 +12,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/name.c,v 1.31 2001/01/24 19:43:14 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/name.c,v 1.32 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -155,7 +155,6 @@ namecat(Name n1, Name n2) return namestrcat(n1, NameStr(*n2)); /* n2 can't be any longer * than n1 */ } - #endif #ifdef NOT_USED @@ -164,7 +163,6 @@ namecmp(Name n1, Name n2) { return strncmp(NameStr(*n1), NameStr(*n2), NAMEDATALEN); } - #endif int @@ -196,7 +194,6 @@ namestrcat(Name name, const char *str) } return 0; } - #endif int @@ -243,5 +240,4 @@ NameComputeLength(Name name) ; return (uint32) length; } - #endif diff --git a/src/backend/utils/adt/network.c b/src/backend/utils/adt/network.c index 674ed49630..4004492174 100644 --- a/src/backend/utils/adt/network.c +++ b/src/backend/utils/adt/network.c @@ -3,7 +3,7 @@ * is for IP V4 CIDR notation, but prepared for V6: just * add the necessary bits where the comments indicate. * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/network.c,v 1.33 2001/08/27 20:03:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/network.c,v 1.34 2001/10/25 05:49:45 momjian Exp $ * * Jon Postel RIP 16 Oct 1998 */ @@ -153,44 +153,43 @@ cidr_out(PG_FUNCTION_ARGS) static Datum text_network(text *src, int type) { - int len = VARSIZE(src) - VARHDRSZ; + int len = VARSIZE(src) - VARHDRSZ; - char *str = palloc(len + 1); - memcpy(str, VARDATA(src), len); - *(str + len) = '\0'; + char *str = palloc(len + 1); - PG_RETURN_INET_P(network_in( str, type)); + memcpy(str, VARDATA(src), len); + *(str + len) = '\0'; + + PG_RETURN_INET_P(network_in(str, type)); } Datum text_cidr(PG_FUNCTION_ARGS) { - return text_network( PG_GETARG_TEXT_P(0), 1); + return text_network(PG_GETARG_TEXT_P(0), 1); } Datum text_inet(PG_FUNCTION_ARGS) { - return text_network( PG_GETARG_TEXT_P(0), 0); + return text_network(PG_GETARG_TEXT_P(0), 0); } Datum inet_set_masklen(PG_FUNCTION_ARGS) { - inet *src = PG_GETARG_INET_P(0); - int bits = PG_GETARG_INT32(1); - inet *dst; + inet *src = PG_GETARG_INET_P(0); + int bits = PG_GETARG_INT32(1); + inet *dst; - if ((bits < 0) || (bits > 32)) /* no support for v6 yet */ - { - elog(ERROR, "set_masklen - invalid value '%d'", bits); - } + if ((bits < 0) || (bits > 32)) /* no support for v6 yet */ + elog(ERROR, "set_masklen - invalid value '%d'", bits); /* clone the original data */ - dst = (inet *) palloc(VARHDRSZ + sizeof(inet_struct)); + dst = (inet *) palloc(VARHDRSZ + sizeof(inet_struct)); memcpy(dst, src, VARHDRSZ + sizeof(inet_struct)); - ip_bits(dst) = bits; + ip_bits(dst) = bits; PG_RETURN_INET_P(dst); } @@ -618,7 +617,7 @@ network_netmask(PG_FUNCTION_ARGS) * involving network types. * * Currently, inet/cidr values are simply converted to the IPv4 address; - * this will need more thought when IPv6 is supported too. MAC addresses + * this will need more thought when IPv6 is supported too. MAC addresses * are converted to their numeric equivalent as well (OK since we have a * double to play in). */ @@ -629,26 +628,26 @@ convert_network_to_scalar(Datum value, Oid typid) { case INETOID: case CIDROID: - { - inet *ip = DatumGetInetP(value); - - if (ip_family(ip) == AF_INET) - return (double) ip_v4addr(ip); - else - /* Go for an IPV6 address here, before faulting out: */ - elog(ERROR, "unknown address family (%d)", ip_family(ip)); - break; - } + { + inet *ip = DatumGetInetP(value); + + if (ip_family(ip) == AF_INET) + return (double) ip_v4addr(ip); + else + /* Go for an IPV6 address here, before faulting out: */ + elog(ERROR, "unknown address family (%d)", ip_family(ip)); + break; + } case MACADDROID: - { - macaddr *mac = DatumGetMacaddrP(value); - double res; - - res = (mac->a << 16) | (mac->b << 8) | (mac->c); - res *= 256*256*256; - res += (mac->d << 16) | (mac->e << 8) | (mac->f); - return res; - } + { + macaddr *mac = DatumGetMacaddrP(value); + double res; + + res = (mac->a << 16) | (mac->b << 8) | (mac->c); + res *= 256 * 256 * 256; + res += (mac->d << 16) | (mac->e << 8) | (mac->f); + return res; + } } /* @@ -722,7 +721,7 @@ network_scan_first(Datum in) } /* - * return "last" IP on a given network. It's the broadcast address, + * return "last" IP on a given network. It's the broadcast address, * however, masklen has to be set to 32, since * 192.168.0.255/24 is considered less than 192.168.0.255/32 * diff --git a/src/backend/utils/adt/not_in.c b/src/backend/utils/adt/not_in.c index ac596b1f12..8c3ca1b73b 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.26 2001/03/22 03:59:52 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/not_in.c,v 1.27 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -113,7 +113,6 @@ oidnotin(PG_FUNCTION_ARGS) #ifdef NOT_USED text *relation_and_attr = PG_GETARG_TEXT_P(1); - #endif if (the_oid == InvalidOid) diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c index 5160f690c1..4e7398448b 100644 --- a/src/backend/utils/adt/numeric.c +++ b/src/backend/utils/adt/numeric.c @@ -5,7 +5,7 @@ * * 1998 Jan Wieck * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/numeric.c,v 1.45 2001/10/13 23:32:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/numeric.c,v 1.46 2001/10/25 05:49:45 momjian Exp $ * * ---------- */ @@ -193,6 +193,7 @@ Datum numeric_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif @@ -440,7 +441,6 @@ numeric_sign(PG_FUNCTION_ARGS) set_var_from_var(&const_zero, &result); else { - /* * And if there are some, we return a copy of ONE with the sign of * our argument @@ -496,7 +496,6 @@ numeric_round(PG_FUNCTION_ARGS) if (i < arg.ndigits) { - /* * If i = 0, the value loses all digits, but could round up if its * first digit is more than 4. If i < 0 the result must be 0. @@ -518,7 +517,7 @@ numeric_round(PG_FUNCTION_ARGS) if (i < 0) { - Assert(i == -1);/* better not have added more than 1 digit */ + Assert(i == -1); /* better not have added more than 1 digit */ Assert(arg.digits > arg.buf); arg.digits--; arg.ndigits++; @@ -781,9 +780,9 @@ cmp_numerics(Numeric num1, Numeric num2) int result; /* - * We consider all NANs to be equal and larger than any non-NAN. - * This is somewhat arbitrary; the important thing is to have a - * consistent sort order. + * We consider all NANs to be equal and larger than any non-NAN. This + * is somewhat arbitrary; the important thing is to have a consistent + * sort order. */ if (NUMERIC_IS_NAN(num1)) { @@ -1799,9 +1798,9 @@ numeric_accum(PG_FUNCTION_ARGS) /* * Integer data types all use Numeric accumulators to share code and - * avoid risk of overflow. For int2 and int4 inputs, Numeric accumulation + * avoid risk of overflow. For int2 and int4 inputs, Numeric accumulation * is overkill for the N and sum(X) values, but definitely not overkill - * for the sum(X*X) value. Hence, we use int2_accum and int4_accum only + * for the sum(X*X) value. Hence, we use int2_accum and int4_accum only * for stddev/variance --- there are faster special-purpose accumulator * routines for SUM and AVG of these datatypes. */ @@ -2020,7 +2019,7 @@ numeric_stddev(PG_FUNCTION_ARGS) * the initial condition of the transition data value needs to be NULL. This * means we can't rely on ExecAgg to automatically insert the first non-null * data value into the transition data: it doesn't know how to do the type - * conversion. The upshot is that these routines have to be marked non-strict + * conversion. The upshot is that these routines have to be marked non-strict * and handle substitution of the first non-null input themselves. */ @@ -2269,7 +2268,6 @@ dump_var(char *str, NumericVar *var) printf("\n"); } - #endif /* NUMERIC_DEBUG */ @@ -2795,7 +2793,6 @@ cmp_var(NumericVar *var1, NumericVar *var2) static void add_var(NumericVar *var1, NumericVar *var2, NumericVar *result) { - /* * Decide on the signs of the two variables what to do */ @@ -2803,7 +2800,6 @@ add_var(NumericVar *var1, NumericVar *var2, NumericVar *result) { if (var2->sign == NUMERIC_POS) { - /* * Both are positive result = +(ABS(var1) + ABS(var2)) */ @@ -2812,7 +2808,6 @@ add_var(NumericVar *var1, NumericVar *var2, NumericVar *result) } else { - /* * var1 is positive, var2 is negative Must compare absolute * values @@ -2919,7 +2914,6 @@ add_var(NumericVar *var1, NumericVar *var2, NumericVar *result) static void sub_var(NumericVar *var1, NumericVar *var2, NumericVar *result) { - /* * Decide on the signs of the two variables what to do */ diff --git a/src/backend/utils/adt/numutils.c b/src/backend/utils/adt/numutils.c index 92af2ab56c..bb7f894441 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.45 2001/03/22 03:59:52 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/numutils.c,v 1.46 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -345,7 +345,6 @@ frac_out: return avail; #endif } - #endif /* @@ -476,5 +475,4 @@ atof1(char *str, double *val) *val = v; return 0; } - #endif diff --git a/src/backend/utils/adt/oracle_compat.c b/src/backend/utils/adt/oracle_compat.c index 698c309f9d..46a029caae 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.35 2001/09/23 11:02:01 ishii Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/oracle_compat.c,v 1.36 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -171,8 +171,9 @@ lpad(PG_FUNCTION_ARGS) int m, s1len, s2len; + #ifdef MULTIBYTE - int bytelen; + int bytelen; #endif /* Negative len is silently taken as zero */ @@ -188,7 +189,7 @@ lpad(PG_FUNCTION_ARGS) s2len = 0; /* shouldn't happen */ #ifdef MULTIBYTE - s1len = pg_mbstrlen_with_len(VARDATA(string1),s1len); + s1len = pg_mbstrlen_with_len(VARDATA(string1), s1len); #endif if (s1len > len) s1len = len; /* truncate string1 to len chars */ @@ -213,12 +214,13 @@ lpad(PG_FUNCTION_ARGS) #ifdef MULTIBYTE while (m--) { - int mlen = pg_mblen(ptr2); - memcpy(ptr_ret, ptr2, mlen); - ptr_ret += mlen; - ptr2 += mlen; - if (ptr2 == ptr2end) /* wrap around at end of s2 */ - ptr2 = VARDATA(string2); + int mlen = pg_mblen(ptr2); + + memcpy(ptr_ret, ptr2, mlen); + ptr_ret += mlen; + ptr2 += mlen; + if (ptr2 == ptr2end) /* wrap around at end of s2 */ + ptr2 = VARDATA(string2); } #else while (m--) @@ -234,10 +236,11 @@ lpad(PG_FUNCTION_ARGS) #ifdef MULTIBYTE while (s1len--) { - int mlen = pg_mblen(ptr1); - memcpy(ptr_ret, ptr1, mlen); - ptr_ret += mlen; - ptr1 += mlen; + int mlen = pg_mblen(ptr1); + + memcpy(ptr_ret, ptr1, mlen); + ptr_ret += mlen; + ptr1 += mlen; } #else while (s1len--) @@ -278,8 +281,9 @@ rpad(PG_FUNCTION_ARGS) int m, s1len, s2len; + #ifdef MULTIBYTE - int bytelen; + int bytelen; #endif /* Negative len is silently taken as zero */ @@ -295,7 +299,7 @@ rpad(PG_FUNCTION_ARGS) s2len = 0; /* shouldn't happen */ #ifdef MULTIBYTE - s1len = pg_mbstrlen_with_len(VARDATA(string1),s1len); + s1len = pg_mbstrlen_with_len(VARDATA(string1), s1len); #endif if (s1len > len) @@ -320,10 +324,11 @@ rpad(PG_FUNCTION_ARGS) #ifdef MULTIBYTE while (s1len--) { - int mlen = pg_mblen(ptr1); - memcpy(ptr_ret, ptr1, mlen); - ptr_ret += mlen; - ptr1 += mlen; + int mlen = pg_mblen(ptr1); + + memcpy(ptr_ret, ptr1, mlen); + ptr_ret += mlen; + ptr1 += mlen; } #else while (s1len--) @@ -336,12 +341,13 @@ rpad(PG_FUNCTION_ARGS) #ifdef MULTIBYTE while (m--) { - int mlen = pg_mblen(ptr2); - memcpy(ptr_ret, ptr2, mlen); - ptr_ret += mlen; - ptr2 += mlen; - if (ptr2 == ptr2end) /* wrap around at end of s2 */ - ptr2 = VARDATA(string2); + int mlen = pg_mblen(ptr2); + + memcpy(ptr_ret, ptr2, mlen); + ptr_ret += mlen; + ptr2 += mlen; + if (ptr2 == ptr2end) /* wrap around at end of s2 */ + ptr2 = VARDATA(string2); } #else while (m--) @@ -384,11 +390,11 @@ btrim(PG_FUNCTION_ARGS) int m; #ifdef MULTIBYTE - char **mp; - int mplen; - char *p; - int mblen; - int len; + char **mp; + int mplen; + char *p; + int mblen; + int len; #endif if ((m = VARSIZE(string) - VARHDRSZ) <= 0 || @@ -398,18 +404,18 @@ btrim(PG_FUNCTION_ARGS) ptr = VARDATA(string); #ifdef MULTIBYTE - len = m; - mp = (char **)palloc(len*sizeof(char *)); + len = m; + mp = (char **) palloc(len * sizeof(char *)); p = ptr; mplen = 0; /* build the mb pointer array */ while (len > 0) { - mp[mplen++] = p; - mblen = pg_mblen(p); - p += mblen; - len -= mblen; + mp[mplen++] = p; + mblen = pg_mblen(p); + p += mblen; + len -= mblen; } mplen--; #else @@ -420,16 +426,17 @@ btrim(PG_FUNCTION_ARGS) #ifdef MULTIBYTE while (m > 0) { - int str_len = pg_mblen(ptr); + int str_len = pg_mblen(ptr); + ptr2 = VARDATA(set); while (ptr2 <= end2) { - int set_len = pg_mblen(ptr2); + int set_len = pg_mblen(ptr2); - if (str_len == set_len && - memcmp(ptr,ptr2,str_len) == 0) + if (str_len == set_len && + memcmp(ptr, ptr2, str_len) == 0) break; - ptr2 += set_len; + ptr2 += set_len; } if (ptr2 > end2) break; @@ -439,18 +446,19 @@ btrim(PG_FUNCTION_ARGS) while (m > 0) { - int str_len; + int str_len; + end = mp[mplen--]; str_len = pg_mblen(end); ptr2 = VARDATA(set); while (ptr2 <= end2) { - int set_len = pg_mblen(ptr2); + int set_len = pg_mblen(ptr2); - if (str_len == set_len && - memcmp(end,ptr2,str_len) == 0) + if (str_len == set_len && + memcmp(end, ptr2, str_len) == 0) break; - ptr2 += set_len; + ptr2 += set_len; } if (ptr2 > end2) break; @@ -604,16 +612,17 @@ ltrim(PG_FUNCTION_ARGS) #ifdef MULTIBYTE while (m > 0) { - int str_len = pg_mblen(ptr); + int str_len = pg_mblen(ptr); + ptr2 = VARDATA(set); while (ptr2 <= end2) { - int set_len = pg_mblen(ptr2); + int set_len = pg_mblen(ptr2); - if (str_len == set_len && - memcmp(ptr,ptr2,str_len) == 0) + if (str_len == set_len && + memcmp(ptr, ptr2, str_len) == 0) break; - ptr2 += set_len; + ptr2 += set_len; } if (ptr2 > end2) break; @@ -673,11 +682,11 @@ rtrim(PG_FUNCTION_ARGS) int m; #ifdef MULTIBYTE - char **mp; - int mplen; - char *p; - int mblen; - int len; + char **mp; + int mplen; + char *p; + int mblen; + int len; #endif if ((m = VARSIZE(string) - VARHDRSZ) <= 0 || @@ -687,18 +696,18 @@ rtrim(PG_FUNCTION_ARGS) ptr = VARDATA(string); #ifdef MULTIBYTE - len = m; - mp = (char **)palloc(len*sizeof(char *)); + len = m; + mp = (char **) palloc(len * sizeof(char *)); p = ptr; mplen = 0; /* build the mb pointer array */ while (len > 0) { - mp[mplen++] = p; - mblen = pg_mblen(p); - p += mblen; - len -= mblen; + mp[mplen++] = p; + mblen = pg_mblen(p); + p += mblen; + len -= mblen; } mplen--; #else @@ -709,18 +718,19 @@ rtrim(PG_FUNCTION_ARGS) #ifdef MULTIBYTE while (m > 0) { - int str_len; + int str_len; + end = mp[mplen--]; str_len = pg_mblen(end); ptr2 = VARDATA(set); while (ptr2 <= end2) { - int set_len = pg_mblen(ptr2); + int set_len = pg_mblen(ptr2); - if (str_len == set_len && - memcmp(end,ptr2,str_len) == 0) + if (str_len == set_len && + memcmp(end, ptr2, str_len) == 0) break; - ptr2 += set_len; + ptr2 += set_len; } if (ptr2 > end2) break; @@ -784,12 +794,13 @@ translate(PG_FUNCTION_ARGS) tolen, retlen, i; + #ifdef MULTIBYTE - int str_len; - int estimate_len; - int len; - int source_len; - int from_index; + int str_len; + int estimate_len; + int len; + int source_len; + int from_index; #endif if ((m = VARSIZE(string) - VARHDRSZ) <= 0) @@ -802,8 +813,8 @@ translate(PG_FUNCTION_ARGS) #ifdef MULTIBYTE str_len = VARSIZE(string); - estimate_len = (tolen*1.0/fromlen + 0.5)*str_len; - estimate_len = estimate_len>str_len?estimate_len:str_len; + estimate_len = (tolen * 1.0 / fromlen + 0.5) * str_len; + estimate_len = estimate_len > str_len ? estimate_len : str_len; result = (text *) palloc(estimate_len); #else result = (text *) palloc(VARSIZE(string)); @@ -821,38 +832,39 @@ translate(PG_FUNCTION_ARGS) for (i = 0; i < fromlen; i += len) { - len = pg_mblen(&from_ptr[i]); - if (len == source_len && - memcmp(source, &from_ptr[i], len) == 0) - break; + len = pg_mblen(&from_ptr[i]); + if (len == source_len && + memcmp(source, &from_ptr[i], len) == 0) + break; - from_index++; + from_index++; } if (i < fromlen) { - /* substitute */ - char *p = to_ptr; - for (i=0;i<from_index;i++) - { - p += pg_mblen(p); - if (p >= (to_ptr + tolen)) - break; - } - if (p < (to_ptr + tolen)) - { - len = pg_mblen(p); - memcpy(target, p, len); - target += len; - retlen += len; - } + /* substitute */ + char *p = to_ptr; + + for (i = 0; i < from_index; i++) + { + p += pg_mblen(p); + if (p >= (to_ptr + tolen)) + break; + } + if (p < (to_ptr + tolen)) + { + len = pg_mblen(p); + memcpy(target, p, len); + target += len; + retlen += len; + } } else { /* no match, so copy */ - memcpy(target, source, source_len); - target += source_len; - retlen += source_len; + memcpy(target, source, source_len); + target += source_len; + retlen += source_len; } source += source_len; diff --git a/src/backend/utils/adt/pg_locale.c b/src/backend/utils/adt/pg_locale.c index 513328d35c..17abbbd5a3 100644 --- a/src/backend/utils/adt/pg_locale.c +++ b/src/backend/utils/adt/pg_locale.c @@ -4,7 +4,7 @@ * The PostgreSQL locale utils. * * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_locale.c,v 1.10 2001/09/29 21:16:30 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_locale.c,v 1.11 2001/10/25 05:49:45 momjian Exp $ * * Portions Copyright (c) 1999-2000, PostgreSQL Global Development Group * @@ -28,15 +28,15 @@ static bool CurrentLocaleConvValid = false; static struct lconv CurrentLocaleConv; -static void PGLC_setlocale(PG_LocaleCategories * lc); +static void PGLC_setlocale(PG_LocaleCategories *lc); /*------ - * Frees memory used in PG_LocaleCategories -- this memory is + * Frees memory used in PG_LocaleCategories -- this memory is * allocated in PGLC_current(). *------ */ void -PGLC_free_categories(PG_LocaleCategories * lc) +PGLC_free_categories(PG_LocaleCategories *lc) { if (lc->lc_ctype) pfree(lc->lc_ctype); @@ -47,7 +47,7 @@ PGLC_free_categories(PG_LocaleCategories * lc) if (lc->lc_collate) pfree(lc->lc_collate); if (lc->lc_monetary); - pfree(lc->lc_monetary); + pfree(lc->lc_monetary); #ifdef LC_MESSAGES if (lc->lc_messages) pfree(lc->lc_messages); @@ -61,17 +61,17 @@ PGLC_free_categories(PG_LocaleCategories * lc) *------ */ void -PGLC_current(PG_LocaleCategories * lc) +PGLC_current(PG_LocaleCategories *lc) { lc->lang = getenv("LANG"); - lc->lc_ctype = pstrdup( setlocale(LC_CTYPE, NULL) ); - lc->lc_numeric = pstrdup( setlocale(LC_NUMERIC, NULL) ); - lc->lc_time = pstrdup( setlocale(LC_TIME, NULL) ); - lc->lc_collate = pstrdup( setlocale(LC_COLLATE, NULL) ); - lc->lc_monetary = pstrdup( setlocale(LC_MONETARY, NULL) ); + lc->lc_ctype = pstrdup(setlocale(LC_CTYPE, NULL)); + lc->lc_numeric = pstrdup(setlocale(LC_NUMERIC, NULL)); + lc->lc_time = pstrdup(setlocale(LC_TIME, NULL)); + lc->lc_collate = pstrdup(setlocale(LC_COLLATE, NULL)); + lc->lc_monetary = pstrdup(setlocale(LC_MONETARY, NULL)); #ifdef LC_MESSAGES - lc->lc_messages = pstrdup( setlocale(LC_MESSAGES, NULL) ); + lc->lc_messages = pstrdup(setlocale(LC_MESSAGES, NULL)); #endif } @@ -83,7 +83,7 @@ PGLC_current(PG_LocaleCategories * lc) *------ */ static void -PGLC_debug_lc(PG_LocaleCategories * lc) +PGLC_debug_lc(PG_LocaleCategories *lc) { #ifdef LC_MESSAGES elog(DEBUG, "CURRENT LOCALE ENVIRONMENT:\n\nLANG: \t%s\nLC_CTYPE:\t%s\nLC_NUMERIC:\t%s\nLC_TIME:\t%s\nLC_COLLATE:\t%s\nLC_MONETARY:\t%s\nLC_MESSAGES:\t%s\n", @@ -104,7 +104,6 @@ PGLC_debug_lc(PG_LocaleCategories * lc) lc->lc_monetary); #endif } - #endif /*------ @@ -117,7 +116,7 @@ PGLC_debug_lc(PG_LocaleCategories * lc) *------ */ static void -PGLC_setlocale(PG_LocaleCategories * lc) +PGLC_setlocale(PG_LocaleCategories *lc) { if (!setlocale(LC_COLLATE, lc->lc_collate)) elog(NOTICE, "pg_setlocale(): 'LC_COLLATE=%s' cannot be honored.", @@ -172,7 +171,10 @@ PGLC_localeconv(void) /* Get formatting information for the external environment */ extlconv = localeconv(); - /* Must copy all values since restoring internal settings may overwrite */ + /* + * Must copy all values since restoring internal settings may + * overwrite + */ CurrentLocaleConv = *extlconv; CurrentLocaleConv.currency_symbol = strdup(extlconv->currency_symbol); CurrentLocaleConv.decimal_point = strdup(extlconv->decimal_point); @@ -194,5 +196,4 @@ PGLC_localeconv(void) CurrentLocaleConvValid = true; return &CurrentLocaleConv; } - #endif /* USE_LOCALE */ diff --git a/src/backend/utils/adt/pg_lzcompress.c b/src/backend/utils/adt/pg_lzcompress.c index 5c6cc6e1e4..056ad98844 100644 --- a/src/backend/utils/adt/pg_lzcompress.c +++ b/src/backend/utils/adt/pg_lzcompress.c @@ -1,7 +1,7 @@ /* ---------- * pg_lzcompress.c - * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_lzcompress.c,v 1.12 2001/10/25 01:29:37 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_lzcompress.c,v 1.13 2001/10/25 05:49:45 momjian Exp $ * * This is an implementation of LZ compression for PostgreSQL. * It uses a simple history table and generates 2-3 byte tags @@ -394,7 +394,6 @@ pglz_find_match(PGLZ_HistEntry **hstart, char *input, char *end, hent = hstart[pglz_hist_idx(input, end)]; while (hent && len < good_match) { - /* * Be happy with lesser good matches the more entries we visited. */ @@ -566,7 +565,6 @@ pglz_compress(char *source, int32 slen, PGLZ_Header *dest, PGLZ_Strategy *strate */ while (dp < dend) { - /* * If we already exceeded the maximum result size, set no * compression flag and stop this. But don't check too often. @@ -583,7 +581,6 @@ pglz_compress(char *source, int32 slen, PGLZ_Header *dest, PGLZ_Strategy *strate if (pglz_find_match(hist_start, dp, dend, &match_len, &match_off, good_match, good_drop)) { - /* * Create the tag and add history entries for all matched * characters. @@ -598,7 +595,6 @@ pglz_compress(char *source, int32 slen, PGLZ_Header *dest, PGLZ_Strategy *strate } else { - /* * No match found. Copy one literal byte. */ @@ -671,7 +667,6 @@ pglz_decompress(PGLZ_Header *source, char *dest) while (dp < dend) { - /* * Read one control byte and process the next 8 items. */ @@ -680,7 +675,6 @@ pglz_decompress(PGLZ_Header *source, char *dest) { if (ctrl & 1) { - /* * Otherwise it contains the match length minus 3 and the * upper 4 bits of the offset. The next following byte @@ -708,7 +702,6 @@ pglz_decompress(PGLZ_Header *source, char *dest) } else { - /* * An unset control bit means LITERAL BYTE. So we just * copy one from INPUT to OUTPUT. @@ -744,7 +737,6 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate) if (dstate->tocopy > 0) { - /* * Copy one byte from output to output until we did it for the * length specified by the last tag. Return that byte. @@ -755,7 +747,6 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate) if (dstate->ctrl_count == 0) { - /* * Get the next control byte if we need to, but check for EOF * before. @@ -838,7 +829,6 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate) dstate->ctrl_count--; if (dstate->ctrl & 0x01) { - /* * Bit is set, so tag is following. Setup copy information and do * the copy for the first byte as above. @@ -857,7 +847,6 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate) } else { - /* * Bit is unset, so literal byte follows. */ diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index 01cc5e45b3..b5f3744d51 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -9,41 +9,41 @@ #include "pgstat.h" -extern Datum pg_stat_get_numscans(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_tuples_returned(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_tuples_fetched(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_tuples_inserted(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_tuples_updated(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_tuples_deleted(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_blocks_fetched(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_blocks_hit(PG_FUNCTION_ARGS); - -extern Datum pg_stat_get_backend_idset(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_backend_pid(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_backend_dbid(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_backend_userid(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_backend_activity(PG_FUNCTION_ARGS); - -extern Datum pg_stat_get_db_numbackends(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_db_xact_commit(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_db_xact_rollback(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_db_blocks_fetched(PG_FUNCTION_ARGS); -extern Datum pg_stat_get_db_blocks_hit(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_numscans(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_tuples_returned(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_tuples_fetched(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_tuples_inserted(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_tuples_updated(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_tuples_deleted(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_blocks_fetched(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_blocks_hit(PG_FUNCTION_ARGS); + +extern Datum pg_stat_get_backend_idset(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_backend_pid(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_backend_dbid(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_backend_userid(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_backend_activity(PG_FUNCTION_ARGS); + +extern Datum pg_stat_get_db_numbackends(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_db_xact_commit(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_db_xact_rollback(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_db_blocks_fetched(PG_FUNCTION_ARGS); +extern Datum pg_stat_get_db_blocks_hit(PG_FUNCTION_ARGS); Datum pg_stat_get_numscans(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->numscans); + result = (int64) (tabentry->numscans); PG_RETURN_INT64(result); } @@ -52,16 +52,16 @@ pg_stat_get_numscans(PG_FUNCTION_ARGS) Datum pg_stat_get_tuples_returned(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->tuples_returned); + result = (int64) (tabentry->tuples_returned); PG_RETURN_INT64(result); } @@ -70,16 +70,16 @@ pg_stat_get_tuples_returned(PG_FUNCTION_ARGS) Datum pg_stat_get_tuples_fetched(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->tuples_fetched); + result = (int64) (tabentry->tuples_fetched); PG_RETURN_INT64(result); } @@ -88,16 +88,16 @@ pg_stat_get_tuples_fetched(PG_FUNCTION_ARGS) Datum pg_stat_get_tuples_inserted(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->tuples_inserted); + result = (int64) (tabentry->tuples_inserted); PG_RETURN_INT64(result); } @@ -106,16 +106,16 @@ pg_stat_get_tuples_inserted(PG_FUNCTION_ARGS) Datum pg_stat_get_tuples_updated(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->tuples_updated); + result = (int64) (tabentry->tuples_updated); PG_RETURN_INT64(result); } @@ -124,16 +124,16 @@ pg_stat_get_tuples_updated(PG_FUNCTION_ARGS) Datum pg_stat_get_tuples_deleted(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->tuples_deleted); + result = (int64) (tabentry->tuples_deleted); PG_RETURN_INT64(result); } @@ -142,16 +142,16 @@ pg_stat_get_tuples_deleted(PG_FUNCTION_ARGS) Datum pg_stat_get_blocks_fetched(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->blocks_fetched); + result = (int64) (tabentry->blocks_fetched); PG_RETURN_INT64(result); } @@ -160,16 +160,16 @@ pg_stat_get_blocks_fetched(PG_FUNCTION_ARGS) Datum pg_stat_get_blocks_hit(PG_FUNCTION_ARGS) { - PgStat_StatTabEntry *tabentry; - Oid relid; - int64 result; + PgStat_StatTabEntry *tabentry; + Oid relid; + int64 result; - relid = PG_GETARG_OID(0); + relid = PG_GETARG_OID(0); if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) result = 0; else - result = (int64)(tabentry->blocks_hit); + result = (int64) (tabentry->blocks_hit); PG_RETURN_INT64(result); } @@ -178,8 +178,8 @@ pg_stat_get_blocks_hit(PG_FUNCTION_ARGS) Datum pg_stat_get_backend_idset(PG_FUNCTION_ARGS) { - FmgrInfo *fmgr_info = fcinfo->flinfo; - int32 result; + FmgrInfo *fmgr_info = fcinfo->flinfo; + int32 result; if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo)) @@ -191,22 +191,22 @@ pg_stat_get_backend_idset(PG_FUNCTION_ARGS) elog(ERROR, "No function memory context in set-function"); fmgr_info->fn_extra = MemoryContextAlloc(fmgr_info->fn_mcxt, 2 * sizeof(int)); - ((int *)(fmgr_info->fn_extra))[0] = 0; - ((int *)(fmgr_info->fn_extra))[1] = pgstat_fetch_stat_numbackends(); + ((int *) (fmgr_info->fn_extra))[0] = 0; + ((int *) (fmgr_info->fn_extra))[1] = pgstat_fetch_stat_numbackends(); } - ((int *)(fmgr_info->fn_extra))[0] += 1; - result = ((int *)(fmgr_info->fn_extra))[0]; + ((int *) (fmgr_info->fn_extra))[0] += 1; + result = ((int *) (fmgr_info->fn_extra))[0]; - if (result > ((int *)(fmgr_info->fn_extra))[1]) + if (result > ((int *) (fmgr_info->fn_extra))[1]) { pfree(fmgr_info->fn_extra); fmgr_info->fn_extra = NULL; - ((ReturnSetInfo *)(fcinfo->resultinfo))->isDone = ExprEndResult; + ((ReturnSetInfo *) (fcinfo->resultinfo))->isDone = ExprEndResult; PG_RETURN_NULL(); } - ((ReturnSetInfo *)(fcinfo->resultinfo))->isDone = ExprMultipleResult; + ((ReturnSetInfo *) (fcinfo->resultinfo))->isDone = ExprMultipleResult; PG_RETURN_INT32(result); } @@ -214,10 +214,10 @@ pg_stat_get_backend_idset(PG_FUNCTION_ARGS) Datum pg_stat_get_backend_pid(PG_FUNCTION_ARGS) { - PgStat_StatBeEntry *beentry; - int32 beid; + PgStat_StatBeEntry *beentry; + int32 beid; - beid = PG_GETARG_INT32(0); + beid = PG_GETARG_INT32(0); if ((beentry = pgstat_fetch_stat_beentry(beid)) == NULL) PG_RETURN_NULL(); @@ -229,10 +229,10 @@ pg_stat_get_backend_pid(PG_FUNCTION_ARGS) Datum pg_stat_get_backend_dbid(PG_FUNCTION_ARGS) { - PgStat_StatBeEntry *beentry; - int32 beid; + PgStat_StatBeEntry *beentry; + int32 beid; - beid = PG_GETARG_INT32(0); + beid = PG_GETARG_INT32(0); if ((beentry = pgstat_fetch_stat_beentry(beid)) == NULL) PG_RETURN_NULL(); @@ -244,10 +244,10 @@ pg_stat_get_backend_dbid(PG_FUNCTION_ARGS) Datum pg_stat_get_backend_userid(PG_FUNCTION_ARGS) { - PgStat_StatBeEntry *beentry; - int32 beid; + PgStat_StatBeEntry *beentry; + int32 beid; - beid = PG_GETARG_INT32(0); + beid = PG_GETARG_INT32(0); if ((beentry = pgstat_fetch_stat_beentry(beid)) == NULL) PG_RETURN_NULL(); @@ -259,15 +259,15 @@ pg_stat_get_backend_userid(PG_FUNCTION_ARGS) Datum pg_stat_get_backend_activity(PG_FUNCTION_ARGS) { - PgStat_StatBeEntry *beentry; - int32 beid; - int len; - text *result; + PgStat_StatBeEntry *beentry; + int32 beid; + int len; + text *result; if (!superuser()) PG_RETURN_NULL(); - beid = PG_GETARG_INT32(0); + beid = PG_GETARG_INT32(0); if ((beentry = pgstat_fetch_stat_beentry(beid)) == NULL) PG_RETURN_NULL(); @@ -284,16 +284,16 @@ pg_stat_get_backend_activity(PG_FUNCTION_ARGS) Datum pg_stat_get_db_numbackends(PG_FUNCTION_ARGS) { - PgStat_StatDBEntry *dbentry; - Oid dbid; - int32 result; + PgStat_StatDBEntry *dbentry; + Oid dbid; + int32 result; - dbid = PG_GETARG_OID(0); + dbid = PG_GETARG_OID(0); if ((dbentry = pgstat_fetch_stat_dbentry(dbid)) == NULL) result = 0; else - result = (int32)(dbentry->n_backends); + result = (int32) (dbentry->n_backends); PG_RETURN_INT32(result); } @@ -302,16 +302,16 @@ pg_stat_get_db_numbackends(PG_FUNCTION_ARGS) Datum pg_stat_get_db_xact_commit(PG_FUNCTION_ARGS) { - PgStat_StatDBEntry *dbentry; - Oid dbid; - int64 result; + PgStat_StatDBEntry *dbentry; + Oid dbid; + int64 result; - dbid = PG_GETARG_OID(0); + dbid = PG_GETARG_OID(0); if ((dbentry = pgstat_fetch_stat_dbentry(dbid)) == NULL) result = 0; else - result = (int64)(dbentry->n_xact_commit); + result = (int64) (dbentry->n_xact_commit); PG_RETURN_INT64(result); } @@ -320,16 +320,16 @@ pg_stat_get_db_xact_commit(PG_FUNCTION_ARGS) Datum pg_stat_get_db_xact_rollback(PG_FUNCTION_ARGS) { - PgStat_StatDBEntry *dbentry; - Oid dbid; - int64 result; + PgStat_StatDBEntry *dbentry; + Oid dbid; + int64 result; - dbid = PG_GETARG_OID(0); + dbid = PG_GETARG_OID(0); if ((dbentry = pgstat_fetch_stat_dbentry(dbid)) == NULL) result = 0; else - result = (int64)(dbentry->n_xact_rollback); + result = (int64) (dbentry->n_xact_rollback); PG_RETURN_INT64(result); } @@ -338,16 +338,16 @@ pg_stat_get_db_xact_rollback(PG_FUNCTION_ARGS) Datum pg_stat_get_db_blocks_fetched(PG_FUNCTION_ARGS) { - PgStat_StatDBEntry *dbentry; - Oid dbid; - int64 result; + PgStat_StatDBEntry *dbentry; + Oid dbid; + int64 result; - dbid = PG_GETARG_OID(0); + dbid = PG_GETARG_OID(0); if ((dbentry = pgstat_fetch_stat_dbentry(dbid)) == NULL) result = 0; else - result = (int64)(dbentry->n_blocks_fetched); + result = (int64) (dbentry->n_blocks_fetched); PG_RETURN_INT64(result); } @@ -356,18 +356,16 @@ pg_stat_get_db_blocks_fetched(PG_FUNCTION_ARGS) Datum pg_stat_get_db_blocks_hit(PG_FUNCTION_ARGS) { - PgStat_StatDBEntry *dbentry; - Oid dbid; - int64 result; + PgStat_StatDBEntry *dbentry; + Oid dbid; + int64 result; - dbid = PG_GETARG_OID(0); + dbid = PG_GETARG_OID(0); if ((dbentry = pgstat_fetch_stat_dbentry(dbid)) == NULL) result = 0; else - result = (int64)(dbentry->n_blocks_hit); + result = (int64) (dbentry->n_blocks_hit); PG_RETURN_INT64(result); } - - diff --git a/src/backend/utils/adt/quote.c b/src/backend/utils/adt/quote.c index 10999150a2..45e4c1133d 100644 --- a/src/backend/utils/adt/quote.c +++ b/src/backend/utils/adt/quote.c @@ -7,7 +7,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/quote.c,v 1.4 2001/03/22 03:59:53 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/quote.c,v 1.5 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -289,5 +289,4 @@ do_quote_literal(text *lptr) return result; } - #endif diff --git a/src/backend/utils/adt/regexp.c b/src/backend/utils/adt/regexp.c index 146ae74263..926d7875ba 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.36 2001/03/22 03:59:53 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/regexp.c,v 1.37 2001/10/25 05:49:45 momjian Exp $ * * Alistair Crooks added the code for the regex caching * agc - cached the regular expressions used - there's a good chance @@ -121,7 +121,6 @@ RE_compile_and_execute(text *text_re, char *text, int cflags) regcomp_result = pg95_regcomp(&rev[oldest].cre_re, re, cflags); if (regcomp_result == 0) { - /* * use malloc/free for the cre_s field because the storage has to * persist across transactions diff --git a/src/backend/utils/adt/regproc.c b/src/backend/utils/adt/regproc.c index 3ae65c6c8e..b06001af3d 100644 --- a/src/backend/utils/adt/regproc.c +++ b/src/backend/utils/adt/regproc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/regproc.c,v 1.63 2001/08/21 16:36:04 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/regproc.c,v 1.64 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -53,9 +53,9 @@ regprocin(PG_FUNCTION_ARGS) Oid searchOid; searchOid = DatumGetObjectId(DirectFunctionCall1(oidin, - CStringGetDatum(pro_name_or_oid))); + CStringGetDatum(pro_name_or_oid))); result = (RegProcedure) GetSysCacheOid(PROCOID, - ObjectIdGetDatum(searchOid), + ObjectIdGetDatum(searchOid), 0, 0, 0); if (!RegProcedureIsValid(result)) elog(ERROR, "No procedure with oid %s", pro_name_or_oid); diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c index a03ca77440..b71732a194 100644 --- a/src/backend/utils/adt/ri_triggers.c +++ b/src/backend/utils/adt/ri_triggers.c @@ -18,7 +18,7 @@ * Portions Copyright (c) 2000-2001, PostgreSQL Global Development Group * Copyright 1999 Jan Wieck * - * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.28 2001/10/06 23:21:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.29 2001/10/25 05:49:45 momjian Exp $ * * ---------- */ @@ -423,7 +423,6 @@ RI_FKey_check(PG_FUNCTION_ARGS) */ for (i = 0; i < qkey.nkeypairs; i++) { - /* * We can implement MATCH PARTIAL by excluding this column from * the query if it is null. Simple! Unfortunately, the @@ -2140,7 +2139,6 @@ RI_FKey_setnull_upd(PG_FUNCTION_ARGS) qualsep = "WHERE"; for (i = 0; i < qkey.nkeypairs; i++) { - /* * MATCH <unspecified> - only change columns * corresponding to changed columns in pk_rel's key @@ -2402,7 +2400,6 @@ RI_FKey_setdefault_del(PG_FUNCTION_ARGS) defval = NULL; for (i = 0; i < qkey.nkeypairs && defval != NULL; i++) { - /* * For each key attribute lookup the tuple constructor * for a corresponding default value @@ -2412,7 +2409,6 @@ RI_FKey_setdefault_del(PG_FUNCTION_ARGS) if (defval[j].adnum == qkey.keypair[i][RI_KEYPAIR_FK_IDX]) { - /* * That's the one - push the expression from * defval.adbin into the plan's targetlist @@ -2629,7 +2625,6 @@ RI_FKey_setdefault_upd(PG_FUNCTION_ARGS) qualsep = "WHERE"; for (i = 0; i < qkey.nkeypairs; i++) { - /* * MATCH <unspecified> - only change columns * corresponding to changed columns in pk_rel's key @@ -2669,7 +2664,6 @@ RI_FKey_setdefault_upd(PG_FUNCTION_ARGS) defval = NULL; for (i = 0; i < qkey.nkeypairs && defval != NULL; i++) { - /* * MATCH <unspecified> - only change columns * corresponding to changed columns in pk_rel's key. @@ -2680,7 +2674,6 @@ RI_FKey_setdefault_upd(PG_FUNCTION_ARGS) !ri_OneKeyEqual(pk_rel, i, old_row, new_row, &qkey, RI_KEYPAIR_PK_IDX)) { - /* * For each key attribute lookup the tuple * constructor for a corresponding default value @@ -2690,7 +2683,6 @@ RI_FKey_setdefault_upd(PG_FUNCTION_ARGS) if (defval[j].adnum == qkey.keypair[i][RI_KEYPAIR_FK_IDX]) { - /* * That's the one - push the expression * from defval.adbin into the plan's @@ -2807,7 +2799,6 @@ RI_FKey_keyequal_upd(TriggerData *trigdata) switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO])) { - /* * MATCH <UNSPECIFIED> */ @@ -3079,7 +3070,6 @@ ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, for (i = 0; i < key->nkeypairs; i++) { - /* * Get one attributes oldvalue. If it is NULL - they're not equal. */ @@ -3129,7 +3119,6 @@ ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup, keys_unequal = true; for (i = 0; keys_unequal && i < key->nkeypairs; i++) { - /* * Get one attributes oldvalue. If it is NULL - they're not equal. */ @@ -3252,17 +3241,17 @@ ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue) CharGetDatum('b')); if (!HeapTupleIsValid(opr_tup)) elog(ERROR, - "ri_AttributesEqual(): cannot find '=' operator for type %u", + "ri_AttributesEqual(): cannot find '=' operator for type %u", typeid); opr_proc = ((Form_pg_operator) GETSTRUCT(opr_tup))->oprcode; ReleaseSysCache(opr_tup); /* * Since fmgr_info could fail, call it *before* creating the - * hashtable entry --- otherwise we could elog leaving an incomplete - * entry in the hashtable. Also, because this will be a permanent - * table entry, we must make sure any subsidiary structures of the - * fmgr record are kept in TopMemoryContext. + * hashtable entry --- otherwise we could elog leaving an + * incomplete entry in the hashtable. Also, because this will be + * a permanent table entry, we must make sure any subsidiary + * structures of the fmgr record are kept in TopMemoryContext. */ fmgr_info_cxt(opr_proc, &finfo, TopMemoryContext); diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index 1d1969e68d..3ed36783f5 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.85 2001/10/08 19:55:07 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v 1.86 2001/10/25 05:49:45 momjian Exp $ * * This software is copyrighted by Jan Wieck - Hamburg. * @@ -84,7 +84,7 @@ typedef struct List *rtable; /* List of RangeTblEntry nodes */ List *namespace; /* List of joinlist items (RangeTblRef and * JoinExpr nodes) */ -} deparse_namespace; +} deparse_namespace; /* ---------- @@ -118,8 +118,8 @@ static void get_basic_select_query(Query *query, deparse_context *context); static void get_setop_query(Node *setOp, Query *query, deparse_context *context, bool toplevel); static void get_rule_sortgroupclause(SortClause *srt, List *tlist, - bool force_colno, - deparse_context *context); + bool force_colno, + deparse_context *context); static void get_names_for_var(Var *var, deparse_context *context, char **refname, char **attname); static bool get_alias_for_case(CaseExpr *caseexpr, deparse_context *context, @@ -138,7 +138,7 @@ static void get_from_clause(Query *query, deparse_context *context); static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context); static void get_opclass_name(Oid opclass, Oid actual_datatype, - StringInfo buf); + StringInfo buf); static bool tleIsArrayAssign(TargetEntry *tle); static char *quote_identifier(char *ident); static char *get_relation_name(Oid relid); @@ -302,7 +302,6 @@ pg_get_viewdef(PG_FUNCTION_ARGS) appendStringInfo(&buf, "Not a view"); else { - /* * Get the rules definition and put it into executors memory */ @@ -409,7 +408,7 @@ pg_get_indexdef(PG_FUNCTION_ARGS) sep = ""; for (keyno = 0; keyno < INDEX_MAX_KEYS; keyno++) { - AttrNumber attnum = idxrec->indkey[keyno]; + AttrNumber attnum = idxrec->indkey[keyno]; if (attnum == InvalidAttrNumber) break; @@ -470,16 +469,17 @@ pg_get_indexdef(PG_FUNCTION_ARGS) */ if (VARSIZE(&idxrec->indpred) > VARHDRSZ) { - Node *node; - List *context; - char *exprstr; - char *str; + Node *node; + List *context; + char *exprstr; + char *str; /* Convert TEXT object to C string */ exprstr = DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(&idxrec->indpred))); + PointerGetDatum(&idxrec->indpred))); /* Convert expression to node tree */ node = (Node *) stringToNode(exprstr); + /* * If top level is a List, assume it is an implicit-AND structure, * and convert to explicit AND. This is needed for partial index @@ -528,14 +528,14 @@ pg_get_indexdef(PG_FUNCTION_ARGS) Datum pg_get_expr(PG_FUNCTION_ARGS) { - text *expr = PG_GETARG_TEXT_P(0); - Oid relid = PG_GETARG_OID(1); - text *result; - Node *node; - List *context; - char *exprstr; - char *relname; - char *str; + text *expr = PG_GETARG_TEXT_P(0); + Oid relid = PG_GETARG_OID(1); + text *result; + Node *node; + List *context; + char *exprstr; + char *relname; + char *str; /* Get the name for the relation */ relname = get_rel_name(relid); @@ -550,19 +550,17 @@ pg_get_expr(PG_FUNCTION_ARGS) node = (Node *) stringToNode(exprstr); /* - * If top level is a List, assume it is an implicit-AND structure, - * and convert to explicit AND. This is needed for partial index + * 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); - } /* Deparse */ context = deparse_context_for(relname, relid); str = deparse_expression(node, context, false); - + /* Pass the result back as TEXT */ result = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(str))); @@ -1178,10 +1176,11 @@ get_rule_sortgroupclause(SortClause *srt, List *tlist, bool force_colno, tle = get_sortgroupclause_tle(srt, tlist); expr = tle->expr; + /* * Use column-number form if requested by caller or if expression is a - * constant --- a constant is ambiguous (and will be misinterpreted - * by findTargetlistEntry()) if we dump it explicitly. + * constant --- a constant is ambiguous (and will be misinterpreted by + * findTargetlistEntry()) if we dump it explicitly. */ if (force_colno || (expr && IsA(expr, Const))) { @@ -1938,54 +1937,54 @@ get_rule_expr(Node *node, deparse_context *context) case T_NullTest: { - NullTest *ntest = (NullTest *) node; + NullTest *ntest = (NullTest *) node; appendStringInfo(buf, "("); get_rule_expr(ntest->arg, context); - switch (ntest->nulltesttype) - { - case IS_NULL: + switch (ntest->nulltesttype) + { + case IS_NULL: appendStringInfo(buf, " IS NULL)"); break; - case IS_NOT_NULL: + case IS_NOT_NULL: appendStringInfo(buf, " IS NOT NULL)"); break; - default: - elog(ERROR, "get_rule_expr: unexpected nulltesttype %d", - (int) ntest->nulltesttype); + default: + elog(ERROR, "get_rule_expr: unexpected nulltesttype %d", + (int) ntest->nulltesttype); } } break; case T_BooleanTest: { - BooleanTest *btest = (BooleanTest *) node; + BooleanTest *btest = (BooleanTest *) node; appendStringInfo(buf, "("); get_rule_expr(btest->arg, context); - switch (btest->booltesttype) - { - case IS_TRUE: + switch (btest->booltesttype) + { + case IS_TRUE: appendStringInfo(buf, " IS TRUE)"); break; - case IS_NOT_TRUE: + case IS_NOT_TRUE: appendStringInfo(buf, " IS NOT TRUE)"); break; - case IS_FALSE: + case IS_FALSE: appendStringInfo(buf, " IS FALSE)"); break; - case IS_NOT_FALSE: + case IS_NOT_FALSE: appendStringInfo(buf, " IS NOT FALSE)"); break; - case IS_UNKNOWN: + case IS_UNKNOWN: appendStringInfo(buf, " IS UNKNOWN)"); break; - case IS_NOT_UNKNOWN: + case IS_NOT_UNKNOWN: appendStringInfo(buf, " IS NOT UNKNOWN)"); break; - default: - elog(ERROR, "get_rule_expr: unexpected booltesttype %d", - (int) btest->booltesttype); + default: + elog(ERROR, "get_rule_expr: unexpected booltesttype %d", + (int) btest->booltesttype); } } break; @@ -2051,14 +2050,15 @@ get_func_expr(Expr *expr, deparse_context *context) appendStringInfoChar(buf, '('); get_rule_expr(arg, context); + /* * Show typename with appropriate length decoration. Note that * since exprIsLengthCoercion succeeded, the function's output * type is the right thing to use. * * XXX In general it is incorrect to quote the result of - * format_type_with_typemod, but are there any special cases - * where we should do so? + * format_type_with_typemod, but are there any special cases where + * we should do so? */ typdesc = format_type_with_typemod(procStruct->prorettype, coercedTypmod); @@ -2107,7 +2107,7 @@ strip_type_coercion(Node *expr, Oid resultType) if (IsA(expr, RelabelType)) return strip_type_coercion(((RelabelType *) expr)->arg, resultType); - if (IsA(expr, Expr) && ((Expr *) expr)->opType == FUNC_EXPR) + if (IsA(expr, Expr) &&((Expr *) expr)->opType == FUNC_EXPR) { Func *func; HeapTuple procTuple; @@ -2135,7 +2135,7 @@ strip_type_coercion(Node *expr, Oid resultType) } /* See if function has same name as its result type */ typeTuple = SearchSysCache(TYPEOID, - ObjectIdGetDatum(procStruct->prorettype), + ObjectIdGetDatum(procStruct->prorettype), 0, 0, 0); if (!HeapTupleIsValid(typeTuple)) elog(ERROR, "cache lookup for type %u failed", @@ -2221,7 +2221,6 @@ get_const_expr(Const *constval, deparse_context *context) if (constval->constisnull) { - /* * Always label the type of a NULL constant. This not only * prevents misdecisions about the type, but it ensures that our @@ -2625,7 +2624,6 @@ tleIsArrayAssign(TargetEntry *tle) static char * quote_identifier(char *ident) { - /* * Can avoid quoting if ident starts with a lowercase letter and * contains only lowercase letters, digits, and underscores, *and* is @@ -2657,7 +2655,6 @@ quote_identifier(char *ident) if (safe) { - /* * Check for keyword. This test is overly strong, since many of * the "keywords" known to the parser are usable as column names, diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c index 306758ff77..e7d319e9b6 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.99 2001/10/13 23:32:33 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/selfuncs.c,v 1.100 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -100,7 +100,7 @@ /* * Note: the default selectivity estimates are not chosen entirely at random. * We want them to be small enough to ensure that indexscans will be used if - * available, for typical table densities of ~100 tuples/page. Thus, for + * available, for typical table densities of ~100 tuples/page. Thus, for * example, 0.01 is not quite small enough, since that makes it appear that * nearly all pages will be hit anyway. Also, since we sometimes estimate * eqsel as 1/num_distinct, we probably want DEFAULT_NUM_DISTINCT to equal @@ -135,22 +135,22 @@ static void convert_string_to_scalar(unsigned char *value, unsigned char *hibound, double *scaledhibound); static void convert_bytea_to_scalar(Datum value, - double *scaledvalue, - Datum lobound, - double *scaledlobound, - Datum hibound, - double *scaledhibound); + double *scaledvalue, + Datum lobound, + double *scaledlobound, + Datum hibound, + double *scaledhibound); static double convert_one_string_to_scalar(unsigned char *value, int rangelo, int rangehi); static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, - int rangelo, int rangehi); + int rangelo, int rangehi); static unsigned char *convert_string_datum(Datum value, Oid typid); static double convert_timevalue_to_scalar(Datum value, Oid typid); static double get_att_numdistinct(Query *root, Var *var, - Form_pg_statistic stats); + Form_pg_statistic stats); static bool get_restriction_var(List *args, int varRelid, - Var **var, Node **other, - bool *varonleft); + Var **var, Node **other, + bool *varonleft); static void get_join_vars(List *args, Var **var1, Var **var2); static Selectivity prefix_selectivity(Query *root, Var *var, char *prefix); static Selectivity pattern_selectivity(char *patt, Pattern_Type ptype); @@ -188,9 +188,9 @@ eqsel(PG_FUNCTION_ARGS) double selec; /* - * If expression is not var = something or something = var for - * a simple var of a real relation (no subqueries, for now), - * then punt and return a default estimate. + * If expression is not var = something or something = var for a + * simple var of a real relation (no subqueries, for now), then punt + * and return a default estimate. */ if (!get_restriction_var(args, varRelid, &var, &other, &varonleft)) @@ -200,10 +200,10 @@ eqsel(PG_FUNCTION_ARGS) PG_RETURN_FLOAT8(DEFAULT_EQ_SEL); /* - * If the something is a NULL constant, assume operator is strict - * and return zero, ie, operator will never return TRUE. + * If the something is a NULL constant, assume operator is strict and + * return zero, ie, operator will never return TRUE. */ - if (IsA(other, Const) && ((Const *) other)->constisnull) + if (IsA(other, Const) &&((Const *) other)->constisnull) PG_RETURN_FLOAT8(0.0); /* get stats for the attribute, if available */ @@ -220,15 +220,15 @@ eqsel(PG_FUNCTION_ARGS) if (IsA(other, Const)) { /* Var is being compared to a known non-null constant */ - Datum constval = ((Const *) other)->constvalue; - bool match = false; - int i; + Datum constval = ((Const *) other)->constvalue; + bool match = false; + int i; /* * Is the constant "=" to any of the column's most common - * values? (Although the given operator may not really be - * "=", we will assume that seeing whether it returns TRUE - * is an appropriate test. If you don't like this, maybe you + * values? (Although the given operator may not really be + * "=", we will assume that seeing whether it returns TRUE is + * an appropriate test. If you don't like this, maybe you * shouldn't be using eqsel for your operator...) */ if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod, @@ -267,41 +267,42 @@ eqsel(PG_FUNCTION_ARGS) { /* * Constant is "=" to this common value. We know - * selectivity exactly (or as exactly as VACUUM - * could calculate it, anyway). + * selectivity exactly (or as exactly as VACUUM could + * calculate it, anyway). */ selec = numbers[i]; } else { /* - * Comparison is against a constant that is neither - * NULL nor any of the common values. Its selectivity - * cannot be more than this: + * Comparison is against a constant that is neither NULL + * nor any of the common values. Its selectivity cannot + * be more than this: */ - double sumcommon = 0.0; - double otherdistinct; + double sumcommon = 0.0; + double otherdistinct; for (i = 0; i < nnumbers; i++) sumcommon += numbers[i]; selec = 1.0 - sumcommon - stats->stanullfrac; + /* - * and in fact it's probably a good deal less. - * We approximate that all the not-common values - * share this remaining fraction equally, so we - * divide by the number of other distinct values. + * and in fact it's probably a good deal less. We + * approximate that all the not-common values share this + * remaining fraction equally, so we divide by the number + * of other distinct values. */ otherdistinct = get_att_numdistinct(root, var, stats) - nnumbers; if (otherdistinct > 1) selec /= otherdistinct; + /* - * Another cross-check: selectivity shouldn't be - * estimated as more than the least common - * "most common value". + * Another cross-check: selectivity shouldn't be estimated + * as more than the least common "most common value". */ - if (nnumbers > 0 && selec > numbers[nnumbers-1]) - selec = numbers[nnumbers-1]; + if (nnumbers > 0 && selec > numbers[nnumbers - 1]) + selec = numbers[nnumbers - 1]; } free_attstatsslot(var->vartype, values, nvalues, @@ -312,22 +313,23 @@ eqsel(PG_FUNCTION_ARGS) double ndistinct; /* - * Search is for a value that we do not know a priori, but - * we will assume it is not NULL. Estimate the selectivity - * as non-null fraction divided by number of distinct values, - * so that we get a result averaged over all possible values - * whether common or uncommon. (Essentially, we are assuming + * Search is for a value that we do not know a priori, but we + * will assume it is not NULL. Estimate the selectivity as + * non-null fraction divided by number of distinct values, so + * that we get a result averaged over all possible values + * whether common or uncommon. (Essentially, we are assuming * that the not-yet-known comparison value is equally likely * to be any of the possible values, regardless of their - * frequency in the table. Is that a good idea?) + * frequency in the table. Is that a good idea?) */ selec = 1.0 - stats->stanullfrac; ndistinct = get_att_numdistinct(root, var, stats); if (ndistinct > 1) selec /= ndistinct; + /* - * Cross-check: selectivity should never be - * estimated as more than the most common value's. + * Cross-check: selectivity should never be estimated as more + * than the most common value's. */ if (get_attstatsslot(statsTuple, var->vartype, var->vartypmod, STATISTIC_KIND_MCV, InvalidOid, @@ -347,8 +349,8 @@ eqsel(PG_FUNCTION_ARGS) /* * No VACUUM ANALYZE stats available, so make a guess using * estimated number of distinct values and assuming they are - * equally common. (The guess is unlikely to be very good, - * but we do know a few special cases.) + * equally common. (The guess is unlikely to be very good, but we + * do know a few special cases.) */ selec = 1.0 / get_att_numdistinct(root, var, NULL); } @@ -387,10 +389,10 @@ neqsel(PG_FUNCTION_ARGS) if (eqop) { result = DatumGetFloat8(DirectFunctionCall4(eqsel, - PointerGetDatum(root), - ObjectIdGetDatum(eqop), - PointerGetDatum(args), - Int32GetDatum(varRelid))); + PointerGetDatum(root), + ObjectIdGetDatum(eqop), + PointerGetDatum(args), + Int32GetDatum(varRelid))); } else { @@ -433,23 +435,24 @@ scalarineqsel(Query *root, Oid operator, bool isgt, int i; /* - * If expression is not var op something or something op var for - * a simple var of a real relation (no subqueries, for now), - * then punt and return a default estimate. + * If expression is not var op something or something op var for a + * simple var of a real relation (no subqueries, for now), then punt + * and return a default estimate. */ relid = getrelid(var->varno, root->rtable); if (relid == InvalidOid) return DEFAULT_INEQ_SEL; /* - * Can't do anything useful if the something is not a constant, either. + * Can't do anything useful if the something is not a constant, + * either. */ - if (! IsA(other, Const)) + if (!IsA(other, Const)) return DEFAULT_INEQ_SEL; /* - * If the constant is NULL, assume operator is strict - * and return zero, ie, operator will never return TRUE. + * If the constant is NULL, assume operator is strict and return zero, + * ie, operator will never return TRUE. */ if (((Const *) other)->constisnull) return 0.0; @@ -471,9 +474,9 @@ scalarineqsel(Query *root, Oid operator, bool isgt, fmgr_info(get_opcode(operator), &opproc); /* - * If we have most-common-values info, add up the fractions of the - * MCV entries that satisfy MCV OP CONST. These fractions contribute - * directly to the result selectivity. Also add up the total fraction + * If we have most-common-values info, add up the fractions of the MCV + * entries that satisfy MCV OP CONST. These fractions contribute + * directly to the result selectivity. Also add up the total fraction * represented by MCV entries. */ mcv_selec = 0.0; @@ -517,8 +520,8 @@ scalarineqsel(Query *root, Oid operator, bool isgt, { if (nvalues > 1) { - double histfrac; - bool ltcmp; + double histfrac; + bool ltcmp; ltcmp = DatumGetBool(FunctionCall2(&opproc, values[0], @@ -533,9 +536,10 @@ scalarineqsel(Query *root, Oid operator, bool isgt, else { /* - * Scan to find proper location. This could be made faster - * by using a binary-search method, but it's probably not - * worth the trouble for typical histogram sizes. + * Scan to find proper location. This could be made + * faster by using a binary-search method, but it's + * probably not worth the trouble for typical histogram + * sizes. */ for (i = 1; i < nvalues; i++) { @@ -563,11 +567,11 @@ scalarineqsel(Query *root, Oid operator, bool isgt, * We have values[i-1] < constant < values[i]. * * Convert the constant and the two nearest bin boundary - * values to a uniform comparison scale, and do a linear - * interpolation within this bin. + * values to a uniform comparison scale, and do a + * linear interpolation within this bin. */ if (convert_to_scalar(constval, consttype, &val, - values[i-1], values[i], + values[i - 1], values[i], var->vartype, &low, &high)) { @@ -583,11 +587,12 @@ scalarineqsel(Query *root, Oid operator, bool isgt, else { binfrac = (val - low) / (high - low); + /* - * Watch out for the possibility that we got a NaN - * or Infinity from the division. This can happen - * despite the previous checks, if for example - * "low" is -Infinity. + * Watch out for the possibility that we got a + * NaN or Infinity from the division. This + * can happen despite the previous checks, if + * for example "low" is -Infinity. */ if (isnan(binfrac) || binfrac < 0.0 || binfrac > 1.0) @@ -597,35 +602,40 @@ scalarineqsel(Query *root, Oid operator, bool isgt, else { /* - * Ideally we'd produce an error here, on the grounds - * that the given operator shouldn't have scalarXXsel - * registered as its selectivity func unless we can - * deal with its operand types. But currently, all - * manner of stuff is invoking scalarXXsel, so give a - * default estimate until that can be fixed. + * Ideally we'd produce an error here, on the + * grounds that the given operator shouldn't have + * scalarXXsel registered as its selectivity func + * unless we can deal with its operand types. But + * currently, all manner of stuff is invoking + * scalarXXsel, so give a default estimate until + * that can be fixed. */ binfrac = 0.5; } + /* - * Now, compute the overall selectivity across the values - * represented by the histogram. We have i-1 full bins - * and binfrac partial bin below the constant. + * Now, compute the overall selectivity across the + * values represented by the histogram. We have i-1 + * full bins and binfrac partial bin below the + * constant. */ - histfrac = (double) (i-1) + binfrac; + histfrac = (double) (i - 1) + binfrac; histfrac /= (double) (nvalues - 1); } } + /* - * Now histfrac = fraction of histogram entries below the constant. + * Now histfrac = fraction of histogram entries below the + * constant. * * Account for "<" vs ">" */ hist_selec = isgt ? (1.0 - histfrac) : histfrac; + /* * The histogram boundaries are only approximate to begin - * with, and may well be out of date anyway. Therefore, - * don't believe extremely small or large selectivity - * estimates. + * with, and may well be out of date anyway. Therefore, don't + * believe extremely small or large selectivity estimates. */ if (hist_selec < 0.0001) hist_selec = 0.0001; @@ -684,9 +694,9 @@ scalarltsel(PG_FUNCTION_ARGS) double selec; /* - * If expression is not var op something or something op var for - * a simple var of a real relation (no subqueries, for now), - * then punt and return a default estimate. + * If expression is not var op something or something op var for a + * simple var of a real relation (no subqueries, for now), then punt + * and return a default estimate. */ if (!get_restriction_var(args, varRelid, &var, &other, &varonleft)) @@ -734,9 +744,9 @@ scalargtsel(PG_FUNCTION_ARGS) double selec; /* - * If expression is not var op something or something op var for - * a simple var of a real relation (no subqueries, for now), - * then punt and return a default estimate. + * If expression is not var op something or something op var for a + * simple var of a real relation (no subqueries, for now), then punt + * and return a default estimate. */ if (!get_restriction_var(args, varRelid, &var, &other, &varonleft)) @@ -774,6 +784,7 @@ static double patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype) { Query *root = (Query *) PG_GETARG_POINTER(0); + #ifdef NOT_USED Oid operator = PG_GETARG_OID(1); #endif @@ -791,9 +802,9 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype) double result; /* - * If expression is not var op constant for - * a simple var of a real relation (no subqueries, for now), - * then punt and return a default estimate. + * If expression is not var op constant for a simple var of a real + * relation (no subqueries, for now), then punt and return a default + * estimate. */ if (!get_restriction_var(args, varRelid, &var, &other, &varonleft)) @@ -805,8 +816,8 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype) return DEFAULT_MATCH_SEL; /* - * If the constant is NULL, assume operator is strict - * and return zero, ie, operator will never return TRUE. + * If the constant is NULL, assume operator is strict and return zero, + * ie, operator will never return TRUE. */ if (((Const *) other)->constisnull) return 0.0; @@ -834,16 +845,16 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype) eqargs = makeList2(var, eqcon); result = DatumGetFloat8(DirectFunctionCall4(eqsel, PointerGetDatum(root), - ObjectIdGetDatum(eqopr), - PointerGetDatum(eqargs), - Int32GetDatum(varRelid))); + ObjectIdGetDatum(eqopr), + PointerGetDatum(eqargs), + Int32GetDatum(varRelid))); } else { /* - * Not exact-match pattern. We estimate selectivity of the - * fixed prefix and remainder of pattern separately, then - * combine the two. + * Not exact-match pattern. We estimate selectivity of the fixed + * prefix and remainder of pattern separately, then combine the + * two. */ Selectivity prefixsel; Selectivity restsel; @@ -964,28 +975,28 @@ icnlikesel(PG_FUNCTION_ARGS) Selectivity booltestsel(Query *root, BooleanTest *clause, int varRelid) { - Var *var; - Node *arg; - Oid relid; - HeapTuple statsTuple; - Datum *values; - int nvalues; - float4 *numbers; - int nnumbers; - double selec; + Var *var; + Node *arg; + Oid relid; + HeapTuple statsTuple; + Datum *values; + int nvalues; + float4 *numbers; + int nnumbers; + double selec; Assert(clause && IsA(clause, BooleanTest)); arg = (Node *) clause->arg; /* - * Ignore any binary-compatible relabeling (probably unnecessary, - * but can't hurt) + * Ignore any binary-compatible relabeling (probably unnecessary, but + * can't hurt) */ if (IsA(arg, RelabelType)) arg = ((RelabelType *) arg)->arg; - if (IsA(arg, Var) && (varRelid == 0 || varRelid == ((Var *) arg)->varno)) + if (IsA(arg, Var) &&(varRelid == 0 || varRelid == ((Var *) arg)->varno)) var = (Var *) arg; else { @@ -996,24 +1007,24 @@ booltestsel(Query *root, BooleanTest *clause, int varRelid) * and just assume the value is either TRUE or FALSE. */ switch (clause->booltesttype) - { + { case IS_UNKNOWN: selec = DEFAULT_UNK_SEL; break; case IS_NOT_UNKNOWN: selec = DEFAULT_NOT_UNK_SEL; break; - case IS_TRUE: - case IS_NOT_FALSE: + case IS_TRUE: + case IS_NOT_FALSE: selec = (double) clause_selectivity(root, arg, varRelid); break; - case IS_FALSE: - case IS_NOT_TRUE: + case IS_FALSE: + case IS_NOT_TRUE: selec = 1.0 - (double) clause_selectivity(root, arg, varRelid); break; - default: - elog(ERROR, "booltestsel: unexpected booltesttype %d", - (int) clause->booltesttype); + default: + elog(ERROR, "booltestsel: unexpected booltesttype %d", + (int) clause->booltesttype); selec = 0.0; /* Keep compiler quiet */ break; } @@ -1033,7 +1044,7 @@ booltestsel(Query *root, BooleanTest *clause, int varRelid) if (HeapTupleIsValid(statsTuple)) { Form_pg_statistic stats; - double freq_null; + double freq_null; stats = (Form_pg_statistic) GETSTRUCT(statsTuple); @@ -1045,8 +1056,8 @@ booltestsel(Query *root, BooleanTest *clause, int varRelid) &numbers, &nnumbers) && nnumbers > 0) { - double freq_true; - double freq_false; + double freq_true; + double freq_false; /* * Get first MCV frequency and derive frequency for true. @@ -1057,41 +1068,41 @@ booltestsel(Query *root, BooleanTest *clause, int varRelid) freq_true = 1.0 - numbers[0] - freq_null; /* - * Next derive freqency for false. - * Then use these as appropriate to derive frequency for each case. + * Next derive freqency for false. Then use these as + * appropriate to derive frequency for each case. */ freq_false = 1.0 - freq_true - freq_null; switch (clause->booltesttype) - { - case IS_UNKNOWN: + { + case IS_UNKNOWN: /* select only NULL values */ selec = freq_null; break; - case IS_NOT_UNKNOWN: + case IS_NOT_UNKNOWN: /* select non-NULL values */ selec = 1.0 - freq_null; break; - case IS_TRUE: + case IS_TRUE: /* select only TRUE values */ selec = freq_true; break; - case IS_NOT_TRUE: + case IS_NOT_TRUE: /* select non-TRUE values */ selec = 1.0 - freq_true; break; - case IS_FALSE: + case IS_FALSE: /* select only FALSE values */ selec = freq_false; break; - case IS_NOT_FALSE: + case IS_NOT_FALSE: /* select non-FALSE values */ selec = 1.0 - freq_false; break; - default: - elog(ERROR, "booltestsel: unexpected booltesttype %d", - (int) clause->booltesttype); - selec = 0.0; /* Keep compiler quiet */ + default: + elog(ERROR, "booltestsel: unexpected booltesttype %d", + (int) clause->booltesttype); + selec = 0.0; /* Keep compiler quiet */ break; } @@ -1101,37 +1112,38 @@ booltestsel(Query *root, BooleanTest *clause, int varRelid) else { /* - * No most-common-value info available. - * Still have null fraction information, - * so use it for IS [NOT] UNKNOWN. - * Otherwise adjust for null fraction and - * assume an even split for boolean tests. + * No most-common-value info available. Still have null + * fraction information, so use it for IS [NOT] UNKNOWN. + * Otherwise adjust for null fraction and assume an even split + * for boolean tests. */ switch (clause->booltesttype) - { - case IS_UNKNOWN: + { + case IS_UNKNOWN: + /* * Use freq_null directly. */ selec = freq_null; break; - case IS_NOT_UNKNOWN: + case IS_NOT_UNKNOWN: + /* - * Select not unknown (not null) values. - * Calculate from freq_null. + * Select not unknown (not null) values. Calculate + * from freq_null. */ selec = 1.0 - freq_null; break; - case IS_TRUE: - case IS_NOT_TRUE: - case IS_FALSE: - case IS_NOT_FALSE: + case IS_TRUE: + case IS_NOT_TRUE: + case IS_FALSE: + case IS_NOT_FALSE: selec = (1.0 - freq_null) / 2.0; break; - default: - elog(ERROR, "booltestsel: unexpected booltesttype %d", - (int) clause->booltesttype); - selec = 0.0; /* Keep compiler quiet */ + default: + elog(ERROR, "booltestsel: unexpected booltesttype %d", + (int) clause->booltesttype); + selec = 0.0; /* Keep compiler quiet */ break; } } @@ -1161,7 +1173,7 @@ booltestsel(Query *root, BooleanTest *clause, int varRelid) default: elog(ERROR, "booltestsel: unexpected booltesttype %d", (int) clause->booltesttype); - selec = 0.0; /* Keep compiler quiet */ + selec = 0.0; /* Keep compiler quiet */ break; } } @@ -1181,28 +1193,28 @@ booltestsel(Query *root, BooleanTest *clause, int varRelid) Selectivity nulltestsel(Query *root, NullTest *clause, int varRelid) { - Var *var; - Node *arg; - Oid relid; - HeapTuple statsTuple; - double selec; - double defselec; - double freq_null; + Var *var; + Node *arg; + Oid relid; + HeapTuple statsTuple; + double selec; + double defselec; + double freq_null; Assert(clause && IsA(clause, NullTest)); switch (clause->nulltesttype) - { - case IS_NULL: + { + case IS_NULL: defselec = DEFAULT_UNK_SEL; break; - case IS_NOT_NULL: + case IS_NOT_NULL: defselec = DEFAULT_NOT_UNK_SEL; break; - default: - elog(ERROR, "nulltestsel: unexpected nulltesttype %d", - (int) clause->nulltesttype); - return (Selectivity) 0; /* keep compiler quiet */ + default: + elog(ERROR, "nulltestsel: unexpected nulltesttype %d", + (int) clause->nulltesttype); + return (Selectivity) 0; /* keep compiler quiet */ } arg = (Node *) clause->arg; @@ -1213,7 +1225,7 @@ nulltestsel(Query *root, NullTest *clause, int varRelid) if (IsA(arg, RelabelType)) arg = ((RelabelType *) arg)->arg; - if (IsA(arg, Var) && (varRelid == 0 || varRelid == ((Var *) arg)->varno)) + if (IsA(arg, Var) &&(varRelid == 0 || varRelid == ((Var *) arg)->varno)) var = (Var *) arg; else { @@ -1225,7 +1237,7 @@ nulltestsel(Query *root, NullTest *clause, int varRelid) relid = getrelid(var->varno, root->rtable); if (relid == InvalidOid) - return (Selectivity) defselec; + return (Selectivity) defselec; /* get stats for the attribute, if available */ statsTuple = SearchSysCache(STATRELATT, @@ -1240,24 +1252,26 @@ nulltestsel(Query *root, NullTest *clause, int varRelid) freq_null = stats->stanullfrac; switch (clause->nulltesttype) - { - case IS_NULL: + { + case IS_NULL: + /* * Use freq_null directly. */ selec = freq_null; break; - case IS_NOT_NULL: + case IS_NOT_NULL: + /* - * Select not unknown (not null) values. - * Calculate from freq_null. + * Select not unknown (not null) values. Calculate from + * freq_null. */ selec = 1.0 - freq_null; break; - default: - elog(ERROR, "nulltestsel: unexpected nulltesttype %d", - (int) clause->nulltesttype); - return (Selectivity) 0; /* keep compiler quiet */ + default: + elog(ERROR, "nulltestsel: unexpected nulltesttype %d", + (int) clause->nulltesttype); + return (Selectivity) 0; /* keep compiler quiet */ } ReleaseSysCache(statsTuple); @@ -1318,13 +1332,13 @@ eqjoinsel(PG_FUNCTION_ARGS) if (var1 != NULL) { /* get stats for the attribute, if available */ - Oid relid1 = getrelid(var1->varno, root->rtable); + Oid relid1 = getrelid(var1->varno, root->rtable); if (relid1 != InvalidOid) { statsTuple1 = SearchSysCache(STATRELATT, ObjectIdGetDatum(relid1), - Int16GetDatum(var1->varattno), + Int16GetDatum(var1->varattno), 0, 0); if (HeapTupleIsValid(statsTuple1)) { @@ -1345,13 +1359,13 @@ eqjoinsel(PG_FUNCTION_ARGS) if (var2 != NULL) { /* get stats for the attribute, if available */ - Oid relid2 = getrelid(var2->varno, root->rtable); + Oid relid2 = getrelid(var2->varno, root->rtable); if (relid2 != InvalidOid) { statsTuple2 = SearchSysCache(STATRELATT, ObjectIdGetDatum(relid2), - Int16GetDatum(var2->varattno), + Int16GetDatum(var2->varattno), 0, 0); if (HeapTupleIsValid(statsTuple2)) { @@ -1372,17 +1386,18 @@ eqjoinsel(PG_FUNCTION_ARGS) if (have_mcvs1 && have_mcvs2) { /* - * We have most-common-value lists for both relations. Run + * We have most-common-value lists for both relations. Run * through the lists to see which MCVs actually join to each * other with the given operator. This allows us to determine * the exact join selectivity for the portion of the relations - * represented by the MCV lists. We still have to estimate for - * the remaining population, but in a skewed distribution this - * gives us a big leg up in accuracy. For motivation see the - * analysis in Y. Ioannidis and S. Christodoulakis, "On the - * propagation of errors in the size of join results", Technical - * Report 1018, Computer Science Dept., University of Wisconsin, - * Madison, March 1991 (available from ftp.cs.wisc.edu). + * represented by the MCV lists. We still have to estimate + * for the remaining population, but in a skewed distribution + * this gives us a big leg up in accuracy. For motivation see + * the analysis in Y. Ioannidis and S. Christodoulakis, "On + * the propagation of errors in the size of join results", + * Technical Report 1018, Computer Science Dept., University + * of Wisconsin, Madison, March 1991 (available from + * ftp.cs.wisc.edu). */ FmgrInfo eqproc; bool *hasmatch1; @@ -1404,17 +1419,19 @@ eqjoinsel(PG_FUNCTION_ARGS) memset(hasmatch1, 0, nvalues1 * sizeof(bool)); hasmatch2 = (bool *) palloc(nvalues2 * sizeof(bool)); memset(hasmatch2, 0, nvalues2 * sizeof(bool)); + /* - * Note we assume that each MCV will match at most one member of - * the other MCV list. If the operator isn't really equality, - * there could be multiple matches --- but we don't look for them, - * both for speed and because the math wouldn't add up... + * Note we assume that each MCV will match at most one member + * of the other MCV list. If the operator isn't really + * equality, there could be multiple matches --- but we don't + * look for them, both for speed and because the math wouldn't + * add up... */ matchprodfreq = 0.0; nmatches = 0; for (i = 0; i < nvalues1; i++) { - int j; + int j; for (j = 0; j < nvalues2; j++) { @@ -1450,19 +1467,21 @@ eqjoinsel(PG_FUNCTION_ARGS) } pfree(hasmatch1); pfree(hasmatch2); + /* * Compute total frequency of non-null values that are not in * the MCV lists. */ otherfreq1 = 1.0 - stats1->stanullfrac - matchfreq1 - unmatchfreq1; otherfreq2 = 1.0 - stats2->stanullfrac - matchfreq2 - unmatchfreq2; + /* - * We can estimate the total selectivity from the point of view - * of relation 1 as: the known selectivity for matched MCVs, plus - * unmatched MCVs that are assumed to match against random members - * of relation 2's non-MCV population, plus non-MCV values that - * are assumed to match against random members of relation 2's - * unmatched MCVs plus non-MCV values. + * We can estimate the total selectivity from the point of + * view of relation 1 as: the known selectivity for matched + * MCVs, plus unmatched MCVs that are assumed to match against + * random members of relation 2's non-MCV population, plus + * non-MCV values that are assumed to match against random + * members of relation 2's unmatched MCVs plus non-MCV values. */ totalsel1 = matchprodfreq; if (nd2 > nvalues2) @@ -1477,33 +1496,36 @@ eqjoinsel(PG_FUNCTION_ARGS) if (nd1 > nmatches) totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) / (nd1 - nmatches); + /* - * Use the smaller of the two estimates. This can be justified - * in essentially the same terms as given below for the no-stats - * case: to a first approximation, we are estimating from the - * point of view of the relation with smaller nd. + * Use the smaller of the two estimates. This can be + * justified in essentially the same terms as given below for + * the no-stats case: to a first approximation, we are + * estimating from the point of view of the relation with + * smaller nd. */ selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2; } else { /* - * We do not have MCV lists for both sides. Estimate the - * join selectivity as MIN(1/nd1, 1/nd2). This is plausible - * if we assume that the values are about equally distributed: - * a given tuple of rel1 will join to either 0 or N2/nd2 rows - * of rel2, so total join rows are at most N1*N2/nd2 giving - * a join selectivity of not more than 1/nd2. By the same logic + * We do not have MCV lists for both sides. Estimate the join + * selectivity as MIN(1/nd1, 1/nd2). This is plausible if we + * assume that the values are about equally distributed: a + * given tuple of rel1 will join to either 0 or N2/nd2 rows of + * rel2, so total join rows are at most N1*N2/nd2 giving a + * join selectivity of not more than 1/nd2. By the same logic * it is not more than 1/nd1, so MIN(1/nd1, 1/nd2) 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. + * 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 other - * side, we end up with the same answer anyway. + * 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 + * other side, we end up with the same answer anyway. */ if (nd1 > nd2) selec = 1.0 / nd1; @@ -1545,9 +1567,9 @@ neqjoinsel(PG_FUNCTION_ARGS) if (eqop) { result = DatumGetFloat8(DirectFunctionCall3(eqjoinsel, - PointerGetDatum(root), - ObjectIdGetDatum(eqop), - PointerGetDatum(args))); + PointerGetDatum(root), + ObjectIdGetDatum(eqop), + PointerGetDatum(args))); } else @@ -1702,9 +1724,9 @@ convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue, { switch (valuetypid) { - /* - * Built-in numeric types - */ + /* + * Built-in numeric types + */ case BOOLOID: case INT2OID: case INT4OID: @@ -1719,9 +1741,9 @@ convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue, *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid); return true; - /* - * Built-in string types - */ + /* + * Built-in string types + */ case CHAROID: case BPCHAROID: case VARCHAROID: @@ -1741,9 +1763,9 @@ convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue, return true; } - /* - * Built-in bytea type - */ + /* + * Built-in bytea type + */ case BYTEAOID: { convert_bytea_to_scalar(value, scaledvalue, @@ -1752,9 +1774,9 @@ convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue, return true; } - /* - * Built-in time types - */ + /* + * Built-in time types + */ case TIMESTAMPOID: case TIMESTAMPTZOID: case ABSTIMEOID: @@ -1769,9 +1791,9 @@ convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue, *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid); return true; - /* - * Built-in network types - */ + /* + * Built-in network types + */ case INETOID: case CIDROID: case MACADDROID: @@ -1975,7 +1997,6 @@ convert_string_datum(Datum value, Oid typid) char *xfrmstr; size_t xfrmsize; size_t xfrmlen; - #endif switch (typid) @@ -2016,7 +2037,7 @@ convert_string_datum(Datum value, Oid typid) #ifdef USE_LOCALE /* Guess that transformed string is not much bigger than original */ - xfrmsize = strlen(val) + 32;/* arbitrary pad value here... */ + xfrmsize = strlen(val) + 32; /* arbitrary pad value here... */ xfrmstr = (char *) palloc(xfrmsize); xfrmlen = strxfrm(xfrmstr, val, xfrmsize); if (xfrmlen >= xfrmsize) @@ -2060,8 +2081,8 @@ convert_bytea_to_scalar(Datum value, i, minlen; unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)), - *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)), - *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound)); + *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)), + *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound)); /* * Assume bytea data is uniformly distributed across all byte values. @@ -2101,8 +2122,8 @@ convert_one_bytea_to_scalar(unsigned char *value, int valuelen, return 0.0; /* empty string has scalar value 0 */ /* - * Since base is 256, need not consider more than about 10 - * chars (even this many seems like overkill) + * Since base is 256, need not consider more than about 10 chars (even + * this many seems like overkill) */ if (valuelen > 10) valuelen = 10; @@ -2214,12 +2235,13 @@ get_att_numdistinct(Query *root, Var *var, Form_pg_statistic stats) ntuples = rel->tuples; if (ntuples <= 0.0) - return DEFAULT_NUM_DISTINCT; /* no data available; return a default */ + return DEFAULT_NUM_DISTINCT; /* no data available; return a + * default */ /* - * Look to see if there is a unique index on the attribute. - * If so, we assume it's distinct, ignoring pg_statistic info - * which could be out of date. + * Look to see if there is a unique index on the attribute. If so, we + * assume it's distinct, ignoring pg_statistic info which could be out + * of date. */ if (has_unique_index(rel, var->varattno)) return ntuples; @@ -2232,12 +2254,12 @@ get_att_numdistinct(Query *root, Var *var, Form_pg_statistic stats) if (stats->stadistinct > 0.0) return stats->stadistinct; if (stats->stadistinct < 0.0) - return - stats->stadistinct * ntuples; + return -stats->stadistinct * ntuples; } /* - * ANALYZE does not compute stats for system attributes, - * but some of them can reasonably be assumed unique anyway. + * ANALYZE does not compute stats for system attributes, but some of + * them can reasonably be assumed unique anyway. */ switch (var->varattno) { @@ -2249,7 +2271,8 @@ get_att_numdistinct(Query *root, Var *var, Form_pg_statistic stats) } /* - * Estimate ndistinct = ntuples if the table is small, else use default. + * Estimate ndistinct = ntuples if the table is small, else use + * default. */ if (ntuples < DEFAULT_NUM_DISTINCT) return ntuples; @@ -2260,7 +2283,7 @@ get_att_numdistinct(Query *root, Var *var, Form_pg_statistic stats) /* * get_restriction_var * Examine the args of a restriction clause to see if it's of the - * form (var op something) or (something op var). If so, extract + * form (var op something) or (something op var). If so, extract * and return the var and the other argument. * * Inputs: @@ -2492,7 +2515,6 @@ regex_fixed_prefix(char *patt, bool case_insensitive, /* note start at pos 1 to skip leading ^ */ for (pos = 1; patt[pos]; pos++) { - /* * Check for characters that indicate multiple possible matches * here. XXX I suspect isalpha() is not an adequately @@ -2609,8 +2631,8 @@ prefix_selectivity(Query *root, Var *var, char *prefix) /* Assume scalargtsel is appropriate for all supported types */ prefixsel = DatumGetFloat8(DirectFunctionCall4(scalargtsel, PointerGetDatum(root), - ObjectIdGetDatum(cmpopr), - PointerGetDatum(cmpargs), + ObjectIdGetDatum(cmpopr), + PointerGetDatum(cmpargs), Int32GetDatum(0))); /*------- @@ -2632,8 +2654,8 @@ prefix_selectivity(Query *root, Var *var, char *prefix) /* Assume scalarltsel is appropriate for all supported types */ topsel = DatumGetFloat8(DirectFunctionCall4(scalarltsel, PointerGetDatum(root), - ObjectIdGetDatum(cmpopr), - PointerGetDatum(cmpargs), + ObjectIdGetDatum(cmpopr), + PointerGetDatum(cmpargs), Int32GetDatum(0))); /* @@ -2655,7 +2677,6 @@ prefix_selectivity(Query *root, Var *var, char *prefix) { if (prefixsel < -0.01) { - /* * No data available --- use a default estimate that is * small, but not real small. @@ -2664,7 +2685,6 @@ prefix_selectivity(Query *root, Var *var, char *prefix) } else { - /* * It's just roundoff error; use a small positive value */ @@ -2738,7 +2758,7 @@ regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive) if (patt[pos] == '(') { if (paren_depth == 0) - paren_pos = pos;/* remember start of parenthesized item */ + paren_pos = pos; /* remember start of parenthesized item */ paren_depth++; } else if (patt[pos] == ')' && paren_depth > 0) @@ -2751,7 +2771,6 @@ regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive) } else if (patt[pos] == '|' && paren_depth == 0) { - /* * If unquoted | is present at paren level 0 in pattern, we * have multiple alternatives; sum their probabilities. @@ -3091,30 +3110,31 @@ genericcostestimate(Query *root, RelOptInfo *rel, List *selectivityQuals = indexQuals; /* - * If the index is partial, AND the index predicate with the explicitly - * given indexquals to produce a more accurate idea of the index - * restriction. This may produce redundant clauses, which we hope that - * cnfify and clauselist_selectivity will deal with intelligently. + * If the index is partial, AND the index predicate with the + * explicitly given indexquals to produce a more accurate idea of the + * index restriction. This may produce redundant clauses, which we + * hope that cnfify and clauselist_selectivity will deal with + * intelligently. * - * Note that index->indpred and indexQuals are both in implicit-AND - * form to start with, which we have to make explicit to hand to + * Note that index->indpred and indexQuals are both in implicit-AND form + * to start with, which we have to make explicit to hand to * canonicalize_qual, and then we get back implicit-AND form again. */ if (index->indpred != NIL) { - Expr *andedQuals; + Expr *andedQuals; andedQuals = make_ands_explicit(nconc(listCopy(index->indpred), indexQuals)); selectivityQuals = canonicalize_qual(andedQuals, true); } - /* Estimate the fraction of main-table tuples that will be visited */ - *indexSelectivity = clauselist_selectivity(root, selectivityQuals, - lfirsti(rel->relids)); + /* Estimate the fraction of main-table tuples that will be visited */ + *indexSelectivity = clauselist_selectivity(root, selectivityQuals, + lfirsti(rel->relids)); /* - * Estimate the number of tuples that will be visited. We do it in + * Estimate the number of tuples that will be visited. We do it in * this rather peculiar-looking way in order to get the right answer * for partial indexes. We can bound the number of tuples by the * index size, in any case. @@ -3124,14 +3144,14 @@ genericcostestimate(Query *root, RelOptInfo *rel, if (numIndexTuples > index->tuples) numIndexTuples = index->tuples; - /* + /* * Always estimate at least one tuple is touched, even when * indexSelectivity estimate is tiny. */ if (numIndexTuples < 1.0) numIndexTuples = 1.0; - /* + /* * Estimate the number of index pages that will be retrieved. * * For all currently-supported index types, the first page of the index @@ -3185,11 +3205,11 @@ btcostestimate(PG_FUNCTION_ARGS) /* * If it's a functional index, leave the default zero-correlation - * estimate in place. If not, and if we can get an estimate for - * the first variable's 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.) + * estimate in place. If not, and if we can get an estimate for the + * first variable's 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.) */ if (index->indproc == InvalidOid) { @@ -3204,10 +3224,10 @@ btcostestimate(PG_FUNCTION_ARGS) 0, 0); if (HeapTupleIsValid(tuple)) { - Oid typid; - int32 typmod; - float4 *numbers; - int nnumbers; + Oid typid; + int32 typmod; + float4 *numbers; + int nnumbers; get_atttypetypmod(relid, index->indexkeys[0], &typid, &typmod); @@ -3216,13 +3236,13 @@ btcostestimate(PG_FUNCTION_ARGS) index->ordering[0], NULL, NULL, &numbers, &nnumbers)) { - double varCorrelation; - int nKeys; + double varCorrelation; + int nKeys; Assert(nnumbers == 1); varCorrelation = numbers[0]; for (nKeys = 1; index->indexkeys[nKeys] != 0; nKeys++) - /*skip*/; + /* skip */ ; *indexCorrelation = varCorrelation / nKeys; diff --git a/src/backend/utils/adt/tid.c b/src/backend/utils/adt/tid.c index 4385b003de..623d3178e0 100644 --- a/src/backend/utils/adt/tid.c +++ b/src/backend/utils/adt/tid.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/adt/tid.c,v 1.27 2001/09/17 00:29:10 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/tid.c,v 1.28 2001/10/25 05:49:45 momjian Exp $ * * NOTES * input routine largely stolen from boxin(). @@ -116,7 +116,6 @@ tidne(PG_FUNCTION_ARGS) BlockIdGetBlockNumber(&(arg2->ip_blkid)) || arg1->ip_posid != arg2->ip_posid); } - #endif /* @@ -125,7 +124,7 @@ tidne(PG_FUNCTION_ARGS) * Maybe these implementations should be moved to another place */ -static ItemPointerData Current_last_tid = { {0, 0}, 0}; +static ItemPointerData Current_last_tid = {{0, 0}, 0}; void setLastTid(const ItemPointer tid) @@ -142,11 +141,11 @@ currtid_byreloid(PG_FUNCTION_ARGS) Relation rel; result = (ItemPointer) palloc(sizeof(ItemPointerData)); - if (!reloid) - { - *result = Current_last_tid; - PG_RETURN_ITEMPOINTER(result); - } + if (!reloid) + { + *result = Current_last_tid; + PG_RETURN_ITEMPOINTER(result); + } ItemPointerCopy(tid, result); if ((rel = heap_open(reloid, AccessShareLock)) != NULL) { diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c index f39e85b235..7bb5bcab88 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.58 2001/10/20 01:02:18 thomas Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/timestamp.c,v 1.59 2001/10/25 05:49:45 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -47,6 +47,7 @@ Datum timestamp_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif @@ -146,7 +147,7 @@ timestamp_scale(PG_FUNCTION_ARGS) static void AdjustTimestampForTypmod(Timestamp *time, int32 typmod) { - if (! TIMESTAMP_NOT_FINITE(*time) && + if (!TIMESTAMP_NOT_FINITE(*time) && (typmod >= 0) && (typmod <= 13)) { static double TimestampScale = 1; @@ -158,7 +159,7 @@ AdjustTimestampForTypmod(Timestamp *time, int32 typmod) TimestampTypmod = typmod; } - *time = (rint(((double) *time) * TimestampScale)/TimestampScale); + *time = (rint(((double) *time) * TimestampScale) / TimestampScale); } } @@ -170,11 +171,12 @@ Datum timestamptz_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif int32 typmod = PG_GETARG_INT32(2); - TimestampTz result; + TimestampTz result; double fsec; struct tm tt, *tm = &tt; @@ -229,7 +231,7 @@ timestamptz_in(PG_FUNCTION_ARGS) Datum timestamptz_out(PG_FUNCTION_ARGS) { - TimestampTz dt = PG_GETARG_TIMESTAMP(0); + TimestampTz dt = PG_GETARG_TIMESTAMP(0); char *result; int tz; struct tm tt, @@ -256,9 +258,9 @@ timestamptz_out(PG_FUNCTION_ARGS) Datum timestamptz_scale(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); int32 typmod = PG_GETARG_INT32(1); - TimestampTz result; + TimestampTz result; result = timestamp; @@ -278,6 +280,7 @@ Datum interval_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif @@ -374,8 +377,8 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod) { if (typmod != -1) { - int range = ((typmod >> 16) & 0x7FFF); - int precision = (typmod & 0xFFFF); + int range = ((typmod >> 16) & 0x7FFF); + int precision = (typmod & 0xFFFF); if (range == 0x7FFF) { @@ -392,69 +395,65 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod) interval->time = 0; } /* YEAR TO MONTH */ - else if (range == (MASK(YEAR) | MASK(MONTH))) - { + else if (range == (MASK(YEAR) | MASK(MONTH))) interval->time = 0; - } else if (range == MASK(DAY)) { interval->month = 0; - interval->time = (((int)(interval->time / 86400)) * 86400); + interval->time = (((int) (interval->time / 86400)) * 86400); } else if (range == MASK(HOUR)) { - double day; + double day; interval->month = 0; TMODULO(interval->time, day, 86400.0); - interval->time = (((int)(interval->time / 3600)) * 3600.0); + interval->time = (((int) (interval->time / 3600)) * 3600.0); } else if (range == MASK(MINUTE)) { - double hour; + double hour; interval->month = 0; TMODULO(interval->time, hour, 3600.0); - interval->time = (((int)(interval->time / 60)) * 60); + interval->time = (((int) (interval->time / 60)) * 60); } else if (range == MASK(SECOND)) { - double hour; + double hour; interval->month = 0; TMODULO(interval->time, hour, 60.0); -// interval->time = (int)(interval->time); +/* interval->time = (int)(interval->time); */ } /* DAY TO HOUR */ else if (range == (MASK(DAY) | MASK(HOUR))) { interval->month = 0; - interval->time = (((int)(interval->time / 3600)) * 3600); + interval->time = (((int) (interval->time / 3600)) * 3600); } /* DAY TO MINUTE */ else if (range == (MASK(DAY) | MASK(HOUR) | MASK(MINUTE))) { interval->month = 0; - interval->time = (((int)(interval->time / 60)) * 60); + interval->time = (((int) (interval->time / 60)) * 60); } /* DAY TO SECOND */ else if (range == (MASK(DAY) | MASK(HOUR) | MASK(MINUTE) | MASK(SECOND))) - { interval->month = 0; - } /* HOUR TO MINUTE */ else if (range == (MASK(HOUR) | MASK(MINUTE))) { - double day; + double day; interval->month = 0; TMODULO(interval->time, day, 86400.0); - interval->time = (((int)(interval->time / 60)) * 60); + interval->time = (((int) (interval->time / 60)) * 60); } /* HOUR TO SECOND */ else if (range == (MASK(HOUR) | MASK(MINUTE) | MASK(SECOND))) { - double day; + double day; interval->month = 0; TMODULO(interval->time, day, 86400.0); @@ -462,20 +461,18 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod) /* MINUTE TO SECOND */ else if (range == (MASK(MINUTE) | MASK(SECOND))) { - double hour; + double hour; interval->month = 0; TMODULO(interval->time, hour, 3600.0); } else - { elog(ERROR, "AdjustIntervalForTypmod(): internal coding error"); - } if (precision != 0xFFFF) { static double IntervalScale = 1; - static int IntervalTypmod = 0; + static int IntervalTypmod = 0; if (precision != IntervalTypmod) { @@ -483,15 +480,15 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod) IntervalScale = pow(10.0, IntervalTypmod); } - /* Hmm. For the time field, we can get to a large value - * since we store everything related to an absolute interval - * (e.g. years worth of days) in this one field. So we have + /* + * Hmm. For the time field, we can get to a large value since + * we store everything related to an absolute interval (e.g. + * years worth of days) in this one field. So we have * precision problems doing rint() on this field if the field - * is too large. This resulted in an annoying "...0001" appended - * to the printed result on my Linux box. - * I hate doing an expensive math operation like log10() - * to avoid this, but what else can we do?? - * - thomas 2001-10-19 + * is too large. This resulted in an annoying "...0001" + * appended to the printed result on my Linux box. I hate + * doing an expensive math operation like log10() to avoid + * this, but what else can we do?? - thomas 2001-10-19 */ if ((log10(interval->time) + IntervalTypmod) <= 13) interval->time = (rint(interval->time * IntervalScale) / IntervalScale); @@ -521,7 +518,7 @@ EncodeSpecialTimestamp(Timestamp dt, char *str) Datum now(PG_FUNCTION_ARGS) { - TimestampTz result; + TimestampTz result; AbsoluteTime sec; int usec; @@ -571,14 +568,14 @@ timestamp2tm(Timestamp dt, int *tzp, struct tm * tm, double *fsec, char **tzn) #if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE) struct tm *tx; - #endif date0 = date2j(2000, 1, 1); - /* If HasCTZSet is true then we have a brute force time zone specified. - * Go ahead and rotate to the local time zone since we will later bypass - * any calls which adjust the tm fields. + /* + * If HasCTZSet is true then we have a brute force time zone + * specified. Go ahead and rotate to the local time zone since we will + * later bypass any calls which adjust the tm fields. */ if (HasCTZSet && (tzp != NULL)) dt -= CTimeZone; @@ -607,9 +604,9 @@ timestamp2tm(Timestamp dt, int *tzp, struct tm * tm, double *fsec, char **tzn) if (tzp != NULL) { - /* We have a brute force time zone per SQL99? - * Then use it without change - * since we have already rotated to the time zone. + /* + * We have a brute force time zone per SQL99? Then use it without + * change since we have already rotated to the time zone. */ if (HasCTZSet) { @@ -623,8 +620,9 @@ timestamp2tm(Timestamp dt, int *tzp, struct tm * tm, double *fsec, char **tzn) *tzn = NULL; } - /* Does this fall within the capabilities of the localtime() interface? - * Then use this to rotate to the local time zone. + /* + * Does this fall within the capabilities of the localtime() + * interface? Then use this to rotate to the local time zone. */ else if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday)) { @@ -1031,7 +1029,6 @@ interval_hash(PG_FUNCTION_ARGS) Datum overlaps_timestamp(PG_FUNCTION_ARGS) { - /* * The arguments are Timestamps, but we leave them as generic Datums * to avoid unnecessary conversions between value and reference forms @@ -1101,7 +1098,6 @@ overlaps_timestamp(PG_FUNCTION_ARGS) */ if (TIMESTAMP_GT(ts1, ts2)) { - /* * This case is ts1 < te2 OR te1 < te2, which may look redundant * but in the presence of nulls it's not quite completely so. @@ -1137,7 +1133,6 @@ overlaps_timestamp(PG_FUNCTION_ARGS) } else { - /* * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a * rather silly way of saying "true if both are nonnull, else @@ -1225,9 +1220,7 @@ timestamp_pl_span(PG_FUNCTION_ARGS) Timestamp result; if (TIMESTAMP_NOT_FINITE(timestamp)) - { result = timestamp; - } else { if (span->month != 0) @@ -1309,16 +1302,14 @@ timestamp_mi_span(PG_FUNCTION_ARGS) Datum timestamptz_pl_span(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); Interval *span = PG_GETARG_INTERVAL_P(1); - TimestampTz result; + TimestampTz result; int tz; char *tzn; if (TIMESTAMP_NOT_FINITE(timestamp)) - { result = timestamp; - } else { if (span->month != 0) @@ -1349,7 +1340,7 @@ timestamptz_pl_span(PG_FUNCTION_ARGS) if (tm2timestamp(tm, fsec, &tz, ×tamp) != 0) elog(ERROR, "Unable to add TIMESTAMP and INTERVAL" - "\n\ttimestamptz_pl_span() internal error encoding timestamp"); + "\n\ttimestamptz_pl_span() internal error encoding timestamp"); } else { @@ -1373,7 +1364,7 @@ timestamptz_pl_span(PG_FUNCTION_ARGS) Datum timestamptz_mi_span(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); Interval *span = PG_GETARG_INTERVAL_P(1); Interval tspan; @@ -1584,8 +1575,8 @@ interval_accum(PG_FUNCTION_ARGS) memcpy(&N, DatumGetIntervalP(transdatums[1]), sizeof(Interval)); newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl, - IntervalPGetDatum(&sumX), - IntervalPGetDatum(newval))); + IntervalPGetDatum(&sumX), + IntervalPGetDatum(newval))); N.time += 1; transdatums[0] = IntervalPGetDatum(newsum); @@ -1750,8 +1741,8 @@ timestamp_age(PG_FUNCTION_ARGS) Datum timestamptz_age(PG_FUNCTION_ARGS) { - TimestampTz dt1 = PG_GETARG_TIMESTAMP(0); - TimestampTz dt2 = PG_GETARG_TIMESTAMP(1); + TimestampTz dt1 = PG_GETARG_TIMESTAMP(0); + TimestampTz dt2 = PG_GETARG_TIMESTAMP(1); Interval *result; double fsec, fsec1, @@ -1978,7 +1969,7 @@ interval_text(PG_FUNCTION_ARGS) int len; str = DatumGetCString(DirectFunctionCall1(interval_out, - IntervalPGetDatum(interval))); + IntervalPGetDatum(interval))); len = (strlen(str) + VARHDRSZ); @@ -2043,7 +2034,7 @@ timestamp_trunc(PG_FUNCTION_ARGS) if (VARSIZE(units) - VARHDRSZ > MAXDATELEN) elog(ERROR, "TIMESTAMP units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -2113,8 +2104,8 @@ Datum timestamptz_trunc(PG_FUNCTION_ARGS) { text *units = PG_GETARG_TEXT_P(0); - TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); - TimestampTz result; + TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); + TimestampTz result; int tz; int type, val; @@ -2130,7 +2121,7 @@ timestamptz_trunc(PG_FUNCTION_ARGS) if (VARSIZE(units) - VARHDRSZ > MAXDATELEN) elog(ERROR, "TIMESTAMP WITH TIME ZONE units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -2218,7 +2209,7 @@ interval_trunc(PG_FUNCTION_ARGS) if (VARSIZE(units) - VARHDRSZ > MAXDATELEN) elog(ERROR, "INTERVAL units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -2281,7 +2272,7 @@ interval_trunc(PG_FUNCTION_ARGS) { elog(ERROR, "INTERVAL units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); *result = *interval; } @@ -2390,7 +2381,7 @@ timestamp_part(PG_FUNCTION_ARGS) if (VARSIZE(units) - VARHDRSZ > MAXDATELEN) elog(ERROR, "TIMESTAMP units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); up = VARDATA(units); lp = lowunits; for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++) @@ -2517,7 +2508,7 @@ Datum timestamptz_part(PG_FUNCTION_ARGS) { text *units = PG_GETARG_TEXT_P(0); - TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); float8 result; int tz; int type, @@ -2756,7 +2747,7 @@ interval_part(PG_FUNCTION_ARGS) default: elog(ERROR, "INTERVAL units '%s' not supported", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); result = 0; } @@ -2781,7 +2772,7 @@ interval_part(PG_FUNCTION_ARGS) { elog(ERROR, "INTERVAL units '%s' not recognized", DatumGetCString(DirectFunctionCall1(textout, - PointerGetDatum(units)))); + PointerGetDatum(units)))); result = 0; } @@ -2797,7 +2788,7 @@ timestamp_zone(PG_FUNCTION_ARGS) { text *zone = PG_GETARG_TEXT_P(0); Timestamp timestamp = PG_GETARG_TIMESTAMP(1); - TimestampTz result; + TimestampTz result; int tz; int type, val; @@ -2845,7 +2836,7 @@ timestamp_izone(PG_FUNCTION_ARGS) { Interval *zone = PG_GETARG_INTERVAL_P(0); Timestamp timestamp = PG_GETARG_TIMESTAMP(1); - TimestampTz result; + TimestampTz result; int tz; if (TIMESTAMP_NOT_FINITE(timestamp)) @@ -2869,16 +2860,14 @@ Datum timestamp_timestamptz(PG_FUNCTION_ARGS) { Timestamp timestamp = PG_GETARG_TIMESTAMP(0); - TimestampTz result; + TimestampTz result; struct tm tt, *tm = &tt; double fsec; int tz; if (TIMESTAMP_NOT_FINITE(timestamp)) - { result = timestamp; - } else { if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0) @@ -2899,7 +2888,7 @@ timestamp_timestamptz(PG_FUNCTION_ARGS) Datum timestamptz_timestamp(PG_FUNCTION_ARGS) { - TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(0); Timestamp result; struct tm tt, *tm = &tt; @@ -2908,9 +2897,7 @@ timestamptz_timestamp(PG_FUNCTION_ARGS) int tz; if (TIMESTAMP_NOT_FINITE(timestamp)) - { result = timestamp; - } else { if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0) @@ -2930,9 +2917,9 @@ Datum timestamptz_zone(PG_FUNCTION_ARGS) { text *zone = PG_GETARG_TEXT_P(0); - TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); text *result; - TimestampTz dt; + TimestampTz dt; int tz; int type, val; @@ -3007,9 +2994,9 @@ Datum timestamptz_izone(PG_FUNCTION_ARGS) { Interval *zone = PG_GETARG_INTERVAL_P(0); - TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); + TimestampTz timestamp = PG_GETARG_TIMESTAMP(1); text *result; - TimestampTz dt; + TimestampTz dt; int tz; char *tzn = ""; double fsec; @@ -3033,7 +3020,7 @@ timestamptz_izone(PG_FUNCTION_ARGS) if (timestamp2tm(dt, NULL, tm, &fsec, NULL) != 0) elog(ERROR, "Unable to decode TIMESTAMP WITH TIME ZONE" - "\n\ttimestamptz_izone() internal coding error"); + "\n\ttimestamptz_izone() internal coding error"); EncodeDateTime(tm, fsec, &tz, &tzn, USE_ISO_DATES, buf); len = (strlen(buf) + VARHDRSZ); diff --git a/src/backend/utils/adt/varbit.c b/src/backend/utils/adt/varbit.c index a294bfc9ff..b1304fbae7 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.19 2001/10/06 23:21:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/varbit.c,v 1.20 2001/10/25 05:49:46 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -51,7 +51,6 @@ bit_in(PG_FUNCTION_ARGS) #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); - #endif int32 atttypmod = PG_GETARG_INT32(2); VarBit *result; /* The resulting bit string */ @@ -77,7 +76,6 @@ bit_in(PG_FUNCTION_ARGS) } else { - /* * Otherwise it's binary. This allows things like cast('1001' as * bit) to work transparently. @@ -233,8 +231,8 @@ _bit(PG_FUNCTION_ARGS) FunctionCallInfoData locfcinfo; /* - * Since bit() is a built-in function, we should only need to look - * it up once per run. + * Since bit() is a built-in function, we should only need to look it + * up once per run. */ static FmgrInfo bit_finfo; @@ -264,7 +262,6 @@ varbit_in(PG_FUNCTION_ARGS) #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); - #endif int32 atttypmod = PG_GETARG_INT32(2); VarBit *result; /* The resulting bit string */ @@ -733,7 +730,6 @@ bitsubstr(PG_FUNCTION_ARGS) } else { - /* * OK, we've got a true substring starting at position s1-1 and * ending at position e1-1 diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c index c963709ac8..a09bed915f 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.84 2001/10/06 23:21:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/varchar.c,v 1.85 2001/10/25 05:49:46 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -65,23 +65,26 @@ Datum bpcharin(PG_FUNCTION_ARGS) { char *s = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif int32 atttypmod = PG_GETARG_INT32(2); BpChar *result; char *r; - size_t len, maxlen; + size_t len, + maxlen; int i; + #ifdef MULTIBYTE - int charlen; /* number of charcters in the input string */ - char *ermsg; + int charlen; /* number of charcters in the input string */ + char *ermsg; #endif len = strlen(s); #ifdef MULTIBYTE if ((ermsg = pg_verifymbstr(s, len))) - elog(ERROR,"%s",ermsg); + elog(ERROR, "%s", ermsg); charlen = pg_mbstrlen(s); #endif @@ -104,19 +107,21 @@ bpcharin(PG_FUNCTION_ARGS) { /* Verify that extra characters are spaces, and clip them off */ #ifdef MULTIBYTE - size_t mbmaxlen = pg_mbcharcliplen(s, len, maxlen); + size_t mbmaxlen = pg_mbcharcliplen(s, len, maxlen); + /* - * at this point, len is the actual BYTE length of the - * input string, maxlen is the max number of - * CHARACTERS allowed for this bpchar type. + * at this point, len is the actual BYTE length of the input + * string, maxlen is the max number of CHARACTERS allowed for this + * bpchar type. */ if (strspn(s + mbmaxlen, " ") == len - mbmaxlen) len = mbmaxlen; else elog(ERROR, "value too long for type character(%d)", maxlen); + /* - * XXX: at this point, maxlen is the necessary byte - * length, not the number of CHARACTERS! + * XXX: at this point, maxlen is the necessary byte length, not + * the number of CHARACTERS! */ maxlen = len; #else @@ -130,8 +135,8 @@ bpcharin(PG_FUNCTION_ARGS) else { /* - * XXX: at this point, maxlen is the necessary byte - * length, not the number of CHARACTERS! + * XXX: at this point, maxlen is the necessary byte length, not + * the number of CHARACTERS! */ maxlen = len + (maxlen - charlen); } @@ -194,9 +199,10 @@ bpchar(PG_FUNCTION_ARGS) char *r; char *s; int i; + #ifdef MULTIBYTE - int charlen; /* number of charcters in the input string - + VARHDRSZ*/ + int charlen; /* number of charcters in the input string + * + VARHDRSZ */ #endif len = VARSIZE(source); @@ -217,7 +223,7 @@ bpchar(PG_FUNCTION_ARGS) size_t maxmblen; maxmblen = pg_mbcharcliplen(VARDATA(source), len - VARHDRSZ, - maxlen - VARHDRSZ) + VARHDRSZ; + maxlen - VARHDRSZ) + VARHDRSZ; for (i = maxmblen - VARHDRSZ; i < len - VARHDRSZ; i++) if (*(VARDATA(source) + i) != ' ') @@ -225,6 +231,7 @@ bpchar(PG_FUNCTION_ARGS) maxlen - VARHDRSZ); len = maxmblen; + /* * XXX: at this point, maxlen is the necessary byte * length+VARHDRSZ, not the number of CHARACTERS! @@ -403,20 +410,23 @@ Datum varcharin(PG_FUNCTION_ARGS) { char *s = PG_GETARG_CSTRING(0); + #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif int32 atttypmod = PG_GETARG_INT32(2); VarChar *result; - size_t len, maxlen; + size_t len, + maxlen; + #ifdef MULTIBYTE - char *ermsg; + char *ermsg; #endif len = strlen(s); #ifdef MULTIBYTE if ((ermsg = pg_verifymbstr(s, len))) - elog(ERROR,"%s",ermsg); + elog(ERROR, "%s", ermsg); #endif maxlen = atttypmod - VARHDRSZ; @@ -424,7 +434,7 @@ varcharin(PG_FUNCTION_ARGS) { /* Verify that extra characters are spaces, and clip them off */ #ifdef MULTIBYTE - size_t mbmaxlen = pg_mbcharcliplen(s, len, maxlen); + size_t mbmaxlen = pg_mbcharcliplen(s, len, maxlen); if (strspn(s + mbmaxlen, " ") == len - mbmaxlen) len = mbmaxlen; @@ -499,7 +509,7 @@ varchar(PG_FUNCTION_ARGS) /* truncate multi-byte string preserving multi-byte boundary */ maxmblen = pg_mbcharcliplen(VARDATA(source), len - VARHDRSZ, - maxlen - VARHDRSZ) + VARHDRSZ; + maxlen - VARHDRSZ) + VARHDRSZ; for (i = maxmblen - VARHDRSZ; i < len - VARHDRSZ; i++) if (*(VARDATA(source) + i) != ' ') @@ -586,8 +596,8 @@ bpcharlen(PG_FUNCTION_ARGS) #ifdef MULTIBYTE PG_RETURN_INT32( - pg_mbstrlen_with_len(VARDATA(arg), VARSIZE(arg) - VARHDRSZ) - ); + pg_mbstrlen_with_len(VARDATA(arg), VARSIZE(arg) - VARHDRSZ) + ); #else PG_RETURN_INT32(VARSIZE(arg) - VARHDRSZ); #endif @@ -794,8 +804,8 @@ varcharlen(PG_FUNCTION_ARGS) #ifdef MULTIBYTE PG_RETURN_INT32( - pg_mbstrlen_with_len(VARDATA(arg), VARSIZE(arg) - VARHDRSZ) - ); + pg_mbstrlen_with_len(VARDATA(arg), VARSIZE(arg) - VARHDRSZ) + ); #else PG_RETURN_INT32(VARSIZE(arg) - VARHDRSZ); #endif diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c index 1c6de93f01..7b15cfa690 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.73 2001/09/14 17:46:40 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/adt/varlena.c,v 1.74 2001/10/25 05:49:46 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -54,21 +54,15 @@ byteain(PG_FUNCTION_ARGS) for (byte = 0, tp = inputText; *tp != '\0'; byte++) { if (tp[0] != '\\') - { tp++; - } - else if ( (tp[0] == '\\') && - (tp[1] >= '0' && tp[1] <= '3') && - (tp[2] >= '0' && tp[2] <= '7') && - (tp[3] >= '0' && tp[3] <= '7') ) - { + else if ((tp[0] == '\\') && + (tp[1] >= '0' && tp[1] <= '3') && + (tp[2] >= '0' && tp[2] <= '7') && + (tp[3] >= '0' && tp[3] <= '7')) tp += 4; - } - else if ( (tp[0] == '\\') && - (tp[1] == '\\') ) - { + else if ((tp[0] == '\\') && + (tp[1] == '\\')) tp += 2; - } else { /* @@ -87,13 +81,11 @@ byteain(PG_FUNCTION_ARGS) while (*tp != '\0') { if (tp[0] != '\\') - { *rp++ = *tp++; - } - else if ( (tp[0] == '\\') && - (tp[1] >= '0' && tp[1] <= '3') && - (tp[2] >= '0' && tp[2] <= '7') && - (tp[3] >= '0' && tp[3] <= '7') ) + else if ((tp[0] == '\\') && + (tp[1] >= '0' && tp[1] <= '3') && + (tp[2] >= '0' && tp[2] <= '7') && + (tp[3] >= '0' && tp[3] <= '7')) { byte = VAL(tp[1]); byte <<= 3; @@ -102,8 +94,8 @@ byteain(PG_FUNCTION_ARGS) *rp++ = byte + VAL(tp[3]); tp += 4; } - else if ( (tp[0] == '\\') && - (tp[1] == '\\') ) + else if ((tp[0] == '\\') && + (tp[1] == '\\')) { *rp++ = '\\'; tp += 2; @@ -111,8 +103,8 @@ byteain(PG_FUNCTION_ARGS) else { /* - * We should never get here. The first pass should - * not allow it. + * We should never get here. The first pass should not allow + * it. */ elog(ERROR, "Bad input string for type bytea"); } @@ -188,15 +180,16 @@ textin(PG_FUNCTION_ARGS) char *inputText = PG_GETARG_CSTRING(0); text *result; int len; + #ifdef MULTIBYTE - char *ermsg; + char *ermsg; #endif len = strlen(inputText) + VARHDRSZ; #ifdef MULTIBYTE if ((ermsg = pg_verifymbstr(inputText, len - VARHDRSZ))) - elog(ERROR,"%s",ermsg); + elog(ERROR, "%s", ermsg); #endif result = (text *) palloc(len); @@ -368,7 +361,6 @@ text_substr(PG_FUNCTION_ARGS) #ifdef MULTIBYTE int i; char *p; - #endif len = VARSIZE(string) - VARHDRSZ; @@ -442,7 +434,6 @@ textpos(PG_FUNCTION_ARGS) #ifdef MULTIBYTE pg_wchar *ps1, *ps2; - #endif if (VARSIZE(t2) <= VARHDRSZ) @@ -819,8 +810,8 @@ byteapos(PG_FUNCTION_ARGS) p; int len1, len2; - char *p1, - *p2; + char *p1, + *p2; if (VARSIZE(t2) <= VARHDRSZ) PG_RETURN_INT32(1); /* result for empty pattern */ @@ -1072,8 +1063,8 @@ name_text(PG_FUNCTION_ARGS) Datum byteaeq(PG_FUNCTION_ARGS) { - bytea *arg1 = PG_GETARG_BYTEA_P(0); - bytea *arg2 = PG_GETARG_BYTEA_P(1); + bytea *arg1 = PG_GETARG_BYTEA_P(0); + bytea *arg2 = PG_GETARG_BYTEA_P(1); int len1, len2; bool result; @@ -1096,8 +1087,8 @@ byteaeq(PG_FUNCTION_ARGS) Datum byteane(PG_FUNCTION_ARGS) { - bytea *arg1 = PG_GETARG_BYTEA_P(0); - bytea *arg2 = PG_GETARG_BYTEA_P(1); + bytea *arg1 = PG_GETARG_BYTEA_P(0); + bytea *arg2 = PG_GETARG_BYTEA_P(1); int len1, len2; bool result; @@ -1120,8 +1111,8 @@ byteane(PG_FUNCTION_ARGS) Datum bytealt(PG_FUNCTION_ARGS) { - bytea *arg1 = PG_GETARG_BYTEA_P(0); - bytea *arg2 = PG_GETARG_BYTEA_P(1); + bytea *arg1 = PG_GETARG_BYTEA_P(0); + bytea *arg2 = PG_GETARG_BYTEA_P(1); int len1, len2; int cmp; @@ -1140,8 +1131,8 @@ bytealt(PG_FUNCTION_ARGS) Datum byteale(PG_FUNCTION_ARGS) { - bytea *arg1 = PG_GETARG_BYTEA_P(0); - bytea *arg2 = PG_GETARG_BYTEA_P(1); + bytea *arg1 = PG_GETARG_BYTEA_P(0); + bytea *arg2 = PG_GETARG_BYTEA_P(1); int len1, len2; int cmp; @@ -1160,8 +1151,8 @@ byteale(PG_FUNCTION_ARGS) Datum byteagt(PG_FUNCTION_ARGS) { - bytea *arg1 = PG_GETARG_BYTEA_P(0); - bytea *arg2 = PG_GETARG_BYTEA_P(1); + bytea *arg1 = PG_GETARG_BYTEA_P(0); + bytea *arg2 = PG_GETARG_BYTEA_P(1); int len1, len2; int cmp; @@ -1180,8 +1171,8 @@ byteagt(PG_FUNCTION_ARGS) Datum byteage(PG_FUNCTION_ARGS) { - bytea *arg1 = PG_GETARG_BYTEA_P(0); - bytea *arg2 = PG_GETARG_BYTEA_P(1); + bytea *arg1 = PG_GETARG_BYTEA_P(0); + bytea *arg2 = PG_GETARG_BYTEA_P(1); int len1, len2; int cmp; @@ -1200,8 +1191,8 @@ byteage(PG_FUNCTION_ARGS) Datum byteacmp(PG_FUNCTION_ARGS) { - bytea *arg1 = PG_GETARG_BYTEA_P(0); - bytea *arg2 = PG_GETARG_BYTEA_P(1); + bytea *arg1 = PG_GETARG_BYTEA_P(0); + bytea *arg2 = PG_GETARG_BYTEA_P(1); int len1, len2; int cmp; diff --git a/src/backend/utils/cache/catcache.c b/src/backend/utils/cache/catcache.c index 77112a694e..fe347fe5fb 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.83 2001/10/06 23:21:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/catcache.c,v 1.84 2001/10/25 05:49:46 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -30,13 +30,13 @@ #include "utils/syscache.h" -/* #define CACHEDEBUG */ /* turns DEBUG elogs on */ + /* #define CACHEDEBUG *//* turns DEBUG elogs on */ /* * Constants related to size of the catcache. * * NCCBUCKETS should be prime and must be less than 64K (because - * SharedInvalCatcacheMsg crams hash indexes into a uint16 field). In + * SharedInvalCatcacheMsg crams hash indexes into a uint16 field). In * practice it should be a lot less, anyway, to avoid chewing up too much * space on hash bucket headers. * @@ -642,13 +642,13 @@ CatalogCacheFlushRelation(Oid relId) tupRelid = ct->tuple.t_data->t_oid; else { - bool isNull; + bool isNull; tupRelid = DatumGetObjectId( - fastgetattr(&ct->tuple, - cache->cc_reloidattr, - cache->cc_tupdesc, - &isNull)); + fastgetattr(&ct->tuple, + cache->cc_reloidattr, + cache->cc_tupdesc, + &isNull)); Assert(!isNull); } @@ -707,8 +707,8 @@ InitCatCache(int id, oldcxt = MemoryContextSwitchTo(CacheMemoryContext); /* - * if first time through, initialize the cache group header, - * including global LRU list header + * if first time through, initialize the cache group header, including + * global LRU list header */ if (CacheHdr == NULL) { @@ -740,7 +740,7 @@ InitCatCache(int id, cp->cc_relname = relname; cp->cc_indname = indname; cp->cc_reloidattr = reloidattr; - cp->cc_relisshared = false; /* temporary */ + cp->cc_relisshared = false; /* temporary */ cp->cc_tupdesc = (TupleDesc) NULL; cp->cc_ntup = 0; cp->cc_size = NCCBUCKETS; @@ -749,8 +749,8 @@ InitCatCache(int id, cp->cc_key[i] = key[i]; /* - * new cache is initialized as far as we can go for now. - * print some debugging information, if appropriate. + * new cache is initialized as far as we can go for now. print some + * debugging information, if appropriate. */ InitCatCache_DEBUG1; @@ -1105,9 +1105,7 @@ ReleaseCatCache(HeapTuple tuple) && ct->dead #endif ) - { CatCacheRemoveCTup(ct->my_cache, ct); - } } /* @@ -1141,7 +1139,7 @@ ReleaseCatCache(HeapTuple tuple) void PrepareToInvalidateCacheTuple(Relation relation, HeapTuple tuple, - void (*function) (int, Index, ItemPointer, Oid)) + void (*function) (int, Index, ItemPointer, Oid)) { CatCache *ccp; diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c index cd01bc9adc..9ebf5f3bf2 100644 --- a/src/backend/utils/cache/inval.c +++ b/src/backend/utils/cache/inval.c @@ -22,14 +22,14 @@ * second lives till end of transaction. Finally, we need a third list of * all tuples outdated in the current transaction; if we commit, we send * those invalidation events to all other backends (via the SI message queue) - * so that they can flush obsolete entries from their caches. This list + * so that they can flush obsolete entries from their caches. This list * definitely can't be processed until after we commit, otherwise the other * backends won't see our updated tuples as good. * * We do not need to register EVERY tuple operation in this way, just those - * on tuples in relations that have associated catcaches. We do, however, + * on tuples in relations that have associated catcaches. We do, however, * have to register every operation on every tuple that *could* be in a - * catcache, whether or not it currently is in our cache. Also, if the + * catcache, whether or not it currently is in our cache. Also, if the * tuple is in a relation that has multiple catcaches, we need to register * an invalidation message for each such catcache. catcache.c's * PrepareToInvalidateCacheTuple() routine provides the knowledge of which @@ -56,7 +56,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/cache/inval.c,v 1.45 2001/06/19 19:42:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/inval.c,v 1.46 2001/10/25 05:49:46 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -74,15 +74,15 @@ /* * To minimize palloc traffic, we keep pending requests in successively- * larger chunks (a slightly more sophisticated version of an expansible - * array). All request types can be stored as SharedInvalidationMessage + * array). All request types can be stored as SharedInvalidationMessage * records. */ typedef struct InvalidationChunk { - struct InvalidationChunk *next; /* list link */ + struct InvalidationChunk *next; /* list link */ int nitems; /* # items currently stored in chunk */ int maxitems; /* size of allocated array in this chunk */ - SharedInvalidationMessage msgs[1]; /* VARIABLE LENGTH ARRAY */ + SharedInvalidationMessage msgs[1]; /* VARIABLE LENGTH ARRAY */ } InvalidationChunk; /* VARIABLE LENGTH STRUCTURE */ typedef struct InvalidationListHeader @@ -148,7 +148,7 @@ AddInvalidationMessage(InvalidationChunk **listHdr, chunk = (InvalidationChunk *) MemoryContextAlloc(TopTransactionContext, sizeof(InvalidationChunk) + - (FIRSTCHUNKSIZE-1) * sizeof(SharedInvalidationMessage)); + (FIRSTCHUNKSIZE - 1) *sizeof(SharedInvalidationMessage)); chunk->nitems = 0; chunk->maxitems = FIRSTCHUNKSIZE; chunk->next = *listHdr; @@ -157,12 +157,12 @@ AddInvalidationMessage(InvalidationChunk **listHdr, else if (chunk->nitems >= chunk->maxitems) { /* Need another chunk; double size of last chunk */ - int chunksize = 2 * chunk->maxitems; + int chunksize = 2 * chunk->maxitems; chunk = (InvalidationChunk *) MemoryContextAlloc(TopTransactionContext, sizeof(InvalidationChunk) + - (chunksize-1) * sizeof(SharedInvalidationMessage)); + (chunksize - 1) *sizeof(SharedInvalidationMessage)); chunk->nitems = 0; chunk->maxitems = chunksize; chunk->next = *listHdr; @@ -279,7 +279,10 @@ DiscardInvalidationMessages(InvalidationListHeader *hdr, bool physicalFree) } else { - /* Assume the storage will go away at xact end, just reset pointers */ + /* + * Assume the storage will go away at xact end, just reset + * pointers + */ hdr->cclist = NULL; hdr->rclist = NULL; } @@ -421,7 +424,7 @@ InvalidateSystemCaches(void) static void PrepareForTupleInvalidation(Relation relation, HeapTuple tuple, void (*CacheIdRegisterFunc) (int, Index, - ItemPointer, Oid), + ItemPointer, Oid), void (*RelationIdRegisterFunc) (Oid, Oid)) { Oid tupleRelId; @@ -460,12 +463,12 @@ PrepareForTupleInvalidation(Relation relation, HeapTuple tuple, * Yes. We need to register a relcache invalidation event for the * relation identified by relationId. * - * KLUGE ALERT: we always send the relcache event with MyDatabaseId, - * even if the rel in question is shared. This essentially means that - * only backends in this same database will react to the relcache flush - * request. This is in fact appropriate, since only those backends could - * see our pg_class or pg_attribute change anyway. It looks a bit ugly - * though. + * KLUGE ALERT: we always send the relcache event with MyDatabaseId, even + * if the rel in question is shared. This essentially means that only + * backends in this same database will react to the relcache flush + * request. This is in fact appropriate, since only those backends + * could see our pg_class or pg_attribute change anyway. It looks a + * bit ugly though. */ (*RelationIdRegisterFunc) (MyDatabaseId, relationId); } @@ -498,7 +501,7 @@ AcceptInvalidationMessages(void) * If isCommit, we must send out the messages in our GlobalInvalidMsgs list * to the shared invalidation message queue. Note that these will be read * not only by other backends, but also by our own backend at the next - * transaction start (via AcceptInvalidationMessages). Therefore, it's okay + * transaction start (via AcceptInvalidationMessages). Therefore, it's okay * to discard any pending LocalInvalidMsgs, since these will be redundant * with the global list. * @@ -538,7 +541,7 @@ AtEOXactInvalidationMessages(bool isCommit) * in a transaction. * * Here, we send no messages to the shared queue, since we don't know yet if - * we will commit. But we do need to locally process the LocalInvalidMsgs + * we will commit. But we do need to locally process the LocalInvalidMsgs * list, so as to flush our caches of any tuples we have outdated in the * current command. * @@ -563,9 +566,10 @@ CommandEndInvalidationMessages(bool isCommit) ProcessInvalidationMessages(&RollbackMsgs, LocalExecuteInvalidationMessage); } + /* - * LocalInvalidMsgs list is not interesting anymore, so flush it - * (for real). Do *not* clear GlobalInvalidMsgs or RollbackMsgs. + * LocalInvalidMsgs list is not interesting anymore, so flush it (for + * real). Do *not* clear GlobalInvalidMsgs or RollbackMsgs. */ DiscardInvalidationMessages(&LocalInvalidMsgs, true); } diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c index b788383ba5..b359651b9b 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.58 2001/09/06 02:07:42 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/lsyscache.c,v 1.59 2001/10/25 05:49:46 momjian Exp $ * * NOTES * Eventually, the index information should go through here, too. @@ -589,7 +589,6 @@ get_relnatts(Oid relid) else return InvalidAttrNumber; } - #endif /* @@ -723,7 +722,6 @@ get_typalign(Oid typid) else return 'i'; } - #endif char @@ -778,8 +776,8 @@ get_typdefault(Oid typid, Datum *defaultValue) typelem = type->typelem; /* - * typdefault is potentially null, so don't try to access it as a struct - * field. Must do it the hard way with SysCacheGetAttr. + * typdefault is potentially null, so don't try to access it as a + * struct field. Must do it the hard way with SysCacheGetAttr. */ textDefaultVal = SysCacheGetAttr(TYPEOID, typeTuple, @@ -828,6 +826,7 @@ get_typavgwidth(Oid typid, int32 typmod) */ if (typlen > 0) return typlen; + /* * type_maximum_size knows the encoding of typmod for some datatypes; * don't duplicate that knowledge here. @@ -836,16 +835,17 @@ get_typavgwidth(Oid typid, int32 typmod) if (maxwidth > 0) { /* - * For BPCHAR, the max width is also the only width. Otherwise - * we need to guess about the typical data width given the max. - * A sliding scale for percentage of max width seems reasonable. + * For BPCHAR, the max width is also the only width. Otherwise we + * need to guess about the typical data width given the max. A + * sliding scale for percentage of max width seems reasonable. */ if (typid == BPCHAROID) return maxwidth; if (maxwidth <= 32) return maxwidth; /* assume full width */ if (maxwidth < 1000) - return 32 + (maxwidth - 32) / 2; /* assume 50% */ + return 32 + (maxwidth - 32) / 2; /* assume 50% */ + /* * Beyond 1000, assume we're looking at something like * "varchar(10000)" where the limit isn't actually reached often, @@ -853,6 +853,7 @@ get_typavgwidth(Oid typid, int32 typmod) */ return 32 + (1000 - 32) / 2; } + /* * Ooops, we have no idea ... wild guess time. */ @@ -887,7 +888,6 @@ get_typtype(Oid typid) else return '\0'; } - #endif /* ---------- STATISTICS CACHE ---------- */ @@ -909,7 +909,7 @@ get_attavgwidth(Oid relid, AttrNumber attnum) 0, 0); if (HeapTupleIsValid(tp)) { - int32 stawidth = ((Form_pg_statistic) GETSTRUCT(tp))->stawidth; + int32 stawidth = ((Form_pg_statistic) GETSTRUCT(tp))->stawidth; ReleaseSysCache(tp); if (stawidth > 0) @@ -977,14 +977,17 @@ get_attstatsslot(HeapTuple statstuple, if (isnull) elog(ERROR, "get_attstatsslot: stavalues is null"); statarray = DatumGetArrayTypeP(val); + /* - * Do initial examination of the array. This produces a list - * of text Datums --- ie, pointers into the text array value. + * Do initial examination of the array. This produces a list of + * text Datums --- ie, pointers into the text array value. */ deconstruct_array(statarray, false, -1, 'i', values, nvalues); narrayelem = *nvalues; + /* - * We now need to replace each text Datum by its internal equivalent. + * We now need to replace each text Datum by its internal + * equivalent. * * Get the type input proc and typelem for the column datatype. */ @@ -997,9 +1000,10 @@ get_attstatsslot(HeapTuple statstuple, fmgr_info(((Form_pg_type) GETSTRUCT(typeTuple))->typinput, &inputproc); typelem = ((Form_pg_type) GETSTRUCT(typeTuple))->typelem; ReleaseSysCache(typeTuple); + /* - * Do the conversions. The palloc'd array of Datums is reused - * in place. + * Do the conversions. The palloc'd array of Datums is reused in + * place. */ for (j = 0; j < narrayelem; j++) { @@ -1013,6 +1017,7 @@ get_attstatsslot(HeapTuple statstuple, Int32GetDatum(atttypmod)); pfree(strval); } + /* * Free statarray if it's a detoasted copy. */ @@ -1028,10 +1033,11 @@ get_attstatsslot(HeapTuple statstuple, if (isnull) elog(ERROR, "get_attstatsslot: stanumbers is null"); statarray = DatumGetArrayTypeP(val); + /* - * We expect the array to be a 1-D float4 array; verify that. - * We don't need to use deconstruct_array() since the array - * data is just going to look like a C array of float4 values. + * We expect the array to be a 1-D float4 array; verify that. We + * don't need to use deconstruct_array() since the array data is + * just going to look like a C array of float4 values. */ narrayelem = ARR_DIMS(statarray)[0]; if (ARR_NDIM(statarray) != 1 || narrayelem <= 0 || @@ -1040,6 +1046,7 @@ get_attstatsslot(HeapTuple statstuple, *numbers = (float4 *) palloc(narrayelem * sizeof(float4)); memcpy(*numbers, ARR_DATA_PTR(statarray), narrayelem * sizeof(float4)); *nnumbers = narrayelem; + /* * Free statarray if it's a detoasted copy. */ @@ -1057,9 +1064,9 @@ free_attstatsslot(Oid atttype, { if (values) { - if (! get_typbyval(atttype)) + if (!get_typbyval(atttype)) { - int i; + int i; for (i = 0; i < nvalues; i++) pfree(DatumGetPointer(values[i])); diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index c56d606076..1073841f9d 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.146 2001/10/06 23:21:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/relcache.c,v 1.147 2001/10/25 05:49:46 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -226,7 +226,6 @@ static void RelationClearRelation(Relation relation, bool rebuildIt); #ifdef ENABLE_REINDEX_NAILED_RELATIONS static void RelationReloadClassinfo(Relation relation); - #endif /* ENABLE_REINDEX_NAILED_RELATIONS */ static void RelationFlushRelation(Relation relation); static Relation RelationNameCacheGetRelation(const char *relationName); @@ -273,7 +272,6 @@ static List *insert_ordered_oid(List *list, Oid datum); static HeapTuple ScanPgRelation(RelationBuildDescInfo buildinfo) { - /* * If this is bootstrap time (initdb), then we can't use the system * catalog indices, because they may not exist yet. Otherwise, we @@ -333,7 +331,6 @@ scan_pg_rel_seq(RelationBuildDescInfo buildinfo) return_tuple = pg_class_tuple; else { - /* * a satanic bug used to live here: pg_class_tuple used to be * returned here without having the corresponding buffer pinned. @@ -382,7 +379,7 @@ scan_pg_rel_ind(RelationBuildDescInfo buildinfo) default: elog(ERROR, "ScanPgRelation: bad buildinfo"); - return_tuple = NULL;/* keep compiler quiet */ + return_tuple = NULL; /* keep compiler quiet */ } heap_close(pg_class_desc, AccessShareLock); @@ -461,7 +458,6 @@ static void RelationBuildTupleDesc(RelationBuildDescInfo buildinfo, Relation relation) { - /* * If this is bootstrap time (initdb), then we can't use the system * catalog indices, because they may not exist yet. Otherwise, we @@ -649,7 +645,6 @@ build_tupdesc_ind(RelationBuildDescInfo buildinfo, { #ifdef _DROP_COLUMN_HACK__ bool columnDropped = false; - #endif /* _DROP_COLUMN_HACK__ */ atttup = AttributeRelidNumIndexScan(attrel, @@ -767,7 +762,7 @@ RelationBuildRuleLock(Relation relation) */ rulescxt = AllocSetContextCreate(CacheMemoryContext, RelationGetRelationName(relation), - 0, /* minsize */ + 0, /* minsize */ 1024, /* initsize */ 1024); /* maxsize */ relation->rd_rulescxt = rulescxt; @@ -1106,16 +1101,16 @@ RelationInitIndexAccessInfo(Relation relation) amsupport = relation->rd_am->amsupport; /* - * Make the private context to hold index access info. The reason - * we need a context, and not just a couple of pallocs, is so that - * we won't leak any subsidiary info attached to fmgr lookup records. + * Make the private context to hold index access info. The reason we + * need a context, and not just a couple of pallocs, is so that we + * won't leak any subsidiary info attached to fmgr lookup records. * * Context parameters are set on the assumption that it'll probably not * contain much data. */ indexcxt = AllocSetContextCreate(CacheMemoryContext, RelationGetRelationName(relation), - 0, /* minsize */ + 0, /* minsize */ 512, /* initsize */ 1024); /* maxsize */ relation->rd_indexcxt = indexcxt; @@ -1128,7 +1123,7 @@ RelationInitIndexAccessInfo(Relation relation) if (amsupport > 0) { - int nsupport = natts * amsupport; + int nsupport = natts * amsupport; support = (RegProcedure *) MemoryContextAlloc(indexcxt, nsupport * sizeof(RegProcedure)); @@ -1214,8 +1209,9 @@ formrdesc(char *relationName, strcpy(RelationGetPhysicalRelationName(relation), relationName); /* - * It's important to distinguish between shared and non-shared relations, - * even at bootstrap time, to make sure we know where they are stored. + * It's important to distinguish between shared and non-shared + * relations, even at bootstrap time, to make sure we know where they + * are stored. */ relation->rd_rel->relisshared = IsSharedSystemRelationName(relationName); @@ -1267,8 +1263,8 @@ formrdesc(char *relationName, if (!IsBootstrapProcessingMode()) { /* - * This list is incomplete, but it only has to work for the - * set of rels that formrdesc is used for ... + * This list is incomplete, but it only has to work for the set of + * rels that formrdesc is used for ... */ if (strcmp(relationName, RelationRelationName) == 0 || strcmp(relationName, AttributeRelationName) == 0 || @@ -1560,7 +1556,6 @@ RelationReloadClassinfo(Relation relation) return; } - #endif /* ENABLE_REINDEX_NAILED_RELATIONS */ /* @@ -1649,7 +1644,6 @@ RelationClearRelation(Relation relation, bool rebuildIt) } else { - /* * When rebuilding an open relcache entry, must preserve ref count * and myxactonly flag. Also attempt to preserve the tupledesc, @@ -1663,7 +1657,7 @@ RelationClearRelation(Relation relation, bool rebuildIt) RuleLock *old_rules = relation->rd_rules; MemoryContext old_rulescxt = relation->rd_rulescxt; TriggerDesc *old_trigdesc = relation->trigdesc; - BlockNumber old_nblocks = relation->rd_nblocks; + BlockNumber old_nblocks = relation->rd_nblocks; RelationBuildDescInfo buildinfo; buildinfo.infotype = INFO_RELID; @@ -1730,7 +1724,6 @@ RelationFlushRelation(Relation relation) if (relation->rd_myxactonly) { - /* * Local rels should always be rebuilt, not flushed; the relcache * entry must live until RelationPurgeLocalRelation(). @@ -1739,7 +1732,6 @@ RelationFlushRelation(Relation relation) } else { - /* * Nonlocal rels can be dropped from the relcache if not open. */ @@ -1837,7 +1829,6 @@ RelationFlushIndexes(Relation *r, relation->rd_rel->relam == accessMethodId)) RelationFlushRelation(relation); } - #endif @@ -1982,8 +1973,8 @@ RelationBuildLocalRelation(const char *relname, rel->rd_isnailed = true; /* - * create a new tuple descriptor from the one passed in - * (we do this to copy it into the cache context) + * create a new tuple descriptor from the one passed in (we do this to + * copy it into the cache context) */ rel->rd_att = CreateTupleDescCopyConstr(tupDesc); @@ -2003,9 +1994,10 @@ RelationBuildLocalRelation(const char *relname, rel->rd_rel->relchecks = tupDesc->constr->num_check; /* - * Insert relation OID and database/tablespace ID into the right places. - * XXX currently we assume physical tblspace/relnode are same as logical - * dbid/reloid. Probably should pass an extra pair of parameters. + * Insert relation OID and database/tablespace ID into the right + * places. XXX currently we assume physical tblspace/relnode are same + * as logical dbid/reloid. Probably should pass an extra pair of + * parameters. */ rel->rd_rel->relisshared = (dbid == InvalidOid); @@ -2149,7 +2141,6 @@ RelationCacheInitialize(void) void RelationCacheInitializePhase2(void) { - /* * Get the real pg_class tuple for each nailed-in-cache relcache entry * that was made by RelationCacheInitialize(), and replace the phony @@ -2159,7 +2150,6 @@ RelationCacheInitializePhase2(void) */ if (!IsBootstrapProcessingMode()) { - /* * Initialize critical system index relation descriptors, first. * They are to make building relation descriptors fast. @@ -2764,9 +2754,9 @@ init_irels(void) */ indexcxt = AllocSetContextCreate(CacheMemoryContext, RelationGetRelationName(ird), - 0, /* minsize */ - 512, /* initsize */ - 1024); /* maxsize */ + 0, /* minsize */ + 512, /* initsize */ + 1024); /* maxsize */ ird->rd_indexcxt = indexcxt; /* next, read the index strategy map */ @@ -2848,7 +2838,6 @@ write_irels(void) fd = PathNameOpenFile(tempfilename, O_WRONLY | O_CREAT | O_TRUNC | PG_BINARY, 0600); if (fd < 0) { - /* * We used to consider this a fatal error, but we might as well * continue with backend startup ... diff --git a/src/backend/utils/cache/syscache.c b/src/backend/utils/cache/syscache.c index 6020597f2a..e629bf48e4 100644 --- a/src/backend/utils/cache/syscache.c +++ b/src/backend/utils/cache/syscache.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/cache/syscache.c,v 1.65 2001/08/21 16:36:05 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/cache/syscache.c,v 1.66 2001/10/25 05:49:46 momjian Exp $ * * NOTES * These routines allow the parser/planner/executor to perform @@ -133,7 +133,7 @@ static struct cachedesc cacheinfo[] = { 0, 0 }}, - {AccessMethodProcedureRelationName, /* AMPROCNUM */ + {AccessMethodProcedureRelationName, /* AMPROCNUM */ AccessMethodProcedureIndex, 0, 2, @@ -365,7 +365,8 @@ static struct cachedesc cacheinfo[] = { }} }; -static CatCache *SysCache[lengthof(cacheinfo)]; +static CatCache *SysCache[ + lengthof(cacheinfo)]; static int SysCacheSize = lengthof(cacheinfo); static bool CacheInitialized = false; @@ -564,7 +565,6 @@ SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull) { - /* * We just need to get the TupleDesc out of the cache entry, and then * we can apply heap_getattr(). We expect that the cache control data diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c index 4e1ab2684c..d9554b9575 100644 --- a/src/backend/utils/error/elog.c +++ b/src/backend/utils/error/elog.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/error/elog.c,v 1.89 2001/10/18 23:07:29 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/error/elog.c,v 1.90 2001/10/25 05:49:46 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -135,16 +135,15 @@ elog(int lev, const char *fmt,...) errorstr = useful_strerror(errno); /* - * Convert initialization errors into fatal errors. This is - * probably redundant, because Warn_restart_ready won't be set - * anyway. + * Convert initialization errors into fatal errors. This is probably + * redundant, because Warn_restart_ready won't be set anyway. */ if (lev == ERROR && IsInitProcessingMode()) lev = FATAL; /* - * If we are inside a critical section, all errors become - * REALLYFATAL errors. See miscadmin.h. + * If we are inside a critical section, all errors become REALLYFATAL + * errors. See miscadmin.h. */ if (lev == ERROR || lev == FATAL) { @@ -161,6 +160,7 @@ elog(int lev, const char *fmt,...) timestamp_size += PID_SIZE; fmt = gettext(fmt); + /* * Set up the expanded format, consisting of the prefix string plus * input format, with any %m replaced by strerror() string (since @@ -189,11 +189,11 @@ elog(int lev, const char *fmt,...) lev = ERROR; prefix = elog_message_prefix(lev); } + /* - * gettext doesn't allocate memory, except in the very - * first call (which this isn't), so it's safe to - * translate here. Worst case we get the untranslated - * string back. + * gettext doesn't allocate memory, except in the very first + * call (which this isn't), so it's safe to translate here. + * Worst case we get the untranslated string back. */ /* translator: This must fit in fmt_fixedbuf. */ fmt = gettext("elog: out of memory"); @@ -329,7 +329,7 @@ elog(int lev, const char *fmt,...) write_syslog(syslog_level, msg_buf + timestamp_size); } -#endif /* ENABLE_SYSLOG */ +#endif /* ENABLE_SYSLOG */ /* syslog doesn't want a trailing newline, but other destinations do */ strcat(msg_buf, "\n"); @@ -665,8 +665,7 @@ write_syslog(int level, const char *line) syslog(level, "[%lu] %s", seq, line); } } - -#endif /* ENABLE_SYSLOG */ +#endif /* ENABLE_SYSLOG */ static void @@ -682,22 +681,22 @@ send_message_to_frontend(int type, const char *msg) pq_endmessage(&buf); /* - * This flush is normally not necessary, since postgres.c will - * flush out waiting data when control returns to the main loop. - * But it seems best to leave it here, so that the client has some - * clue what happened if the backend dies before getting back to - * the main loop ... error/notice messages should not be a - * performance-critical path anyway, so an extra flush won't hurt - * much ... + * This flush is normally not necessary, since postgres.c will flush + * out waiting data when control returns to the main loop. But it + * seems best to leave it here, so that the client has some clue what + * happened if the backend dies before getting back to the main loop + * ... error/notice messages should not be a performance-critical path + * anyway, so an extra flush won't hurt much ... */ pq_flush(); } -static const char *useful_strerror(int errnum) +static const char * +useful_strerror(int errnum) { /* this buffer is only used if errno has a bogus value */ - static char errorstr_buf[48]; + static char errorstr_buf[48]; char *str; if (errnum == ERANGE) @@ -712,7 +711,10 @@ static const char *useful_strerror(int errnum) */ if (str == NULL || *str == '\0') { - /* translator: This string will be truncated at 47 characters expanded. */ + /* + * translator: This string will be truncated at 47 characters + * expanded. + */ snprintf(errorstr_buf, 48, gettext("operating system error %d"), errnum); str = errorstr_buf; } @@ -725,7 +727,7 @@ static const char *useful_strerror(int errnum) static const char * elog_message_prefix(int lev) { - const char * prefix = NULL; + const char *prefix = NULL; switch (lev) { diff --git a/src/backend/utils/error/exc.c b/src/backend/utils/error/exc.c index ee64ecb5f0..d5400e72a0 100644 --- a/src/backend/utils/error/exc.c +++ b/src/backend/utils/error/exc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/error/Attic/exc.c,v 1.37 2001/03/22 03:59:58 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/error/Attic/exc.c,v 1.38 2001/10/25 05:49:46 momjian Exp $ * * NOTE * XXX this code needs improvement--check for state violations and @@ -138,16 +138,15 @@ ExcPrint(Exception *excP, } #ifdef NOT_USED -ExcProc * +ExcProc * ExcGetUnCaught(void) { return ExcUnCaughtP; } - #endif #ifdef NOT_USED -ExcProc * +ExcProc * ExcSetUnCaught(ExcProc *newP) { ExcProc *oldP = ExcUnCaughtP; @@ -156,7 +155,6 @@ ExcSetUnCaught(ExcProc *newP) return oldP; } - #endif static void diff --git a/src/backend/utils/fmgr/dfmgr.c b/src/backend/utils/fmgr/dfmgr.c index 3085187d8a..1a1633cc57 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.53 2001/10/06 23:21:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/dfmgr.c,v 1.54 2001/10/25 05:49:48 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -46,12 +46,12 @@ static DynamicFileList *file_tail = (DynamicFileList *) NULL; #define SAME_INODE(A,B) ((A).st_ino == (B).inode && (A).st_dev == (B).device) -char * Dynamic_library_path; +char *Dynamic_library_path; static bool file_exists(const char *name); -static char * find_in_dynamic_libpath(const char * basename); -static char * expand_dynamic_library_name(const char *name); -static char * substitute_libpath_macro(const char * name); +static char *find_in_dynamic_libpath(const char *basename); +static char *expand_dynamic_library_name(const char *name); +static char *substitute_libpath_macro(const char *name); /* * Load the specified dynamic-link library file, and look for a function @@ -237,7 +237,7 @@ file_exists(const char *name) if (stat(name, &st) == 0) return S_ISDIR(st.st_mode) ? false : true; else if (!(errno == ENOENT || errno == ENOTDIR || errno == EACCES)) - elog(ERROR, "stat failed on %s: %s", name, strerror(errno)); + elog(ERROR, "stat failed on %s: %s", name, strerror(errno)); return false; } @@ -258,7 +258,7 @@ file_exists(const char *name) * If name contains a slash, check if the file exists, if so return * the name. Else (no slash) try to expand using search path (see * find_in_dynamic_libpath below); if that works, return the fully - * expanded file name. If the previous failed, append DLSUFFIX and + * expanded file name. If the previous failed, append DLSUFFIX and * try again. If all fails, return NULL. * * A non-NULL result will always be freshly palloc'd. @@ -266,9 +266,9 @@ file_exists(const char *name) static char * expand_dynamic_library_name(const char *name) { - bool have_slash; - char * new; - char * full; + bool have_slash; + char *new; + char *full; AssertArg(name); @@ -288,7 +288,7 @@ expand_dynamic_library_name(const char *name) pfree(full); } - new = palloc(strlen(name)+ strlen(DLSUFFIX) + 1); + new = palloc(strlen(name) + strlen(DLSUFFIX) + 1); strcpy(new, name); strcat(new, DLSUFFIX); @@ -307,7 +307,7 @@ expand_dynamic_library_name(const char *name) return full; pfree(full); } - + return NULL; } @@ -317,10 +317,10 @@ expand_dynamic_library_name(const char *name) * Result is always freshly palloc'd. */ static char * -substitute_libpath_macro(const char * name) +substitute_libpath_macro(const char *name) { - size_t macroname_len; - char * replacement = NULL; + size_t macroname_len; + char *replacement = NULL; AssertArg(name != NULL); @@ -329,7 +329,7 @@ substitute_libpath_macro(const char * name) macroname_len = strcspn(name + 1, "/") + 1; - if (strncmp(name, "$libdir", macroname_len)==0) + if (strncmp(name, "$libdir", macroname_len) == 0) replacement = PKGLIBDIR; else elog(ERROR, "invalid macro name in dynamic library path"); @@ -338,7 +338,7 @@ substitute_libpath_macro(const char * name) return pstrdup(replacement); else { - char * new; + char *new; new = palloc(strlen(replacement) + (strlen(name) - macroname_len) + 1); @@ -357,10 +357,10 @@ substitute_libpath_macro(const char * name) * return NULL. */ static char * -find_in_dynamic_libpath(const char * basename) +find_in_dynamic_libpath(const char *basename) { const char *p; - size_t baselen; + size_t baselen; AssertArg(basename != NULL); AssertArg(strchr(basename, '/') == NULL); @@ -374,10 +374,10 @@ find_in_dynamic_libpath(const char * basename) for (;;) { - size_t len; - char * piece; - char * mangled; - char *full; + size_t len; + char *piece; + char *mangled; + char *full; len = strcspn(p, ":"); diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c index 5faa8a155c..18d2000d21 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.55 2001/10/06 23:21:44 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/fmgr.c,v 1.56 2001/10/25 05:49:50 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -43,7 +43,6 @@ typedef int32 ((*func_ptr) ()); #else typedef char *((*func_ptr) ()); - #endif /* @@ -143,9 +142,9 @@ fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt) char *prosrc; /* - * fn_oid *must* be filled in last. Some code assumes that if fn_oid is - * valid, the whole struct is valid. Some FmgrInfo struct's do survive - * elogs. + * fn_oid *must* be filled in last. Some code assumes that if fn_oid + * is valid, the whole struct is valid. Some FmgrInfo struct's do + * survive elogs. */ finfo->fn_oid = InvalidOid; finfo->fn_extra = NULL; @@ -154,7 +153,8 @@ fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt) if ((fbp = fmgr_isbuiltin(functionId)) != NULL) { /* - * Fast path for builtin functions: don't bother consulting pg_proc + * Fast path for builtin functions: don't bother consulting + * pg_proc */ finfo->fn_nargs = fbp->nargs; finfo->fn_strict = fbp->strict; @@ -189,6 +189,7 @@ fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt) switch (procedureStruct->prolang) { case INTERNALlanguageId: + /* * For an ordinary builtin function, we should never get here * because the isbuiltin() search above will have succeeded. @@ -405,7 +406,7 @@ fetch_finfo_record(void *filehandle, char *funcname) * Copy an FmgrInfo struct * * This is inherently somewhat bogus since we can't reliably duplicate - * language-dependent subsidiary info. We cheat by zeroing fn_extra, + * language-dependent subsidiary info. We cheat by zeroing fn_extra, * instead, meaning that subsidiary info will have to be recomputed. */ void @@ -624,7 +625,6 @@ fmgr_oldstyle(PG_FUNCTION_ARGS) static Datum fmgr_untrusted(PG_FUNCTION_ARGS) { - /* * Currently these are unsupported. Someday we might do something * like forking a subprocess to execute 'em. @@ -1457,19 +1457,20 @@ Int64GetDatum(int64 X) *retval = X; return PointerGetDatum(retval); -#else /* INT64_IS_BUSTED */ +#else /* INT64_IS_BUSTED */ + /* - * On a machine with no 64-bit-int C datatype, sizeof(int64) will not be - * 8, but we want Int64GetDatum to return an 8-byte object anyway, with - * zeroes in the unused bits. This is needed so that, for example, - * hash join of int8 will behave properly. + * On a machine with no 64-bit-int C datatype, sizeof(int64) will not + * be 8, but we want Int64GetDatum to return an 8-byte object anyway, + * with zeroes in the unused bits. This is needed so that, for + * example, hash join of int8 will behave properly. */ int64 *retval = (int64 *) palloc(Max(sizeof(int64), 8)); MemSet(retval, 0, Max(sizeof(int64), 8)); *retval = X; return PointerGetDatum(retval); -#endif /* INT64_IS_BUSTED */ +#endif /* INT64_IS_BUSTED */ } Datum diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c index 2d5a79551e..d12cbcbbf1 100644 --- a/src/backend/utils/hash/dynahash.c +++ b/src/backend/utils/hash/dynahash.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/hash/dynahash.c,v 1.38 2001/10/05 17:28:13 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/hash/dynahash.c,v 1.39 2001/10/25 05:49:50 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -66,11 +66,11 @@ static void *DynaHashAlloc(Size size); static uint32 call_hash(HTAB *hashp, void *k); static HASHSEGMENT seg_alloc(HTAB *hashp); -static bool element_alloc(HTAB *hashp); -static bool dir_realloc(HTAB *hashp); -static bool expand_table(HTAB *hashp); -static bool hdefault(HTAB *hashp); -static bool init_htab(HTAB *hashp, long nelem); +static bool element_alloc(HTAB *hashp); +static bool dir_realloc(HTAB *hashp); +static bool expand_table(HTAB *hashp); +static bool hdefault(HTAB *hashp); +static bool init_htab(HTAB *hashp, long nelem); static void hash_corrupted(HTAB *hashp); @@ -104,7 +104,7 @@ HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) { HTAB *hashp; - HASHHDR *hctl; + HASHHDR *hctl; /* First time through, create a memory context for hash tables */ if (!DynaHashCxt) @@ -132,7 +132,7 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) if (flags & HASH_FUNCTION) hashp->hash = info->hash; else - hashp->hash = string_hash; /* default hash function */ + hashp->hash = string_hash; /* default hash function */ if (flags & HASH_SHARED_MEM) { @@ -212,20 +212,20 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) { /* hash table structures live in child of given context */ CurrentDynaHashCxt = AllocSetContextCreate(info->hcxt, - "DynaHashTable", - ALLOCSET_DEFAULT_MINSIZE, - ALLOCSET_DEFAULT_INITSIZE, - ALLOCSET_DEFAULT_MAXSIZE); + "DynaHashTable", + ALLOCSET_DEFAULT_MINSIZE, + ALLOCSET_DEFAULT_INITSIZE, + ALLOCSET_DEFAULT_MAXSIZE); hashp->hcxt = CurrentDynaHashCxt; } else { /* hash table structures live in child of DynaHashCxt */ CurrentDynaHashCxt = AllocSetContextCreate(DynaHashCxt, - "DynaHashTable", - ALLOCSET_DEFAULT_MINSIZE, - ALLOCSET_DEFAULT_INITSIZE, - ALLOCSET_DEFAULT_MAXSIZE); + "DynaHashTable", + ALLOCSET_DEFAULT_MINSIZE, + ALLOCSET_DEFAULT_INITSIZE, + ALLOCSET_DEFAULT_MAXSIZE); hashp->hcxt = CurrentDynaHashCxt; } } @@ -244,7 +244,7 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) static bool hdefault(HTAB *hashp) { - HASHHDR *hctl = hashp->hctl; + HASHHDR *hctl = hashp->hctl; MemSet(hctl, 0, sizeof(HASHHDR)); @@ -274,7 +274,7 @@ hdefault(HTAB *hashp) static bool init_htab(HTAB *hashp, long nelem) { - HASHHDR *hctl = hashp->hctl; + HASHHDR *hctl = hashp->hctl; HASHSEGMENT *segp; int nbuckets; int nsegs; @@ -372,7 +372,7 @@ hash_estimate_size(long num_entries, long entrysize) nDirEntries <<= 1; /* dir_alloc doubles dsize at each call */ /* fixed control info */ - size += MAXALIGN(sizeof(HASHHDR)); /* but not HTAB, per above */ + size += MAXALIGN(sizeof(HASHHDR)); /* but not HTAB, per above */ /* directory */ size += MAXALIGN(nDirEntries * sizeof(HASHSEGMENT)); /* segments */ @@ -429,15 +429,15 @@ hash_destroy(HTAB *hashp) hash_stats("destroy", hashp); /* - * Free buckets, dir etc. by destroying the hash table's - * memory context. + * Free buckets, dir etc. by destroying the hash table's memory + * context. */ MemoryContextDelete(hashp->hcxt); /* - * Free the HTAB and control structure, which are allocated - * in the parent context (DynaHashCxt or the context given - * by the caller of hash_create()). + * Free the HTAB and control structure, which are allocated in the + * parent context (DynaHashCxt or the context given by the caller + * of hash_create()). */ MEM_FREE(hashp->hctl); MEM_FREE(hashp->tabname); @@ -460,7 +460,6 @@ hash_stats(const char *where, HTAB *hashp) where, hash_accesses, hash_collisions); fprintf(stderr, "hash_stats: total expansions %ld\n", hash_expansions); - #endif } @@ -470,7 +469,7 @@ hash_stats(const char *where, HTAB *hashp) static uint32 call_hash(HTAB *hashp, void *k) { - HASHHDR *hctl = hashp->hctl; + HASHHDR *hctl = hashp->hctl; long hash_val, bucket; @@ -503,7 +502,7 @@ call_hash(HTAB *hashp, void *k) * HASH_ENTER case, but is redundant with the return value otherwise. * * The HASH_FIND_SAVE/HASH_REMOVE_SAVED interface is a hack to save one - * table lookup in a find/process/remove scenario. Note that no other + * table lookup in a find/process/remove scenario. Note that no other * addition or removal in the table can safely happen in between. *---------- */ @@ -513,17 +512,17 @@ hash_search(HTAB *hashp, HASHACTION action, bool *foundPtr) { - HASHHDR *hctl = hashp->hctl; + HASHHDR *hctl = hashp->hctl; uint32 bucket; long segment_num; long segment_ndx; - HASHSEGMENT segp; - HASHBUCKET currBucket; + HASHSEGMENT segp; + HASHBUCKET currBucket; HASHBUCKET *prevBucketPtr; static struct State { - HASHBUCKET currBucket; + HASHBUCKET currBucket; HASHBUCKET *prevBucketPtr; } saveState; @@ -631,7 +630,7 @@ hash_search(HTAB *hashp, { /* no free elements. allocate another chunk of buckets */ if (!element_alloc(hashp)) - return NULL; /* out of memory */ + return NULL; /* out of memory */ currBucket = hctl->freeList; Assert(currBucket != NULL); } @@ -651,8 +650,9 @@ hash_search(HTAB *hashp, if (++hctl->nentries / (hctl->max_bucket + 1) > hctl->ffactor) { /* - * NOTE: failure to expand table is not a fatal error, it just - * means we have to run at higher fill factor than we wanted. + * NOTE: failure to expand table is not a fatal error, it + * just means we have to run at higher fill factor than we + * wanted. */ expand_table(hashp); } @@ -688,13 +688,13 @@ void * hash_seq_search(HASH_SEQ_STATUS *status) { HTAB *hashp = status->hashp; - HASHHDR *hctl = hashp->hctl; + HASHHDR *hctl = hashp->hctl; while (status->curBucket <= hctl->max_bucket) { long segment_num; long segment_ndx; - HASHSEGMENT segp; + HASHSEGMENT segp; if (status->curEntry != NULL) { @@ -703,7 +703,7 @@ hash_seq_search(HASH_SEQ_STATUS *status) curElem = status->curEntry; status->curEntry = curElem->link; - if (status->curEntry == NULL) /* end of this bucket */ + if (status->curEntry == NULL) /* end of this bucket */ ++status->curBucket; return (void *) ELEMENTKEY(curElem); } @@ -731,7 +731,7 @@ hash_seq_search(HASH_SEQ_STATUS *status) */ status->curEntry = segp[segment_ndx]; - if (status->curEntry == NULL) /* empty bucket */ + if (status->curEntry == NULL) /* empty bucket */ ++status->curBucket; } @@ -747,8 +747,8 @@ hash_seq_search(HASH_SEQ_STATUS *status) static bool expand_table(HTAB *hashp) { - HASHHDR *hctl = hashp->hctl; - HASHSEGMENT old_seg, + HASHHDR *hctl = hashp->hctl; + HASHSEGMENT old_seg, new_seg; long old_bucket, new_bucket; @@ -758,7 +758,7 @@ expand_table(HTAB *hashp) old_segndx; HASHBUCKET *oldlink, *newlink; - HASHBUCKET currElement, + HASHBUCKET currElement, nextElement; #ifdef HASH_STATISTICS @@ -879,7 +879,7 @@ dir_realloc(HTAB *hashp) static HASHSEGMENT seg_alloc(HTAB *hashp) { - HASHSEGMENT segp; + HASHSEGMENT segp; CurrentDynaHashCxt = hashp->hcxt; segp = (HASHSEGMENT) hashp->alloc(sizeof(HASHBUCKET) * hashp->hctl->ssize); @@ -898,7 +898,7 @@ seg_alloc(HTAB *hashp) static bool element_alloc(HTAB *hashp) { - HASHHDR *hctl = hashp->hctl; + HASHHDR *hctl = hashp->hctl; Size elementSize; HASHELEMENT *tmpElement; int i; @@ -930,7 +930,7 @@ hash_corrupted(HTAB *hashp) { /* * If the corruption is in a shared hashtable, we'd better force a - * systemwide restart. Otherwise, just shut down this one backend. + * systemwide restart. Otherwise, just shut down this one backend. */ if (hashp->isshared) elog(STOP, "Hash table '%s' corrupted", hashp->tabname); diff --git a/src/backend/utils/hash/hashfn.c b/src/backend/utils/hash/hashfn.c index 958deee804..4c7dd4cbb4 100644 --- a/src/backend/utils/hash/hashfn.c +++ b/src/backend/utils/hash/hashfn.c @@ -9,7 +9,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/hash/hashfn.c,v 1.14 2001/10/01 05:36:16 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/hash/hashfn.c,v 1.15 2001/10/25 05:49:51 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -57,41 +57,41 @@ tag_hash(void *key, int keysize) * Use four byte chunks in a "jump table" to go a little faster. * * Currently the maximum keysize is 16 (mar 17 1992). I have put in - * cases for up to 32. Bigger than this will resort to a for loop + * cases for up to 32. Bigger than this will resort to a for loop * (see the default case). */ switch (keysize) { case 8 * sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); /* fall through */ case 7 * sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); /* fall through */ case 6 * sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); /* fall through */ case 5 * sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); /* fall through */ case 4 * sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); /* fall through */ case 3 * sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); /* fall through */ case 2 * sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); /* fall through */ case sizeof(int): - h = (h * PRIME1) ^ (*k++); + h = (h * PRIME1) ^(*k++); break; default: @@ -102,7 +102,7 @@ tag_hash(void *key, int keysize) /* Cope with any partial-int leftover bytes */ if (keysize > 0) { - unsigned char *keybyte = (unsigned char *) k; + unsigned char *keybyte = (unsigned char *) k; do h = (h * PRIME1) ^ (*keybyte++); diff --git a/src/backend/utils/hash/pg_crc.c b/src/backend/utils/hash/pg_crc.c index 9ad712c066..86a714aa40 100644 --- a/src/backend/utils/hash/pg_crc.c +++ b/src/backend/utils/hash/pg_crc.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/hash/pg_crc.c,v 1.3 2001/03/23 18:42:12 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/hash/pg_crc.c,v 1.4 2001/10/25 05:49:51 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -413,5 +413,4 @@ const uint64 crc_table[256] = { INT64CONST(0x5DEDC41A34BBEEB2), INT64CONST(0x1F1D25F19D51D821), INT64CONST(0xD80C07CD676F8394), INT64CONST(0x9AFCE626CE85B507) }; - #endif /* INT64_IS_BUSTED */ diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index c6dafb9e2f..ec6235aba4 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/init/globals.c,v 1.61 2001/10/21 03:25:35 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/init/globals.c,v 1.62 2001/10/25 05:49:51 momjian Exp $ * * NOTES * Globals used all over the place should be declared here and not @@ -57,7 +57,8 @@ Relation reldesc; /* current relation descriptor */ char OutputFileName[MAXPGPATH]; -char pg_pathname[MAXPGPATH]; /* full path to postgres executable */ +char pg_pathname[MAXPGPATH]; /* full path to postgres + * executable */ BackendId MyBackendId; diff --git a/src/backend/utils/init/miscinit.c b/src/backend/utils/init/miscinit.c index fc8b6b3ed7..2043fd6a4a 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.80 2001/10/19 18:19:41 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.81 2001/10/25 05:49:51 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -256,7 +256,6 @@ next_token(FILE *fp, char *buf, const int bufsz) if (c != '\n') { - /* * build a token in buf of next characters up to EOF, eol, or * blank. @@ -317,8 +316,8 @@ SetCharSet() if (p && *p != '\0') { - map_file = malloc(strlen(DataDir) + strlen(p) + 2); - if (! map_file) + map_file = malloc(strlen(DataDir) + strlen(p) + 2); + if (!map_file) elog(FATAL, "out of memory"); sprintf(map_file, "%s/%s", DataDir, p); file = AllocateFile(map_file, PG_BINARY_R); @@ -381,7 +380,6 @@ convertstr(unsigned char *buff, int len, int dest) } return ch; } - #endif @@ -487,7 +485,8 @@ InitializeSessionUserIdStandalone(void) /* * Change session auth ID while running */ -void SetSessionAuthorization(const char * username) +void +SetSessionAuthorization(const char *username) { int32 userid; @@ -579,13 +578,12 @@ CreateLockFile(const char *filename, bool amPostmaster, pid_t my_pid = getpid(); /* - * We need a loop here because of race conditions. But don't loop + * We need a loop here because of race conditions. But don't loop * forever (for example, a non-writable $PGDATA directory might cause * a failure that won't go away). 100 tries seems like plenty. */ - for (ntries = 0; ; ntries++) + for (ntries = 0;; ntries++) { - /* * Try to create the lock file --- O_EXCL makes this atomic. */ diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c index f653f55640..edec4a8329 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.94 2001/10/19 17:03:08 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.95 2001/10/25 05:49:51 momjian Exp $ * * *------------------------------------------------------------------------- @@ -221,7 +221,10 @@ InitPostgres(const char *dbname, const char *username) char *fullpath, datpath[MAXPGPATH]; - /* Formerly we validated DataDir here, but now that's done earlier. */ + /* + * Formerly we validated DataDir here, but now that's done + * earlier. + */ /* * Find oid and path of the database we're about to open. Since @@ -257,7 +260,7 @@ InitPostgres(const char *dbname, const char *username) */ /* - * Set up my per-backend PROC struct in shared memory. (We need to + * Set up my per-backend PROC struct in shared memory. (We need to * know MyDatabaseId before we can do this, since it's entered into * the PROC struct.) */ @@ -284,8 +287,8 @@ InitPostgres(const char *dbname, const char *username) AmiTransactionOverride(bootstrap); /* - * Initialize the relation descriptor cache. - * The pre-allocated reldescs are created here. + * Initialize the relation descriptor cache. The pre-allocated + * reldescs are created here. */ RelationCacheInitialize(); @@ -320,9 +323,8 @@ InitPostgres(const char *dbname, const char *username) RelationCacheInitializePhase2(); /* - * Figure out our postgres user id. In standalone mode we use a - * fixed id, otherwise we figure it out from the authenticated - * user name. + * Figure out our postgres user id. In standalone mode we use a fixed + * id, otherwise we figure it out from the authenticated user name. */ if (bootstrap) InitializeSessionUserIdStandalone(); @@ -388,7 +390,6 @@ InitPostgres(const char *dbname, const char *username) static void ShutdownPostgres(void) { - /* * These operations are really just a minimal subset of * AbortTransaction(). We don't want to do any inessential cleanup, @@ -408,7 +409,7 @@ ShutdownPostgres(void) * has to happen before bufmgr shutdown, so having smgr register a * callback for it wouldn't work. */ - smgrDoPendingDeletes(false);/* delete as though aborting xact */ + smgrDoPendingDeletes(false); /* delete as though aborting xact */ } diff --git a/src/backend/utils/mb/big5.c b/src/backend/utils/mb/big5.c index 2546ee4079..7ebaafb079 100644 --- a/src/backend/utils/mb/big5.c +++ b/src/backend/utils/mb/big5.c @@ -7,7 +7,7 @@ * * 1999/1/15 Tatsuo Ishii * - * $Id: big5.c,v 1.7 2001/02/10 02:31:27 tgl Exp $ + * $Id: big5.c,v 1.8 2001/10/25 05:49:51 momjian Exp $ */ /* can be used in either frontend or backend */ @@ -19,7 +19,7 @@ typedef struct { unsigned short code, peer; -} codes_t; +} codes_t; /* map Big5 Level 1 to CNS 11643-1992 Plane 1 */ static codes_t big5Level1ToCnsPlane1[25] = { /* range */ @@ -205,7 +205,7 @@ static unsigned short b2c3[][2] = { }; static unsigned short BinarySearchRange - (codes_t * array, int high, unsigned short code) + (codes_t *array, int high, unsigned short code) { int low, mid, diff --git a/src/backend/utils/mb/conv.c b/src/backend/utils/mb/conv.c index 68fec7e090..a3ff9aaf8f 100644 --- a/src/backend/utils/mb/conv.c +++ b/src/backend/utils/mb/conv.c @@ -6,7 +6,7 @@ * WIN1250 client encoding support contributed by Pavel Behal * SJIS UDC (NEC selection IBM kanji) support contributed by Eiji Tokuya * - * $Id: conv.c,v 1.32 2001/10/16 10:09:17 ishii Exp $ + * $Id: conv.c,v 1.33 2001/10/25 05:49:51 momjian Exp $ * * */ @@ -64,7 +64,6 @@ #include "Unicode/utf8_to_koi8r.map" #include "Unicode/utf8_to_win1251.map" - #endif /* UNICODE_CONVERSION */ /* @@ -124,7 +123,6 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len) } else if (c1 > 0x7f) { - /* * JIS X0208, X0212, user defined extended characters */ @@ -168,7 +166,6 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len) } else if (k >= 0xf040 && k < 0xf540) { - /* * UDC1 mapping to X0208 85 ku - 94 ku JIS code 0x7521 - * 0x7e7e EUC 0xf5a1 - 0xfefe @@ -181,7 +178,6 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len) } else if (k >= 0xf540 && k < 0xfa40) { - /* * UDC2 mapping to X0212 85 ku - 94 ku JIS code 0x7521 - * 0x7e7e EUC 0x8ff5a1 - 0x8ffefe @@ -194,7 +190,6 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len) } else if (k >= 0xfa40) { - /* * mapping IBM kanji to X0208 and X0212 * @@ -624,7 +619,7 @@ big52mic(unsigned char *big5, unsigned char *p, int len) { if (lc == LC_CNS11643_3 || lc == LC_CNS11643_4) { - *p++ = 0x9d;/* LCPRV2 */ + *p++ = 0x9d; /* LCPRV2 */ } *p++ = lc; /* Plane No. */ *p++ = (cnsBuf >> 8) & 0x00ff; @@ -793,7 +788,6 @@ mic2latin5(unsigned char *mic, unsigned char *p, int len) { mic2latin(mic, p, len, LC_ISO8859_5); } - #endif /* @@ -1275,7 +1269,7 @@ compare2(const void *p1, const void *p2) */ static void utf_to_local(unsigned char *utf, unsigned char *iso, - pg_utf_to_local * map, int size, int len) + pg_utf_to_local *map, int size, int len) { unsigned int iutf; int l; @@ -1355,14 +1349,14 @@ utf_to_latin5(unsigned char *utf, unsigned char *iso, int len) { utf_to_local(utf, iso, ULmapISO8859_5, sizeof(ULmapISO8859_5) / sizeof(pg_utf_to_local), len); } -#endif /* NOT_USED */ +#endif /* NOT_USED */ /* * Cyrillic charsets */ /* - * UTF-8 --->KOI8-R + * UTF-8 --->KOI8-R */ static void utf_to_KOI8R(unsigned char *utf, unsigned char *iso, int len) @@ -1372,7 +1366,7 @@ utf_to_KOI8R(unsigned char *utf, unsigned char *iso, int len) } /* - * UTF-8 --->WIN1251 + * UTF-8 --->WIN1251 */ static void utf_to_WIN1251(unsigned char *utf, unsigned char *iso, int len) @@ -1382,7 +1376,7 @@ utf_to_WIN1251(unsigned char *utf, unsigned char *iso, int len) } /* - * UTF-8 --->ALT + * UTF-8 --->ALT */ static void utf_to_ALT(unsigned char *utf, unsigned char *iso, int len) @@ -1396,7 +1390,7 @@ utf_to_ALT(unsigned char *utf, unsigned char *iso, int len) */ static void local_to_utf(unsigned char *iso, unsigned char *utf, - pg_local_to_utf * map, int size, int encoding, int len) + pg_local_to_utf *map, int size, int encoding, int len) { unsigned int iiso; int l; @@ -1441,7 +1435,7 @@ local_to_utf(unsigned char *iso, unsigned char *utf, if (p == NULL) { elog(NOTICE, "local_to_utf: could not convert (0x%04x) %s to UTF-8. Ignored", - iiso, (&pg_enc2name_tbl[ encoding ])->name); + iiso, (&pg_enc2name_tbl[encoding])->name); continue; } if (p->utf & 0xff000000) @@ -1492,7 +1486,7 @@ latin5_to_utf(unsigned char *iso, unsigned char *utf, int len) { local_to_utf(iso, utf, LUmapISO8859_5, sizeof(LUmapISO8859_5) / sizeof(pg_local_to_utf), PG_LATIN5, len); } -#endif /* NOT_USED */ +#endif /* NOT_USED */ #define UTF_ISO8859(_id_) \ static void \ @@ -1546,6 +1540,7 @@ ALT_to_utf(unsigned char *iso, unsigned char *utf, int len) { local_to_utf(iso, utf, LUmapALT, sizeof(LUmapALT) / sizeof(pg_local_to_utf), PG_ALT, len); } + /* * UTF-8 ---> EUC_JP */ @@ -1564,7 +1559,7 @@ static void euc_jp_to_utf(unsigned char *euc, unsigned char *utf, int len) { local_to_utf(euc, utf, LUmapEUC_JP, - sizeof(LUmapEUC_JP) / sizeof(pg_local_to_utf), PG_EUC_JP, len); + sizeof(LUmapEUC_JP) / sizeof(pg_local_to_utf), PG_EUC_JP, len); } /* @@ -1585,7 +1580,7 @@ static void euc_cn_to_utf(unsigned char *euc, unsigned char *utf, int len) { local_to_utf(euc, utf, LUmapEUC_CN, - sizeof(LUmapEUC_CN) / sizeof(pg_local_to_utf), PG_EUC_CN, len); + sizeof(LUmapEUC_CN) / sizeof(pg_local_to_utf), PG_EUC_CN, len); } /* @@ -1606,7 +1601,7 @@ static void euc_kr_to_utf(unsigned char *euc, unsigned char *utf, int len) { local_to_utf(euc, utf, LUmapEUC_KR, - sizeof(LUmapEUC_KR) / sizeof(pg_local_to_utf), PG_EUC_KR, len); + sizeof(LUmapEUC_KR) / sizeof(pg_local_to_utf), PG_EUC_KR, len); } /* @@ -1627,7 +1622,7 @@ static void euc_tw_to_utf(unsigned char *euc, unsigned char *utf, int len) { local_to_utf(euc, utf, LUmapEUC_TW, - sizeof(LUmapEUC_TW) / sizeof(pg_local_to_utf), PG_EUC_TW, len); + sizeof(LUmapEUC_TW) / sizeof(pg_local_to_utf), PG_EUC_TW, len); } /* @@ -1648,7 +1643,7 @@ static void sjis_to_utf(unsigned char *euc, unsigned char *utf, int len) { local_to_utf(euc, utf, LUmapSJIS, - sizeof(LUmapSJIS) / sizeof(pg_local_to_utf), PG_SJIS, len); + sizeof(LUmapSJIS) / sizeof(pg_local_to_utf), PG_SJIS, len); } /* @@ -1669,7 +1664,7 @@ static void big5_to_utf(unsigned char *euc, unsigned char *utf, int len) { local_to_utf(euc, utf, LUmapBIG5, - sizeof(LUmapBIG5) / sizeof(pg_local_to_utf), PG_BIG5, len); + sizeof(LUmapBIG5) / sizeof(pg_local_to_utf), PG_BIG5, len); } /* ---------- @@ -1678,69 +1673,176 @@ big5_to_utf(unsigned char *euc, unsigned char *utf, int len) * WARINIG: must by same order as pg_enc in include/mb/pg_wchar.h! * ---------- */ -pg_enconv pg_enconv_tbl[] = -{ - { PG_SQL_ASCII, ascii2mic, mic2ascii, ascii2utf, utf2ascii}, - { PG_EUC_JP, euc_jp2mic, mic2euc_jp, euc_jp_to_utf, utf_to_euc_jp}, - { PG_EUC_CN, euc_cn2mic, mic2euc_cn, euc_cn_to_utf, utf_to_euc_cn}, - { PG_EUC_KR, euc_kr2mic, mic2euc_kr, euc_kr_to_utf, utf_to_euc_kr}, - { PG_EUC_TW, euc_tw2mic, mic2euc_tw, euc_tw_to_utf, utf_to_euc_tw}, - { PG_UTF8, 0, 0, 0, 0}, - { PG_MULE_INTERNAL, 0, 0, 0, 0}, - { PG_LATIN1, latin12mic, mic2latin1, iso8859_1_to_utf, utf_to_iso8859_1}, - { PG_LATIN2, latin22mic, mic2latin2, iso8859_2_to_utf, utf_to_iso8859_2}, - { PG_LATIN3, latin32mic, mic2latin3, iso8859_3_to_utf, utf_to_iso8859_3}, - { PG_LATIN4, latin42mic, mic2latin4, iso8859_4_to_utf, utf_to_iso8859_4}, - { PG_LATIN5, iso2mic, mic2iso, iso8859_9_to_utf, utf_to_iso8859_9}, - { PG_LATIN6, 0, 0, iso8859_10_to_utf, utf_to_iso8859_10}, - { PG_LATIN7, 0, 0, iso8859_13_to_utf, utf_to_iso8859_13}, - { PG_LATIN8, 0, 0, iso8859_14_to_utf, utf_to_iso8859_14}, - { PG_LATIN9, 0, 0, iso8859_15_to_utf, utf_to_iso8859_15}, - { PG_LATIN10, 0, 0, iso8859_16_to_utf, utf_to_iso8859_16}, - { PG_KOI8R, koi8r2mic, mic2koi8r, KOI8R_to_utf, utf_to_KOI8R}, - { PG_WIN1251, win12512mic, mic2win1251, WIN1251_to_utf, utf_to_WIN1251}, - { PG_ALT, alt2mic, mic2alt, ALT_to_utf, utf_to_ALT}, - { PG_ISO_8859_5, 0, 0, iso8859_5_to_utf, utf_to_iso8859_5}, - { PG_ISO_8859_6, 0, 0, iso8859_6_to_utf, utf_to_iso8859_6}, - { PG_ISO_8859_7, 0, 0, iso8859_7_to_utf, utf_to_iso8859_7}, - { PG_ISO_8859_8, 0, 0, iso8859_8_to_utf, utf_to_iso8859_8}, - - { PG_SJIS, sjis2mic, mic2sjis, sjis_to_utf, utf_to_sjis}, - { PG_BIG5, big52mic, mic2big5, big5_to_utf, utf_to_big5}, - { PG_WIN1250, win12502mic, mic2win1250, 0, 0}, +pg_enconv pg_enconv_tbl[] = +{ + { + PG_SQL_ASCII, ascii2mic, mic2ascii, ascii2utf, utf2ascii + } , + { + PG_EUC_JP, euc_jp2mic, mic2euc_jp, euc_jp_to_utf, utf_to_euc_jp + }, + { + PG_EUC_CN, euc_cn2mic, mic2euc_cn, euc_cn_to_utf, utf_to_euc_cn + }, + { + PG_EUC_KR, euc_kr2mic, mic2euc_kr, euc_kr_to_utf, utf_to_euc_kr + }, + { + PG_EUC_TW, euc_tw2mic, mic2euc_tw, euc_tw_to_utf, utf_to_euc_tw + }, + { + PG_UTF8, 0, 0, 0, 0 + }, + { + PG_MULE_INTERNAL, 0, 0, 0, 0 + }, + { + PG_LATIN1, latin12mic, mic2latin1, iso8859_1_to_utf, utf_to_iso8859_1 + }, + { + PG_LATIN2, latin22mic, mic2latin2, iso8859_2_to_utf, utf_to_iso8859_2 + }, + { + PG_LATIN3, latin32mic, mic2latin3, iso8859_3_to_utf, utf_to_iso8859_3 + }, + { + PG_LATIN4, latin42mic, mic2latin4, iso8859_4_to_utf, utf_to_iso8859_4 + }, + { + PG_LATIN5, iso2mic, mic2iso, iso8859_9_to_utf, utf_to_iso8859_9 + }, + { + PG_LATIN6, 0, 0, iso8859_10_to_utf, utf_to_iso8859_10 + }, + { + PG_LATIN7, 0, 0, iso8859_13_to_utf, utf_to_iso8859_13 + }, + { + PG_LATIN8, 0, 0, iso8859_14_to_utf, utf_to_iso8859_14 + }, + { + PG_LATIN9, 0, 0, iso8859_15_to_utf, utf_to_iso8859_15 + }, + { + PG_LATIN10, 0, 0, iso8859_16_to_utf, utf_to_iso8859_16 + }, + { + PG_KOI8R, koi8r2mic, mic2koi8r, KOI8R_to_utf, utf_to_KOI8R + }, + { + PG_WIN1251, win12512mic, mic2win1251, WIN1251_to_utf, utf_to_WIN1251 + }, + { + PG_ALT, alt2mic, mic2alt, ALT_to_utf, utf_to_ALT + }, + { + PG_ISO_8859_5, 0, 0, iso8859_5_to_utf, utf_to_iso8859_5 + }, + { + PG_ISO_8859_6, 0, 0, iso8859_6_to_utf, utf_to_iso8859_6 + }, + { + PG_ISO_8859_7, 0, 0, iso8859_7_to_utf, utf_to_iso8859_7 + }, + { + PG_ISO_8859_8, 0, 0, iso8859_8_to_utf, utf_to_iso8859_8 + }, + + { + PG_SJIS, sjis2mic, mic2sjis, sjis_to_utf, utf_to_sjis + }, + { + PG_BIG5, big52mic, mic2big5, big5_to_utf, utf_to_big5 + }, + { + PG_WIN1250, win12502mic, mic2win1250, 0, 0 + }, }; #else -pg_enconv pg_enconv_tbl[] = -{ - { PG_SQL_ASCII, ascii2mic, mic2ascii, 0, 0}, - { PG_EUC_JP, euc_jp2mic, mic2euc_jp, 0, 0}, - { PG_EUC_CN, euc_cn2mic, mic2euc_cn, 0, 0}, - { PG_EUC_KR, euc_kr2mic, mic2euc_kr, 0, 0}, - { PG_EUC_TW, euc_tw2mic, mic2euc_tw, 0, 0}, - { PG_UTF8, 0, 0, 0, 0}, - { PG_MULE_INTERNAL, 0, 0, 0, 0}, - { PG_LATIN1, latin12mic, mic2latin1, 0, 0}, - { PG_LATIN2, latin22mic, mic2latin2, 0, 0}, - { PG_LATIN3, latin32mic, mic2latin3, 0, 0}, - { PG_LATIN4, latin42mic, mic2latin4, 0, 0}, - { PG_LATIN5, iso2mic, mic2iso, 0, 0}, - { PG_LATIN6, 0, 0, 0, 0}, - { PG_LATIN7, 0, 0, 0, 0}, - { PG_LATIN8, 0, 0, 0, 0}, - { PG_LATIN9, 0, 0, 0, 0}, - { PG_LATIN10, 0, 0, 0, 0}, - { PG_KOI8R, koi8r2mic, mic2koi8r, 0, 0}, - { PG_WIN1251, win12512mic, mic2win1251, 0, 0}, - { PG_ALT, alt2mic, mic2alt, 0, 0}, - { PG_ISO_8859_5, 0, 0, 0, 0}, - { PG_ISO_8859_6, 0, 0, 0, 0}, - { PG_ISO_8859_7, 0, 0, 0, 0}, - { PG_ISO_8859_8, 0, 0, 0, 0}, - { PG_SJIS, sjis2mic, mic2sjis, 0, 0}, - { PG_BIG5, big52mic, mic2big5, 0, 0}, - { PG_WIN1250, win12502mic, mic2win1250, 0, 0}, +pg_enconv pg_enconv_tbl[] = +{ + { + PG_SQL_ASCII, ascii2mic, mic2ascii, 0, 0 + } , + { + PG_EUC_JP, euc_jp2mic, mic2euc_jp, 0, 0 + }, + { + PG_EUC_CN, euc_cn2mic, mic2euc_cn, 0, 0 + }, + { + PG_EUC_KR, euc_kr2mic, mic2euc_kr, 0, 0 + }, + { + PG_EUC_TW, euc_tw2mic, mic2euc_tw, 0, 0 + }, + { + PG_UTF8, 0, 0, 0, 0 + }, + { + PG_MULE_INTERNAL, 0, 0, 0, 0 + }, + { + PG_LATIN1, latin12mic, mic2latin1, 0, 0 + }, + { + PG_LATIN2, latin22mic, mic2latin2, 0, 0 + }, + { + PG_LATIN3, latin32mic, mic2latin3, 0, 0 + }, + { + PG_LATIN4, latin42mic, mic2latin4, 0, 0 + }, + { + PG_LATIN5, iso2mic, mic2iso, 0, 0 + }, + { + PG_LATIN6, 0, 0, 0, 0 + }, + { + PG_LATIN7, 0, 0, 0, 0 + }, + { + PG_LATIN8, 0, 0, 0, 0 + }, + { + PG_LATIN9, 0, 0, 0, 0 + }, + { + PG_LATIN10, 0, 0, 0, 0 + }, + { + PG_KOI8R, koi8r2mic, mic2koi8r, 0, 0 + }, + { + PG_WIN1251, win12512mic, mic2win1251, 0, 0 + }, + { + PG_ALT, alt2mic, mic2alt, 0, 0 + }, + { + PG_ISO_8859_5, 0, 0, 0, 0 + }, + { + PG_ISO_8859_6, 0, 0, 0, 0 + }, + { + PG_ISO_8859_7, 0, 0, 0, 0 + }, + { + PG_ISO_8859_8, 0, 0, 0, 0 + }, + { + PG_SJIS, sjis2mic, mic2sjis, 0, 0 + }, + { + PG_BIG5, big52mic, mic2big5, 0, 0 + }, + { + PG_WIN1250, win12502mic, mic2win1250, 0, 0 + }, }; - #endif /* UNICODE_CONVERSION */ diff --git a/src/backend/utils/mb/encnames.c b/src/backend/utils/mb/encnames.c index f2e16460eb..7667e478aa 100644 --- a/src/backend/utils/mb/encnames.c +++ b/src/backend/utils/mb/encnames.c @@ -2,7 +2,7 @@ * Encoding names and routines for work with it. All * in this file is shared bedween FE and BE. * - * $Id: encnames.c,v 1.4 2001/10/16 10:09:17 ishii Exp $ + * $Id: encnames.c,v 1.5 2001/10/25 05:49:51 momjian Exp $ */ #ifdef FRONTEND #include "postgres_fe.h" @@ -23,7 +23,7 @@ #include <ctype.h> /* ---------- - * All encoding names, sorted: *** A L P H A B E T I C *** + * All encoding names, sorted: *** A L P H A B E T I C *** * * All names must be without irrelevan chars, search routines use * isalnum() chars only. It means ISO-8859-1, iso_8859-1 and Iso8859_1 @@ -34,58 +34,153 @@ * Karel Zak, Aug 2001 * ---------- */ -pg_encname pg_encname_tbl[] = +pg_encname pg_encname_tbl[] = { - { "alt", PG_ALT }, /* IBM866 */ - { "big5", PG_BIG5 }, /* Big5; Chinese for Taiwan Multi-byte set */ - { "euccn", PG_EUC_CN }, /* EUC-CN; Extended Unix Code for simplified Chinese */ - { "eucjp", PG_EUC_JP }, /* EUC-JP; Extended UNIX Code fixed Width for Japanese, stdandard OSF */ - { "euckr", PG_EUC_KR }, /* EUC-KR; RFC1557,Choi */ - { "euctw", PG_EUC_TW }, /* EUC-TW; Extended Unix Code for traditional Chinese */ - { "iso88591", PG_LATIN1 }, /* ISO-8859-1; RFC1345,KXS2 */ - { "iso885910", PG_LATIN6 }, /* ISO-8859-10; RFC1345,KXS2 */ - { "iso885913", PG_LATIN7 }, /* ISO-8859-13; RFC1345,KXS2 */ - { "iso885914", PG_LATIN8 }, /* ISO-8859-14; RFC1345,KXS2 */ - { "iso885915", PG_LATIN9 }, /* ISO-8859-15; RFC1345,KXS2 */ - { "iso885916", PG_LATIN10 }, /* ISO-8859-16; RFC1345,KXS2 */ - { "iso88592", PG_LATIN2 }, /* ISO-8859-2; RFC1345,KXS2 */ - { "iso88593", PG_LATIN3 }, /* ISO-8859-3; RFC1345,KXS2 */ - { "iso88594", PG_LATIN4 }, /* ISO-8859-4; RFC1345,KXS2 */ - { "iso88595", PG_ISO_8859_5 }, /* ISO-8859-5; RFC1345,KXS2 */ - { "iso88596", PG_ISO_8859_6 }, /* ISO-8859-6; RFC1345,KXS2 */ - { "iso88597", PG_ISO_8859_7 }, /* ISO-8859-7; RFC1345,KXS2 */ - { "iso88598", PG_ISO_8859_8 }, /* ISO-8859-8; RFC1345,KXS2 */ - { "iso88599", PG_LATIN5 }, /* ISO-8859-9; RFC1345,KXS2 */ - { "koi8", PG_KOI8R }, /* _dirty_ alias for KOI8-R (backward compatibility) */ - { "koi8r", PG_KOI8R }, /* KOI8-R; RFC1489 */ - { "latin1", PG_LATIN1 }, /* alias for ISO-8859-1 */ - { "latin10", PG_LATIN10}, /* alias for ISO-8859-16 */ - { "latin2", PG_LATIN2 }, /* alias for ISO-8859-2 */ - { "latin3", PG_LATIN3 }, /* alias for ISO-8859-3 */ - { "latin4", PG_LATIN4 }, /* alias for ISO-8859-4 */ - { "latin5", PG_LATIN5 }, /* alias for ISO-8859-9 */ - { "latin6", PG_LATIN6}, /* alias for ISO-8859-10 */ - { "latin7", PG_LATIN7}, /* alias for ISO-8859-13 */ - { "latin8", PG_LATIN8}, /* alias for ISO-8859-14 */ - { "latin9", PG_LATIN9}, /* alias for ISO-8859-15 */ - { "mskanji", PG_SJIS }, /* alias for Shift_JIS */ - { "muleinternal",PG_MULE_INTERNAL }, - { "shiftjis", PG_SJIS }, /* Shift_JIS; JIS X 0202-1991 */ - { "sjis", PG_SJIS }, /* alias for Shift_JIS */ - { "sqlascii", PG_SQL_ASCII }, - { "unicode", PG_UTF8 }, /* alias for UTF-8 */ - { "utf8", PG_UTF8 }, /* UTF-8; RFC2279 */ - { "win", PG_WIN1251 }, /* _dirty_ alias for windows-1251 (backward compatibility) */ - { "win1250", PG_WIN1250 }, /* alias for Windows-1250 */ - { "win1251", PG_WIN1251 }, /* alias for Windows-1251 */ - { "windows1250",PG_WIN1250 }, /* Windows-1251; Microsoft */ - { "windows1251",PG_WIN1251 }, /* Windows-1251; Microsoft */ + { + "alt", PG_ALT + } , /* IBM866 */ + { + "big5", PG_BIG5 + }, /* Big5; Chinese for Taiwan Multi-byte set */ + { + "euccn", PG_EUC_CN + }, /* EUC-CN; Extended Unix Code for + * simplified Chinese */ + { + "eucjp", PG_EUC_JP + }, /* EUC-JP; Extended UNIX Code fixed Width + * for Japanese, stdandard OSF */ + { + "euckr", PG_EUC_KR + }, /* EUC-KR; RFC1557,Choi */ + { + "euctw", PG_EUC_TW + }, /* EUC-TW; Extended Unix Code for + * traditional Chinese */ + { + "iso88591", PG_LATIN1 + }, /* ISO-8859-1; RFC1345,KXS2 */ + { + "iso885910", PG_LATIN6 + }, /* ISO-8859-10; RFC1345,KXS2 */ + { + "iso885913", PG_LATIN7 + }, /* ISO-8859-13; RFC1345,KXS2 */ + { + "iso885914", PG_LATIN8 + }, /* ISO-8859-14; RFC1345,KXS2 */ + { + "iso885915", PG_LATIN9 + }, /* ISO-8859-15; RFC1345,KXS2 */ + { + "iso885916", PG_LATIN10 + }, /* ISO-8859-16; RFC1345,KXS2 */ + { + "iso88592", PG_LATIN2 + }, /* ISO-8859-2; RFC1345,KXS2 */ + { + "iso88593", PG_LATIN3 + }, /* ISO-8859-3; RFC1345,KXS2 */ + { + "iso88594", PG_LATIN4 + }, /* ISO-8859-4; RFC1345,KXS2 */ + { + "iso88595", PG_ISO_8859_5 + }, /* ISO-8859-5; RFC1345,KXS2 */ + { + "iso88596", PG_ISO_8859_6 + }, /* ISO-8859-6; RFC1345,KXS2 */ + { + "iso88597", PG_ISO_8859_7 + }, /* ISO-8859-7; RFC1345,KXS2 */ + { + "iso88598", PG_ISO_8859_8 + }, /* ISO-8859-8; RFC1345,KXS2 */ + { + "iso88599", PG_LATIN5 + }, /* ISO-8859-9; RFC1345,KXS2 */ + { + "koi8", PG_KOI8R + }, /* _dirty_ alias for KOI8-R (backward + * compatibility) */ + { + "koi8r", PG_KOI8R + }, /* KOI8-R; RFC1489 */ + { + "latin1", PG_LATIN1 + }, /* alias for ISO-8859-1 */ + { + "latin10", PG_LATIN10 + }, /* alias for ISO-8859-16 */ + { + "latin2", PG_LATIN2 + }, /* alias for ISO-8859-2 */ + { + "latin3", PG_LATIN3 + }, /* alias for ISO-8859-3 */ + { + "latin4", PG_LATIN4 + }, /* alias for ISO-8859-4 */ + { + "latin5", PG_LATIN5 + }, /* alias for ISO-8859-9 */ + { + "latin6", PG_LATIN6 + }, /* alias for ISO-8859-10 */ + { + "latin7", PG_LATIN7 + }, /* alias for ISO-8859-13 */ + { + "latin8", PG_LATIN8 + }, /* alias for ISO-8859-14 */ + { + "latin9", PG_LATIN9 + }, /* alias for ISO-8859-15 */ + { + "mskanji", PG_SJIS + }, /* alias for Shift_JIS */ + { + "muleinternal", PG_MULE_INTERNAL + }, + { + "shiftjis", PG_SJIS + }, /* Shift_JIS; JIS X 0202-1991 */ + { + "sjis", PG_SJIS + }, /* alias for Shift_JIS */ + { + "sqlascii", PG_SQL_ASCII + }, + { + "unicode", PG_UTF8 + }, /* alias for UTF-8 */ + { + "utf8", PG_UTF8 + }, /* UTF-8; RFC2279 */ + { + "win", PG_WIN1251 + }, /* _dirty_ alias for windows-1251 + * (backward compatibility) */ + { + "win1250", PG_WIN1250 + }, /* alias for Windows-1250 */ + { + "win1251", PG_WIN1251 + }, /* alias for Windows-1251 */ + { + "windows1250", PG_WIN1250 + }, /* Windows-1251; Microsoft */ + { + "windows1251", PG_WIN1251 + }, /* Windows-1251; Microsoft */ - { NULL, 0 } /* last */ + { + NULL, 0 + } /* last */ }; unsigned int pg_encname_tbl_sz = \ - sizeof(pg_encname_tbl) / sizeof(pg_encname_tbl[0]) -1; +sizeof(pg_encname_tbl) / sizeof(pg_encname_tbl[0]) - 1; /* ---------- * These are "official" encoding names. @@ -94,33 +189,87 @@ unsigned int pg_encname_tbl_sz = \ */ pg_enc2name pg_enc2name_tbl[] = { - { "SQL_ASCII", PG_SQL_ASCII }, - { "EUC_JP", PG_EUC_JP }, - { "EUC_CN", PG_EUC_CN }, - { "EUC_KR", PG_EUC_KR }, - { "EUC_TW", PG_EUC_TW }, - { "UNICODE", PG_UTF8 }, - { "MULE_INTERNAL",PG_MULE_INTERNAL }, - { "LATIN1", PG_LATIN1 }, - { "LATIN2", PG_LATIN2 }, - { "LATIN3", PG_LATIN3 }, - { "LATIN4", PG_LATIN4 }, - { "LATIN5", PG_LATIN5 }, - { "LATIN6", PG_LATIN6 }, - { "LATIN7", PG_LATIN7 }, - { "LATIN8", PG_LATIN8 }, - { "LATIN9", PG_LATIN9 }, - { "LATIN10", PG_LATIN10 }, - { "KOI8", PG_KOI8R }, - { "WIN", PG_WIN1251 }, - { "ALT", PG_ALT }, - { "ISO_8859_5", PG_ISO_8859_5 }, - { "ISO_8859_6", PG_ISO_8859_6 }, - { "ISO_8859_7", PG_ISO_8859_7 }, - { "ISO_8859_8", PG_ISO_8859_8 }, - { "SJIS", PG_SJIS }, - { "BIG5", PG_BIG5 }, - { "WIN1250", PG_WIN1250 } + { + "SQL_ASCII", PG_SQL_ASCII + } , + { + "EUC_JP", PG_EUC_JP + }, + { + "EUC_CN", PG_EUC_CN + }, + { + "EUC_KR", PG_EUC_KR + }, + { + "EUC_TW", PG_EUC_TW + }, + { + "UNICODE", PG_UTF8 + }, + { + "MULE_INTERNAL", PG_MULE_INTERNAL + }, + { + "LATIN1", PG_LATIN1 + }, + { + "LATIN2", PG_LATIN2 + }, + { + "LATIN3", PG_LATIN3 + }, + { + "LATIN4", PG_LATIN4 + }, + { + "LATIN5", PG_LATIN5 + }, + { + "LATIN6", PG_LATIN6 + }, + { + "LATIN7", PG_LATIN7 + }, + { + "LATIN8", PG_LATIN8 + }, + { + "LATIN9", PG_LATIN9 + }, + { + "LATIN10", PG_LATIN10 + }, + { + "KOI8", PG_KOI8R + }, + { + "WIN", PG_WIN1251 + }, + { + "ALT", PG_ALT + }, + { + "ISO_8859_5", PG_ISO_8859_5 + }, + { + "ISO_8859_6", PG_ISO_8859_6 + }, + { + "ISO_8859_7", PG_ISO_8859_7 + }, + { + "ISO_8859_8", PG_ISO_8859_8 + }, + { + "SJIS", PG_SJIS + }, + { + "BIG5", PG_BIG5 + }, + { + "WIN1250", PG_WIN1250 + } }; /* ---------- @@ -130,12 +279,12 @@ pg_enc2name pg_enc2name_tbl[] = int pg_valid_client_encoding(const char *name) { - int enc; + int enc; if ((enc = pg_char_to_encoding(name)) < 0) return -1; - if (!PG_VALID_FE_ENCODING( enc)) + if (!PG_VALID_FE_ENCODING(enc)) return -1; return enc; @@ -144,12 +293,12 @@ pg_valid_client_encoding(const char *name) int pg_valid_server_encoding(const char *name) { - int enc; + int enc; if ((enc = pg_char_to_encoding(name)) < 0) return -1; - if (!PG_VALID_BE_ENCODING( enc)) + if (!PG_VALID_BE_ENCODING(enc)) return -1; return enc; @@ -162,12 +311,13 @@ pg_valid_server_encoding(const char *name) static char * clean_encoding_name(char *key, char *newkey) { - char *p, *np; + char *p, + *np; - for(p=key, np=newkey; *p!='\0'; p++) + for (p = key, np = newkey; *p != '\0'; p++) { if (isalnum((unsigned char) *p)) - *np++=tolower((unsigned char) *p); + *np++ = tolower((unsigned char) *p); } *np = '\0'; return newkey; @@ -180,15 +330,15 @@ clean_encoding_name(char *key, char *newkey) pg_encname * pg_char_to_encname_struct(const char *name) { - unsigned int nel = pg_encname_tbl_sz; - pg_encname *base = pg_encname_tbl, - *last = base + nel - 1, - *position; - int result; + unsigned int nel = pg_encname_tbl_sz; + pg_encname *base = pg_encname_tbl, + *last = base + nel - 1, + *position; + int result; char buff[NAMEDATALEN], - *key; + *key; - if(name==NULL || *name=='\0') + if (name == NULL || *name == '\0') return NULL; if (strlen(name) > NAMEDATALEN) @@ -241,6 +391,7 @@ Datum PG_char_to_encoding(PG_FUNCTION_ARGS) { Name s = PG_GETARG_NAME(0); + PG_RETURN_INT32(pg_char_to_encoding(NameStr(*s))); } #endif @@ -250,8 +401,9 @@ pg_encoding_to_char(int encoding) { if (PG_VALID_ENCODING(encoding)) { - pg_enc2name *p = &pg_enc2name_tbl[ encoding ]; - Assert( encoding == p->encoding ); + pg_enc2name *p = &pg_enc2name_tbl[encoding]; + + Assert(encoding == p->encoding); return p->name; } return ""; @@ -262,9 +414,8 @@ Datum PG_encoding_to_char(PG_FUNCTION_ARGS) { int32 encoding = PG_GETARG_INT32(0); - const char *encoding_name = pg_encoding_to_char(encoding); + const char *encoding_name = pg_encoding_to_char(encoding); return DirectFunctionCall1(namein, CStringGetDatum(encoding_name)); } #endif - diff --git a/src/backend/utils/mb/mbutils.c b/src/backend/utils/mb/mbutils.c index c0949a6324..645b9f3260 100644 --- a/src/backend/utils/mb/mbutils.c +++ b/src/backend/utils/mb/mbutils.c @@ -3,7 +3,7 @@ * client encoding and server internal encoding. * (currently mule internal code (mic) is used) * Tatsuo Ishii - * $Id: mbutils.c,v 1.24 2001/10/12 02:08:34 ishii Exp $ + * $Id: mbutils.c,v 1.25 2001/10/25 05:49:51 momjian Exp $ */ #include "postgres.h" @@ -12,7 +12,7 @@ #include "utils/builtins.h" /* - * We handle for actual FE and BE encoding setting encoding-identificator + * We handle for actual FE and BE encoding setting encoding-identificator * and encoding-name too. It prevent searching and conversion from encoding * to encoding name in getdatabaseencoding() and other routines. * @@ -21,13 +21,13 @@ * * Karel Zak (Aug 2001) */ -static pg_enc2name *ClientEncoding = &pg_enc2name_tbl[ PG_SQL_ASCII ]; -static pg_enc2name *DatabaseEncoding = &pg_enc2name_tbl[ PG_SQL_ASCII ]; +static pg_enc2name *ClientEncoding = &pg_enc2name_tbl[PG_SQL_ASCII]; +static pg_enc2name *DatabaseEncoding = &pg_enc2name_tbl[PG_SQL_ASCII]; static to_mic_converter client_to_mic; /* something to MIC */ -static from_mic_converter client_from_mic; /* MIC to something */ +static from_mic_converter client_from_mic; /* MIC to something */ static to_mic_converter server_to_mic; /* something to MIC */ -static from_mic_converter server_from_mic; /* MIC to something */ +static from_mic_converter server_from_mic; /* MIC to something */ /* * find encoding table entry by encoding @@ -37,8 +37,8 @@ pg_get_enconv_by_encoding(int encoding) { if (PG_VALID_ENCODING(encoding)) { - Assert((&pg_enconv_tbl[ encoding ])->encoding == encoding); - return &pg_enconv_tbl[ encoding ]; + Assert((&pg_enconv_tbl[encoding])->encoding == encoding); + return &pg_enconv_tbl[encoding]; } return 0; } @@ -113,7 +113,7 @@ pg_find_encoding_converters(int src, int dest, int pg_set_client_encoding(int encoding) { - int current_server_encoding = DatabaseEncoding->encoding; + int current_server_encoding = DatabaseEncoding->encoding; if (!PG_VALID_FE_ENCODING(encoding)) return (-1); @@ -121,7 +121,7 @@ pg_set_client_encoding(int encoding) if (pg_find_encoding_converters(encoding, current_server_encoding, &client_to_mic, &server_from_mic) < 0) return (-1); - ClientEncoding = &pg_enc2name_tbl[ encoding ]; + ClientEncoding = &pg_enc2name_tbl[encoding]; Assert(ClientEncoding->encoding == encoding); @@ -162,7 +162,7 @@ pg_get_client_encoding_name(void) * function). Another case is you have direct-conversion function from * src to dest. In this case either src_to_mic or dest_from_mic could * be set to 0 also. - * + * * Note that If src or dest is UNICODE, we have to do * direct-conversion, since we don't support conversion bwteen UNICODE * and MULE_INTERNAL, we cannot go through MULE_INTERNAL. @@ -175,7 +175,7 @@ pg_get_client_encoding_name(void) * to determine whether to pfree the result or not! * * Note: we assume that conversion cannot cause more than a 4-to-1 growth - * in the length of the string --- is this enough? */ + * in the length of the string --- is this enough? */ unsigned char * pg_do_encoding_conversion(unsigned char *src, int len, @@ -212,32 +212,33 @@ pg_do_encoding_conversion(unsigned char *src, int len, Datum pg_convert(PG_FUNCTION_ARGS) { - text *string = PG_GETARG_TEXT_P(0); - Name s = PG_GETARG_NAME(1); - int encoding = pg_char_to_encoding(NameStr(*s)); - int db_encoding = DatabaseEncoding->encoding; + text *string = PG_GETARG_TEXT_P(0); + Name s = PG_GETARG_NAME(1); + int encoding = pg_char_to_encoding(NameStr(*s)); + int db_encoding = DatabaseEncoding->encoding; to_mic_converter src; from_mic_converter dest; - unsigned char *result; - text *retval; + unsigned char *result; + text *retval; if (encoding < 0) - elog(ERROR, "Invalid encoding name %s", NameStr(*s)); + elog(ERROR, "Invalid encoding name %s", NameStr(*s)); if (pg_find_encoding_converters(db_encoding, encoding, &src, &dest) < 0) { - char *encoding_name = (char *)pg_encoding_to_char(db_encoding); - elog(ERROR, "Conversion from %s to %s is not possible", NameStr(*s), encoding_name); + char *encoding_name = (char *) pg_encoding_to_char(db_encoding); + + elog(ERROR, "Conversion from %s to %s is not possible", NameStr(*s), encoding_name); } - result = pg_do_encoding_conversion(VARDATA(string), VARSIZE(string)-VARHDRSZ, - src, dest); + result = pg_do_encoding_conversion(VARDATA(string), VARSIZE(string) - VARHDRSZ, + src, dest); if (result == NULL) - elog(ERROR, "Encoding conversion failed"); + elog(ERROR, "Encoding conversion failed"); retval = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(result))); - if (result != (unsigned char *)VARDATA(string)) - pfree(result); + if (result != (unsigned char *) VARDATA(string)) + pfree(result); /* free memory if allocated by the toaster */ PG_FREE_IF_COPY(string, 0); @@ -253,35 +254,35 @@ pg_convert(PG_FUNCTION_ARGS) Datum pg_convert2(PG_FUNCTION_ARGS) { - text *string = PG_GETARG_TEXT_P(0); - char *src_encoding_name = NameStr(*PG_GETARG_NAME(1)); - int src_encoding = pg_char_to_encoding(src_encoding_name); - char *dest_encoding_name = NameStr(*PG_GETARG_NAME(2)); - int dest_encoding = pg_char_to_encoding(dest_encoding_name); + text *string = PG_GETARG_TEXT_P(0); + char *src_encoding_name = NameStr(*PG_GETARG_NAME(1)); + int src_encoding = pg_char_to_encoding(src_encoding_name); + char *dest_encoding_name = NameStr(*PG_GETARG_NAME(2)); + int dest_encoding = pg_char_to_encoding(dest_encoding_name); to_mic_converter src; from_mic_converter dest; - unsigned char *result; - text *retval; + unsigned char *result; + text *retval; if (src_encoding < 0) - elog(ERROR, "Invalid source encoding name %s", src_encoding_name); + elog(ERROR, "Invalid source encoding name %s", src_encoding_name); if (dest_encoding < 0) - elog(ERROR, "Invalid destination encoding name %s", dest_encoding_name); + elog(ERROR, "Invalid destination encoding name %s", dest_encoding_name); if (pg_find_encoding_converters(src_encoding, dest_encoding, &src, &dest) < 0) { - elog(ERROR, "Conversion from %s to %s is not possible", - src_encoding_name, dest_encoding_name); + elog(ERROR, "Conversion from %s to %s is not possible", + src_encoding_name, dest_encoding_name); } - result = pg_do_encoding_conversion(VARDATA(string), VARSIZE(string)-VARHDRSZ, - src, dest); + result = pg_do_encoding_conversion(VARDATA(string), VARSIZE(string) - VARHDRSZ, + src, dest); if (result == NULL) - elog(ERROR, "Encoding conversion failed"); + elog(ERROR, "Encoding conversion failed"); retval = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(result))); - if (result != (unsigned char *)VARDATA(string)) - pfree(result); + if (result != (unsigned char *) VARDATA(string)) + pfree(result); /* free memory if allocated by the toaster */ PG_FREE_IF_COPY(string, 0); @@ -309,7 +310,7 @@ pg_client_to_server(unsigned char *s, int len) Assert(ClientEncoding); if (ClientEncoding->encoding == DatabaseEncoding->encoding) - return s; + return s; return pg_do_encoding_conversion(s, len, client_to_mic, server_from_mic); } @@ -341,23 +342,23 @@ pg_server_to_client(unsigned char *s, int len) /* convert a multi-byte string to a wchar */ int -pg_mb2wchar(const unsigned char *from, pg_wchar * to) +pg_mb2wchar(const unsigned char *from, pg_wchar *to) { - return (*pg_wchar_table[ DatabaseEncoding->encoding ].mb2wchar_with_len) (from, to, strlen(from)); + return (*pg_wchar_table[DatabaseEncoding->encoding].mb2wchar_with_len) (from, to, strlen(from)); } /* convert a multi-byte string to a wchar with a limited length */ int -pg_mb2wchar_with_len(const unsigned char *from, pg_wchar * to, int len) +pg_mb2wchar_with_len(const unsigned char *from, pg_wchar *to, int len) { - return (*pg_wchar_table[ DatabaseEncoding->encoding ].mb2wchar_with_len) (from, to, len); + return (*pg_wchar_table[DatabaseEncoding->encoding].mb2wchar_with_len) (from, to, len); } /* returns the byte length of a multi-byte word */ int pg_mblen(const unsigned char *mbstr) { - return ((*pg_wchar_table[ DatabaseEncoding->encoding ].mblen) (mbstr)); + return ((*pg_wchar_table[DatabaseEncoding->encoding].mblen) (mbstr)); } /* returns the length (counted as a wchar) of a multi-byte string */ @@ -447,7 +448,7 @@ SetDatabaseEncoding(int encoding) if (!PG_VALID_BE_ENCODING(encoding)) elog(ERROR, "SetDatabaseEncoding(): invalid database encoding"); - DatabaseEncoding = &pg_enc2name_tbl[ encoding ]; + DatabaseEncoding = &pg_enc2name_tbl[encoding]; Assert(DatabaseEncoding->encoding == encoding); } diff --git a/src/backend/utils/mb/wchar.c b/src/backend/utils/mb/wchar.c index 0c51da5ab7..9d778d0041 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 multi-byte streams. * Tatsuo Ishii - * $Id: wchar.c,v 1.24 2001/10/15 01:19:15 ishii Exp $ + * $Id: wchar.c,v 1.25 2001/10/25 05:49:51 momjian Exp $ * * WIN1250 client encoding updated by Pavel Behal * @@ -29,7 +29,7 @@ * SQL/ASCII */ static int pg_ascii2wchar_with_len - (const unsigned char *from, pg_wchar * to, int len) + (const unsigned char *from, pg_wchar *to, int len) { int cnt = 0; @@ -54,7 +54,7 @@ pg_ascii_mblen(const unsigned char *s) */ static int pg_euc2wchar_with_len - (const unsigned char *from, pg_wchar * to, int len) + (const unsigned char *from, pg_wchar *to, int len) { int cnt = 0; @@ -111,7 +111,7 @@ pg_euc_mblen(const unsigned char *s) * EUC_JP */ static int pg_eucjp2wchar_with_len - (const unsigned char *from, pg_wchar * to, int len) + (const unsigned char *from, pg_wchar *to, int len) { return (pg_euc2wchar_with_len(from, to, len)); } @@ -126,7 +126,7 @@ pg_eucjp_mblen(const unsigned char *s) * EUC_KR */ static int pg_euckr2wchar_with_len - (const unsigned char *from, pg_wchar * to, int len) + (const unsigned char *from, pg_wchar *to, int len) { return (pg_euc2wchar_with_len(from, to, len)); } @@ -141,7 +141,7 @@ pg_euckr_mblen(const unsigned char *s) * EUC_CN */ static int pg_euccn2wchar_with_len - (const unsigned char *from, pg_wchar * to, int len) + (const unsigned char *from, pg_wchar *to, int len) { int cnt = 0; @@ -195,7 +195,7 @@ pg_euccn_mblen(const unsigned char *s) * EUC_TW */ static int pg_euctw2wchar_with_len - (const unsigned char *from, pg_wchar * to, int len) + (const unsigned char *from, pg_wchar *to, int len) { int cnt = 0; @@ -257,7 +257,7 @@ pg_euctw_mblen(const unsigned char *s) * "from" not necessarily null terminated. */ static int -pg_utf2wchar_with_len(const unsigned char *from, pg_wchar * to, int len) +pg_utf2wchar_with_len(const unsigned char *from, pg_wchar *to, int len) { unsigned char c1, c2, @@ -325,7 +325,7 @@ pg_utf_mblen(const unsigned char *s) * "from" not necessarily null terminated. */ static int -pg_mule2wchar_with_len(const unsigned char *from, pg_wchar * to, int len) +pg_mule2wchar_with_len(const unsigned char *from, pg_wchar *to, int len) { int cnt = 0; @@ -395,7 +395,7 @@ pg_mule_mblen(const unsigned char *s) * ISO8859-1 */ static int -pg_latin12wchar_with_len(const unsigned char *from, pg_wchar * to, int len) +pg_latin12wchar_with_len(const unsigned char *from, pg_wchar *to, int len) { int cnt = 0; @@ -458,33 +458,33 @@ pg_big5_mblen(const unsigned char *s) } pg_wchar_tbl pg_wchar_table[] = { - {pg_ascii2wchar_with_len, pg_ascii_mblen, 1}, /* 0; PG_SQL_ASCII */ - {pg_eucjp2wchar_with_len, pg_eucjp_mblen, 3}, /* 1; PG_EUC_JP */ - {pg_euccn2wchar_with_len, pg_euccn_mblen, 3}, /* 2; PG_EUC_CN */ - {pg_euckr2wchar_with_len, pg_euckr_mblen, 3}, /* 3; PG_EUC_KR */ - {pg_euctw2wchar_with_len, pg_euctw_mblen, 3}, /* 4; PG_EUC_TW */ + {pg_ascii2wchar_with_len, pg_ascii_mblen, 1}, /* 0; PG_SQL_ASCII */ + {pg_eucjp2wchar_with_len, pg_eucjp_mblen, 3}, /* 1; PG_EUC_JP */ + {pg_euccn2wchar_with_len, pg_euccn_mblen, 3}, /* 2; PG_EUC_CN */ + {pg_euckr2wchar_with_len, pg_euckr_mblen, 3}, /* 3; PG_EUC_KR */ + {pg_euctw2wchar_with_len, pg_euctw_mblen, 3}, /* 4; PG_EUC_TW */ {pg_utf2wchar_with_len, pg_utf_mblen, 3}, /* 5; PG_UNICODE */ - {pg_mule2wchar_with_len, pg_mule_mblen, 3}, /* 6; PG_MULE_INTERNAL */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 7; PG_LATIN1 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 8; PG_LATIN2 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 9; PG_LATIN3 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 10; PG_LATIN4 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 11; PG_LATIN5 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 12; PG_KOI8 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 13; PG_WIN1251 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 14; PG_ALT */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 15; ISO-8859-5 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 16; ISO-8859-6 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 17; ISO-8859-7 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 18; ISO-8859-8 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 19; ISO-8859-10 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 20; ISO-8859-13 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 21; ISO-8859-14 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 22; ISO-8859-15 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 23; ISO-8859-16 */ - {0, pg_sjis_mblen, 2}, /* 24; PG_SJIS */ - {0, pg_big5_mblen, 2}, /* 25; PG_BIG5 */ - {pg_latin12wchar_with_len, pg_latin1_mblen, 1} /* 26; PG_WIN1250 */ + {pg_mule2wchar_with_len, pg_mule_mblen, 3}, /* 6; PG_MULE_INTERNAL */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 7; PG_LATIN1 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 8; PG_LATIN2 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 9; PG_LATIN3 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 10; PG_LATIN4 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 11; PG_LATIN5 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 12; PG_KOI8 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 13; PG_WIN1251 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 14; PG_ALT */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 15; ISO-8859-5 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 16; ISO-8859-6 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 17; ISO-8859-7 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 18; ISO-8859-8 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 19; ISO-8859-10 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 20; ISO-8859-13 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 21; ISO-8859-14 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 22; ISO-8859-15 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1}, /* 23; ISO-8859-16 */ + {0, pg_sjis_mblen, 2}, /* 24; PG_SJIS */ + {0, pg_big5_mblen, 2}, /* 25; PG_BIG5 */ + {pg_latin12wchar_with_len, pg_latin1_mblen, 1} /* 26; PG_WIN1250 */ }; /* returns the byte length of a word for mule internal code */ @@ -502,9 +502,9 @@ pg_encoding_mblen(int encoding, const unsigned char *mbstr) { Assert(PG_VALID_ENCODING(encoding)); - return( (encoding >= 0 && - encoding < sizeof(pg_wchar_table)/sizeof(pg_wchar_tbl)) ? - ((*pg_wchar_table[encoding].mblen) (mbstr)) : + return ((encoding >= 0 && + encoding < sizeof(pg_wchar_table) / sizeof(pg_wchar_tbl)) ? + ((*pg_wchar_table[encoding].mblen) (mbstr)) : ((*pg_wchar_table[PG_SQL_ASCII].mblen) (mbstr))); } @@ -531,59 +531,62 @@ pg_encoding_max_length(int encoding) char * pg_verifymbstr(const unsigned char *mbstr, int len) { - int l; - int i, j; - static char buf[256]; - int slen = 0; + int l; + int i, + j; + static char buf[256]; + int slen = 0; /* we do not check single byte encodings */ if (pg_database_encoding_max_length() <= 1) - return NULL; + return NULL; while (len > 0 && *mbstr) { /* special UTF-8 check */ if (GetDatabaseEncoding() == PG_UTF8 && - (*mbstr & 0xf8) == 0xf0) + (*mbstr & 0xf8) == 0xf0) { - snprintf(buf, sizeof(buf), "Unicode >= 0x10000 is not supoorted"); - return(buf); + snprintf(buf, sizeof(buf), "Unicode >= 0x10000 is not supoorted"); + return (buf); } - + l = pg_mblen(mbstr); /* multi-byte letter? */ if (l > 1) { - for (i=1;i<l;i++) - { - if (i > len || *(mbstr+i) == '\0' || - /* we assume that every muti-byte letter - * consists of bytes being the 8th bit set - */ - ((*(mbstr+i) & 0x80) == 0)) + for (i = 1; i < l; i++) { - int remains = sizeof(buf); - char *p = buf; - - slen = snprintf(p, remains, "Invalid %s character sequence found (0x", - GetDatabaseEncodingName()); - p += slen; - remains -= slen; - - i = ((*(mbstr+i) & 0x80) == 0)?l:i; - - for (j=0;j<i;j++) - { - slen = snprintf(p, remains, "%02x", - *(mbstr+j)); - p += slen; - remains -= slen; - } - snprintf(p, remains, ")"); - return(buf); + if (i > len || *(mbstr + i) == '\0' || + + /* + * we assume that every muti-byte letter consists of bytes + * being the 8th bit set + */ + ((*(mbstr + i) & 0x80) == 0)) + { + int remains = sizeof(buf); + char *p = buf; + + slen = snprintf(p, remains, "Invalid %s character sequence found (0x", + GetDatabaseEncodingName()); + p += slen; + remains -= slen; + + i = ((*(mbstr + i) & 0x80) == 0) ? l : i; + + for (j = 0; j < i; j++) + { + slen = snprintf(p, remains, "%02x", + *(mbstr + j)); + p += slen; + remains -= slen; + } + snprintf(p, remains, ")"); + return (buf); + } } - } } len -= l; mbstr += l; @@ -599,5 +602,4 @@ pg_database_encoding_max_length(void) { return pg_wchar_table[GetDatabaseEncoding()].maxmblen; } - #endif diff --git a/src/backend/utils/mb/wstrcmp.c b/src/backend/utils/mb/wstrcmp.c index 13255d7c5e..f828c31a3a 100644 --- a/src/backend/utils/mb/wstrcmp.c +++ b/src/backend/utils/mb/wstrcmp.c @@ -43,7 +43,7 @@ pg_char_and_wchar_strcmp(s1, s2) register const char *s1; register const pg_wchar *s2; { - while ((pg_wchar) * s1 == *s2++) + while ((pg_wchar) *s1 == *s2++) if (*s1++ == 0) return 0; return *(const unsigned char *) s1 - *(const pg_wchar *) (s2 - 1); diff --git a/src/backend/utils/misc/database.c b/src/backend/utils/misc/database.c index 218114f7cf..293d9df525 100644 --- a/src/backend/utils/misc/database.c +++ b/src/backend/utils/misc/database.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/misc/Attic/database.c,v 1.48 2001/08/25 18:52:42 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/misc/Attic/database.c,v 1.49 2001/10/25 05:49:51 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -89,7 +89,6 @@ ExpandDatabasePath(const char *dbpath) */ for (cp = buf; *cp; cp++) { - /* * The following characters will not be allowed anywhere in the * database path. (Do not include the slash or '.' here.) diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c index c506e3147c..ff57dc92bb 100644 --- a/src/backend/utils/misc/guc.c +++ b/src/backend/utils/misc/guc.c @@ -4,7 +4,7 @@ * Support for grand unified configuration scheme, including SET * command, configuration file, and command line options. * - * $Header: /cvsroot/pgsql/src/backend/utils/misc/guc.c,v 1.55 2001/09/30 20:16:21 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/misc/guc.c,v 1.56 2001/10/25 05:49:51 momjian Exp $ * * Copyright 2000 by PostgreSQL Global Development Group * Written by Peter Eisentraut <peter_e@gmx.net>. @@ -95,11 +95,11 @@ bool Password_encryption = false; */ enum config_type { - PGC_NONE = 0, - PGC_BOOL, - PGC_INT, - PGC_REAL, - PGC_STRING + PGC_NONE = 0, + PGC_BOOL, + PGC_INT, + PGC_REAL, + PGC_STRING }; @@ -161,7 +161,7 @@ struct config_string const char *boot_default_val; bool (*parse_hook) (const char *proposed); void (*assign_hook) (const char *newval); - char *default_val; + char *default_val; }; @@ -192,92 +192,196 @@ struct config_string static struct config_bool ConfigureNamesBool[] = { - {"enable_seqscan", PGC_USERSET, &enable_seqscan, true, NULL}, - {"enable_indexscan", PGC_USERSET, &enable_indexscan, true, NULL}, - {"enable_tidscan", PGC_USERSET, &enable_tidscan, true, NULL}, - {"enable_sort", PGC_USERSET, &enable_sort, true, NULL}, - {"enable_nestloop", PGC_USERSET, &enable_nestloop, true, NULL}, - {"enable_mergejoin", PGC_USERSET, &enable_mergejoin, true, NULL}, - {"enable_hashjoin", PGC_USERSET, &enable_hashjoin, true, NULL}, - - {"ksqo", PGC_USERSET, &_use_keyset_query_optimizer, false, NULL}, - {"geqo", PGC_USERSET, &enable_geqo, true, NULL}, - - {"tcpip_socket", PGC_POSTMASTER, &NetServer, false, NULL}, - {"ssl", PGC_POSTMASTER, &EnableSSL, false, NULL}, - {"fsync", PGC_SIGHUP, &enableFsync, true, NULL}, - {"silent_mode", PGC_POSTMASTER, &SilentMode, false, NULL}, - - {"log_connections", PGC_BACKEND, &Log_connections, false, NULL}, - {"log_timestamp", PGC_SIGHUP, &Log_timestamp, false, NULL}, - {"log_pid", PGC_SIGHUP, &Log_pid, false, NULL}, + { + "enable_seqscan", PGC_USERSET, &enable_seqscan, true, NULL + } , + { + "enable_indexscan", PGC_USERSET, &enable_indexscan, true, NULL + }, + { + "enable_tidscan", PGC_USERSET, &enable_tidscan, true, NULL + }, + { + "enable_sort", PGC_USERSET, &enable_sort, true, NULL + }, + { + "enable_nestloop", PGC_USERSET, &enable_nestloop, true, NULL + }, + { + "enable_mergejoin", PGC_USERSET, &enable_mergejoin, true, NULL + }, + { + "enable_hashjoin", PGC_USERSET, &enable_hashjoin, true, NULL + }, + + { + "ksqo", PGC_USERSET, &_use_keyset_query_optimizer, false, NULL + }, + { + "geqo", PGC_USERSET, &enable_geqo, true, NULL + }, + + { + "tcpip_socket", PGC_POSTMASTER, &NetServer, false, NULL + }, + { + "ssl", PGC_POSTMASTER, &EnableSSL, false, NULL + }, + { + "fsync", PGC_SIGHUP, &enableFsync, true, NULL + }, + { + "silent_mode", PGC_POSTMASTER, &SilentMode, false, NULL + }, + + { + "log_connections", PGC_BACKEND, &Log_connections, false, NULL + }, + { + "log_timestamp", PGC_SIGHUP, &Log_timestamp, false, NULL + }, + { + "log_pid", PGC_SIGHUP, &Log_pid, false, NULL + }, #ifdef USE_ASSERT_CHECKING - {"debug_assertions", PGC_USERSET, &assert_enabled, true, NULL}, + { + "debug_assertions", PGC_USERSET, &assert_enabled, true, NULL + }, #endif - {"debug_print_query", PGC_USERSET, &Debug_print_query, false, NULL}, - {"debug_print_parse", PGC_USERSET, &Debug_print_parse, false, NULL}, - {"debug_print_rewritten", PGC_USERSET, &Debug_print_rewritten, false, NULL}, - {"debug_print_plan", PGC_USERSET, &Debug_print_plan, false, NULL}, - {"debug_pretty_print", PGC_USERSET, &Debug_pretty_print, false, NULL}, + { + "debug_print_query", PGC_USERSET, &Debug_print_query, false, NULL + }, + { + "debug_print_parse", PGC_USERSET, &Debug_print_parse, false, NULL + }, + { + "debug_print_rewritten", PGC_USERSET, &Debug_print_rewritten, false, NULL + }, + { + "debug_print_plan", PGC_USERSET, &Debug_print_plan, false, NULL + }, + { + "debug_pretty_print", PGC_USERSET, &Debug_pretty_print, false, NULL + }, - {"show_parser_stats", PGC_USERSET, &Show_parser_stats, false, NULL}, - {"show_planner_stats", PGC_USERSET, &Show_planner_stats, false, NULL}, - {"show_executor_stats", PGC_USERSET, &Show_executor_stats, false, NULL}, - {"show_query_stats", PGC_USERSET, &Show_query_stats, false, NULL}, + { + "show_parser_stats", PGC_USERSET, &Show_parser_stats, false, NULL + }, + { + "show_planner_stats", PGC_USERSET, &Show_planner_stats, false, NULL + }, + { + "show_executor_stats", PGC_USERSET, &Show_executor_stats, false, NULL + }, + { + "show_query_stats", PGC_USERSET, &Show_query_stats, false, NULL + }, #ifdef BTREE_BUILD_STATS - {"show_btree_build_stats", PGC_SUSET, &Show_btree_build_stats, false, NULL}, + { + "show_btree_build_stats", PGC_SUSET, &Show_btree_build_stats, false, NULL + }, #endif - {"stats_start_collector", PGC_POSTMASTER, &pgstat_collect_startcollector, true, NULL}, - {"stats_reset_on_server_start", PGC_POSTMASTER, &pgstat_collect_resetonpmstart, true, NULL}, - {"stats_command_string", PGC_SUSET, &pgstat_collect_querystring, false, NULL}, - {"stats_row_level", PGC_SUSET, &pgstat_collect_tuplelevel, false, NULL}, - {"stats_block_level", PGC_SUSET, &pgstat_collect_blocklevel, false, NULL}, + { + "stats_start_collector", PGC_POSTMASTER, &pgstat_collect_startcollector, true, NULL + }, + { + "stats_reset_on_server_start", PGC_POSTMASTER, &pgstat_collect_resetonpmstart, true, NULL + }, + { + "stats_command_string", PGC_SUSET, &pgstat_collect_querystring, false, NULL + }, + { + "stats_row_level", PGC_SUSET, &pgstat_collect_tuplelevel, false, NULL + }, + { + "stats_block_level", PGC_SUSET, &pgstat_collect_blocklevel, false, NULL + }, - {"trace_notify", PGC_USERSET, &Trace_notify, false, NULL}, + { + "trace_notify", PGC_USERSET, &Trace_notify, false, NULL + }, #ifdef LOCK_DEBUG - {"trace_locks", PGC_SUSET, &Trace_locks, false, NULL}, - {"trace_userlocks", PGC_SUSET, &Trace_userlocks, false, NULL}, - {"trace_lwlocks", PGC_SUSET, &Trace_lwlocks, false, NULL}, - {"debug_deadlocks", PGC_SUSET, &Debug_deadlocks, false, NULL}, + { + "trace_locks", PGC_SUSET, &Trace_locks, false, NULL + }, + { + "trace_userlocks", PGC_SUSET, &Trace_userlocks, false, NULL + }, + { + "trace_lwlocks", PGC_SUSET, &Trace_lwlocks, false, NULL + }, + { + "debug_deadlocks", PGC_SUSET, &Debug_deadlocks, false, NULL + }, #endif - {"hostname_lookup", PGC_SIGHUP, &HostnameLookup, false, NULL}, - {"show_source_port", PGC_SIGHUP, &ShowPortNumber, false, NULL}, + { + "hostname_lookup", PGC_SIGHUP, &HostnameLookup, false, NULL + }, + { + "show_source_port", PGC_SIGHUP, &ShowPortNumber, false, NULL + }, - {"sql_inheritance", PGC_USERSET, &SQL_inheritance, true, NULL}, - {"australian_timezones", PGC_USERSET, &Australian_timezones, false, ClearDateCache}, - {"fixbtree", PGC_POSTMASTER, &FixBTree, true, NULL}, - {"password_encryption", PGC_USERSET, &Password_encryption, false, NULL}, - {"transform_null_equals", PGC_USERSET, &Transform_null_equals, false, NULL}, + { + "sql_inheritance", PGC_USERSET, &SQL_inheritance, true, NULL + }, + { + "australian_timezones", PGC_USERSET, &Australian_timezones, false, ClearDateCache + }, + { + "fixbtree", PGC_POSTMASTER, &FixBTree, true, NULL + }, + { + "password_encryption", PGC_USERSET, &Password_encryption, false, NULL + }, + { + "transform_null_equals", PGC_USERSET, &Transform_null_equals, false, NULL + }, - {NULL, 0, NULL, false, NULL} + { + NULL, 0, NULL, false, NULL + } }; static struct config_int ConfigureNamesInt[] = { - {"geqo_threshold", PGC_USERSET, &geqo_rels, - DEFAULT_GEQO_RELS, 2, INT_MAX, NULL, NULL}, - {"geqo_pool_size", PGC_USERSET, &Geqo_pool_size, - DEFAULT_GEQO_POOL_SIZE, 0, MAX_GEQO_POOL_SIZE, NULL, NULL}, - {"geqo_effort", PGC_USERSET, &Geqo_effort, - 1, 1, INT_MAX, NULL, NULL}, - {"geqo_generations", PGC_USERSET, &Geqo_generations, - 0, 0, INT_MAX, NULL, NULL}, - {"geqo_random_seed", PGC_USERSET, &Geqo_random_seed, - -1, INT_MIN, INT_MAX, NULL, NULL}, - - {"deadlock_timeout", PGC_POSTMASTER, &DeadlockTimeout, - 1000, 0, INT_MAX, NULL, NULL}, + { + "geqo_threshold", PGC_USERSET, &geqo_rels, + DEFAULT_GEQO_RELS, 2, INT_MAX, NULL, NULL + } , + { + "geqo_pool_size", PGC_USERSET, &Geqo_pool_size, + DEFAULT_GEQO_POOL_SIZE, 0, MAX_GEQO_POOL_SIZE, NULL, NULL + }, + { + "geqo_effort", PGC_USERSET, &Geqo_effort, + 1, 1, INT_MAX, NULL, NULL + }, + { + "geqo_generations", PGC_USERSET, &Geqo_generations, + 0, 0, INT_MAX, NULL, NULL + }, + { + "geqo_random_seed", PGC_USERSET, &Geqo_random_seed, + -1, INT_MIN, INT_MAX, NULL, NULL + }, + + { + "deadlock_timeout", PGC_POSTMASTER, &DeadlockTimeout, + 1000, 0, INT_MAX, NULL, NULL + }, #ifdef ENABLE_SYSLOG - {"syslog", PGC_SIGHUP, &Use_syslog, - 0, 0, 2, NULL, NULL}, + { + "syslog", PGC_SIGHUP, &Use_syslog, + 0, 0, 2, NULL, NULL + }, #endif /* @@ -285,133 +389,215 @@ static struct config_int * sure the buffers are at least twice the number of backends, so the * constraints here are partially unused. */ - {"max_connections", PGC_POSTMASTER, &MaxBackends, - DEF_MAXBACKENDS, 1, INT_MAX, NULL, NULL}, + { + "max_connections", PGC_POSTMASTER, &MaxBackends, + DEF_MAXBACKENDS, 1, INT_MAX, NULL, NULL + }, - {"shared_buffers", PGC_POSTMASTER, &NBuffers, - DEF_NBUFFERS, 16, INT_MAX, NULL, NULL}, + { + "shared_buffers", PGC_POSTMASTER, &NBuffers, + DEF_NBUFFERS, 16, INT_MAX, NULL, NULL + }, - {"port", PGC_POSTMASTER, &PostPortNumber, - DEF_PGPORT, 1, 65535, NULL, NULL}, + { + "port", PGC_POSTMASTER, &PostPortNumber, + DEF_PGPORT, 1, 65535, NULL, NULL + }, - {"unix_socket_permissions", PGC_POSTMASTER, &Unix_socket_permissions, - 0777, 0000, 0777, NULL, NULL}, + { + "unix_socket_permissions", PGC_POSTMASTER, &Unix_socket_permissions, + 0777, 0000, 0777, NULL, NULL + }, - {"sort_mem", PGC_USERSET, &SortMem, - 512, 4*BLCKSZ/1024, INT_MAX, NULL, NULL}, + { + "sort_mem", PGC_USERSET, &SortMem, + 512, 4 * BLCKSZ / 1024, INT_MAX, NULL, NULL + }, - {"vacuum_mem", PGC_USERSET, &VacuumMem, - 8192, 1024, INT_MAX, NULL, NULL}, + { + "vacuum_mem", PGC_USERSET, &VacuumMem, + 8192, 1024, INT_MAX, NULL, NULL + }, - {"max_files_per_process", PGC_BACKEND, &max_files_per_process, - 1000, 25, INT_MAX, NULL, NULL}, + { + "max_files_per_process", PGC_BACKEND, &max_files_per_process, + 1000, 25, INT_MAX, NULL, NULL + }, - {"debug_level", PGC_USERSET, &DebugLvl, - 0, 0, 16, NULL, NULL}, + { + "debug_level", PGC_USERSET, &DebugLvl, + 0, 0, 16, NULL, NULL + }, #ifdef LOCK_DEBUG - {"trace_lock_oidmin", PGC_SUSET, &Trace_lock_oidmin, - BootstrapObjectIdData, 1, INT_MAX, NULL, NULL}, - {"trace_lock_table", PGC_SUSET, &Trace_lock_table, - 0, 0, INT_MAX, NULL, NULL}, + { + "trace_lock_oidmin", PGC_SUSET, &Trace_lock_oidmin, + BootstrapObjectIdData, 1, INT_MAX, NULL, NULL + }, + { + "trace_lock_table", PGC_SUSET, &Trace_lock_table, + 0, 0, INT_MAX, NULL, NULL + }, #endif - {"max_expr_depth", PGC_USERSET, &max_expr_depth, - DEFAULT_MAX_EXPR_DEPTH, 10, INT_MAX, NULL, NULL}, + { + "max_expr_depth", PGC_USERSET, &max_expr_depth, + DEFAULT_MAX_EXPR_DEPTH, 10, INT_MAX, NULL, NULL + }, - {"max_fsm_relations", PGC_POSTMASTER, &MaxFSMRelations, - 100, 10, INT_MAX, NULL, NULL}, - {"max_fsm_pages", PGC_POSTMASTER, &MaxFSMPages, - 10000, 1000, INT_MAX, NULL, NULL}, + { + "max_fsm_relations", PGC_POSTMASTER, &MaxFSMRelations, + 100, 10, INT_MAX, NULL, NULL + }, + { + "max_fsm_pages", PGC_POSTMASTER, &MaxFSMPages, + 10000, 1000, INT_MAX, NULL, NULL + }, - {"max_locks_per_transaction", PGC_POSTMASTER, &max_locks_per_xact, - 64, 10, INT_MAX, NULL, NULL}, + { + "max_locks_per_transaction", PGC_POSTMASTER, &max_locks_per_xact, + 64, 10, INT_MAX, NULL, NULL + }, - {"authentication_timeout", PGC_SIGHUP, &AuthenticationTimeout, - 60, 1, 600, NULL, NULL}, + { + "authentication_timeout", PGC_SIGHUP, &AuthenticationTimeout, + 60, 1, 600, NULL, NULL + }, - {"pre_auth_delay", PGC_SIGHUP, &PreAuthDelay, - 0, 0, 60, NULL, NULL}, + { + "pre_auth_delay", PGC_SIGHUP, &PreAuthDelay, + 0, 0, 60, NULL, NULL + }, - {"checkpoint_segments", PGC_SIGHUP, &CheckPointSegments, - 3, 1, INT_MAX, NULL, NULL}, + { + "checkpoint_segments", PGC_SIGHUP, &CheckPointSegments, + 3, 1, INT_MAX, NULL, NULL + }, - {"checkpoint_timeout", PGC_SIGHUP, &CheckPointTimeout, - 300, 30, 3600, NULL, NULL}, + { + "checkpoint_timeout", PGC_SIGHUP, &CheckPointTimeout, + 300, 30, 3600, NULL, NULL + }, - {"wal_buffers", PGC_POSTMASTER, &XLOGbuffers, - 8, 4, INT_MAX, NULL, NULL}, + { + "wal_buffers", PGC_POSTMASTER, &XLOGbuffers, + 8, 4, INT_MAX, NULL, NULL + }, - {"wal_files", PGC_SIGHUP, &XLOGfiles, - 0, 0, 64, NULL, NULL}, + { + "wal_files", PGC_SIGHUP, &XLOGfiles, + 0, 0, 64, NULL, NULL + }, - {"wal_debug", PGC_SUSET, &XLOG_DEBUG, - 0, 0, 16, NULL, NULL}, + { + "wal_debug", PGC_SUSET, &XLOG_DEBUG, + 0, 0, 16, NULL, NULL + }, - {"commit_delay", PGC_USERSET, &CommitDelay, - 0, 0, 100000, NULL, NULL}, + { + "commit_delay", PGC_USERSET, &CommitDelay, + 0, 0, 100000, NULL, NULL + }, - {"commit_siblings", PGC_USERSET, &CommitSiblings, - 5, 1, 1000, NULL, NULL}, + { + "commit_siblings", PGC_USERSET, &CommitSiblings, + 5, 1, 1000, NULL, NULL + }, - {NULL, 0, NULL, 0, 0, 0, NULL, NULL} + { + NULL, 0, NULL, 0, 0, 0, NULL, NULL + } }; static struct config_real ConfigureNamesReal[] = { - {"effective_cache_size", PGC_USERSET, &effective_cache_size, - DEFAULT_EFFECTIVE_CACHE_SIZE, 0, DBL_MAX, NULL, NULL}, - {"random_page_cost", PGC_USERSET, &random_page_cost, - DEFAULT_RANDOM_PAGE_COST, 0, DBL_MAX, NULL, NULL}, - {"cpu_tuple_cost", PGC_USERSET, &cpu_tuple_cost, - DEFAULT_CPU_TUPLE_COST, 0, DBL_MAX, NULL, NULL}, - {"cpu_index_tuple_cost", PGC_USERSET, &cpu_index_tuple_cost, - DEFAULT_CPU_INDEX_TUPLE_COST, 0, DBL_MAX, NULL, NULL}, - {"cpu_operator_cost", PGC_USERSET, &cpu_operator_cost, - DEFAULT_CPU_OPERATOR_COST, 0, DBL_MAX, NULL, NULL}, - - {"geqo_selection_bias", PGC_USERSET, &Geqo_selection_bias, - DEFAULT_GEQO_SELECTION_BIAS, MIN_GEQO_SELECTION_BIAS, - MAX_GEQO_SELECTION_BIAS, NULL, NULL}, - - {NULL, 0, NULL, 0.0, 0.0, 0.0, NULL, NULL} + { + "effective_cache_size", PGC_USERSET, &effective_cache_size, + DEFAULT_EFFECTIVE_CACHE_SIZE, 0, DBL_MAX, NULL, NULL + } , + { + "random_page_cost", PGC_USERSET, &random_page_cost, + DEFAULT_RANDOM_PAGE_COST, 0, DBL_MAX, NULL, NULL + }, + { + "cpu_tuple_cost", PGC_USERSET, &cpu_tuple_cost, + DEFAULT_CPU_TUPLE_COST, 0, DBL_MAX, NULL, NULL + }, + { + "cpu_index_tuple_cost", PGC_USERSET, &cpu_index_tuple_cost, + DEFAULT_CPU_INDEX_TUPLE_COST, 0, DBL_MAX, NULL, NULL + }, + { + "cpu_operator_cost", PGC_USERSET, &cpu_operator_cost, + DEFAULT_CPU_OPERATOR_COST, 0, DBL_MAX, NULL, NULL + }, + + { + "geqo_selection_bias", PGC_USERSET, &Geqo_selection_bias, + DEFAULT_GEQO_SELECTION_BIAS, MIN_GEQO_SELECTION_BIAS, + MAX_GEQO_SELECTION_BIAS, NULL, NULL + }, + + { + NULL, 0, NULL, 0.0, 0.0, 0.0, NULL, NULL + } }; static struct config_string ConfigureNamesString[] = { - {"default_transaction_isolation", PGC_USERSET, &default_iso_level_string, - "read committed", check_defaultxactisolevel, assign_defaultxactisolevel}, + { + "default_transaction_isolation", PGC_USERSET, &default_iso_level_string, + "read committed", check_defaultxactisolevel, assign_defaultxactisolevel + } , - {"dynamic_library_path", PGC_SUSET, &Dynamic_library_path, - "$libdir", NULL, NULL}, + { + "dynamic_library_path", PGC_SUSET, &Dynamic_library_path, + "$libdir", NULL, NULL + }, - {"krb_server_keyfile", PGC_POSTMASTER, &pg_krb_server_keyfile, - PG_KRB_SRVTAB, NULL, NULL}, + { + "krb_server_keyfile", PGC_POSTMASTER, &pg_krb_server_keyfile, + PG_KRB_SRVTAB, NULL, NULL + }, #ifdef ENABLE_SYSLOG - {"syslog_facility", PGC_POSTMASTER, &Syslog_facility, - "LOCAL0", check_facility, NULL}, - {"syslog_ident", PGC_POSTMASTER, &Syslog_ident, - "postgres", NULL, NULL}, + { + "syslog_facility", PGC_POSTMASTER, &Syslog_facility, + "LOCAL0", check_facility, NULL + }, + { + "syslog_ident", PGC_POSTMASTER, &Syslog_ident, + "postgres", NULL, NULL + }, #endif - {"unix_socket_group", PGC_POSTMASTER, &Unix_socket_group, - "", NULL, NULL}, + { + "unix_socket_group", PGC_POSTMASTER, &Unix_socket_group, + "", NULL, NULL + }, - {"unix_socket_directory", PGC_POSTMASTER, &UnixSocketDir, - "", NULL, NULL}, + { + "unix_socket_directory", PGC_POSTMASTER, &UnixSocketDir, + "", NULL, NULL + }, - {"virtual_host", PGC_POSTMASTER, &VirtualHost, - "", NULL, NULL}, + { + "virtual_host", PGC_POSTMASTER, &VirtualHost, + "", NULL, NULL + }, - {"wal_sync_method", PGC_SIGHUP, &XLOG_sync_method, - XLOG_sync_method_default, check_xlog_sync_method, - assign_xlog_sync_method}, + { + "wal_sync_method", PGC_SIGHUP, &XLOG_sync_method, + XLOG_sync_method_default, check_xlog_sync_method, + assign_xlog_sync_method + }, - {NULL, 0, NULL, NULL, NULL, NULL} + { + NULL, 0, NULL, NULL, NULL, NULL + } }; /******** end of options list ********/ @@ -628,10 +814,10 @@ parse_int(const char *value, int *result) val = strtol(value, &endptr, 0); if (endptr == value || *endptr != '\0' || errno == ERANGE #ifdef HAVE_LONG_INT_64 - /* if long > 32 bits, check for overflow of int4 */ + /* if long > 32 bits, check for overflow of int4 */ || val != (long) ((int32) val) #endif - ) + ) return false; if (result) *result = (int) val; @@ -715,23 +901,24 @@ set_config_option(const char *name, const char *value, case PGC_SIGHUP: if (context != PGC_SIGHUP && context != PGC_POSTMASTER) elog(ERROR, "'%s' cannot be changed now", name); + /* - * Hmm, the idea of the SIGHUP context is "ought to be global, but - * can be changed after postmaster start". But there's nothing - * that prevents a crafty administrator from sending SIGHUP - * signals to individual backends only. + * Hmm, the idea of the SIGHUP context is "ought to be global, + * but can be changed after postmaster start". But there's + * nothing that prevents a crafty administrator from sending + * SIGHUP signals to individual backends only. */ break; case PGC_BACKEND: if (context == PGC_SIGHUP) { /* - * If a PGC_BACKEND parameter is changed in the config file, - * we want to accept the new value in the postmaster (whence - * it will propagate to subsequently-started backends), but - * ignore it in existing backends. This is a tad klugy, but - * necessary because we don't re-read the config file during - * backend start. + * If a PGC_BACKEND parameter is changed in the config + * file, we want to accept the new value in the postmaster + * (whence it will propagate to subsequently-started + * backends), but ignore it in existing backends. This is + * a tad klugy, but necessary because we don't re-read the + * config file during backend start. */ if (IsUnderPostmaster) return true; @@ -903,7 +1090,8 @@ set_config_option(const char *name, const char *value, if (makeDefault) { str = strdup(value); - if (str == NULL) { + if (str == NULL) + { elog(elevel, "out of memory"); return false; } @@ -1006,10 +1194,10 @@ GetConfigOption(const char *name) } static void -_ShowOption(enum config_type opttype, struct config_generic *record) +_ShowOption(enum config_type opttype, struct config_generic * record) { - char buffer[256]; - char *val; + char buffer[256]; + char *val; switch (opttype) { @@ -1046,16 +1234,16 @@ ShowAllGUCConfig(void) int i; for (i = 0; ConfigureNamesBool[i].name; i++) - _ShowOption(PGC_BOOL, (struct config_generic *)&ConfigureNamesBool[i]); + _ShowOption(PGC_BOOL, (struct config_generic *) & ConfigureNamesBool[i]); for (i = 0; ConfigureNamesInt[i].name; i++) - _ShowOption(PGC_INT, (struct config_generic *)&ConfigureNamesInt[i]); + _ShowOption(PGC_INT, (struct config_generic *) & ConfigureNamesInt[i]); for (i = 0; ConfigureNamesReal[i].name; i++) - _ShowOption(PGC_REAL, (struct config_generic *)&ConfigureNamesReal[i]); + _ShowOption(PGC_REAL, (struct config_generic *) & ConfigureNamesReal[i]); for (i = 0; ConfigureNamesString[i].name; i++) - _ShowOption(PGC_STRING, (struct config_generic *)&ConfigureNamesString[i]); + _ShowOption(PGC_STRING, (struct config_generic *) & ConfigureNamesString[i]); } @@ -1132,7 +1320,6 @@ check_facility(const char *facility) return true; return false; } - #endif diff --git a/src/backend/utils/misc/ps_status.c b/src/backend/utils/misc/ps_status.c index 9441aa0056..65d2e10cdb 100644 --- a/src/backend/utils/misc/ps_status.c +++ b/src/backend/utils/misc/ps_status.c @@ -5,7 +5,7 @@ * to contain some useful information. Mechanism differs wildly across * platforms. * - * $Header: /cvsroot/pgsql/src/backend/utils/misc/ps_status.c,v 1.7 2001/10/22 19:41:38 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/misc/ps_status.c,v 1.8 2001/10/25 05:49:51 momjian Exp $ * * Copyright 2000 by PostgreSQL Global Development Group * various details abducted from various places @@ -83,7 +83,6 @@ static const size_t ps_buffer_size = PS_BUFFER_SIZE; #else /* PS_USE_CLOBBER_ARGV */ static char *ps_buffer; /* will point to argv area */ static size_t ps_buffer_size; /* space determined at run time */ - #endif /* PS_USE_CLOBBER_ARGV */ static size_t ps_buffer_fixed_size; /* size of the constant prefix */ @@ -97,7 +96,7 @@ static char **save_argv; * Call this early in startup to save the original argc/argv values. * * argv[] will not be overwritten by this routine, but may be overwritten - * during init_ps_display. Also, the physical location of the environment + * during init_ps_display. Also, the physical location of the environment * strings may be moved, so this should be called before any code that * might try to hang onto a getenv() result. */ @@ -108,6 +107,7 @@ save_ps_display_args(int argc, char *argv[]) save_argv = argv; #ifdef PS_USE_CLOBBER_ARGV + /* * If we're going to overwrite the argv area, count the available * space. Also move the environment to make additional room. @@ -126,7 +126,7 @@ save_ps_display_args(int argc, char *argv[]) end_of_area = argv[i] + strlen(argv[i]); } - if (end_of_area == NULL) /* probably can't happen? */ + if (end_of_area == NULL)/* probably can't happen? */ { ps_buffer = NULL; ps_buffer_size = 0; @@ -159,7 +159,7 @@ save_ps_display_args(int argc, char *argv[]) /* * Call this once during subprocess startup to set the identification - * values. At this point, the original argv[] array may be overwritten. + * values. At this point, the original argv[] array may be overwritten. */ void init_ps_display(const char *username, const char *dbname, @@ -201,6 +201,7 @@ init_ps_display(const char *username, const char *dbname, */ #ifdef PS_USE_SETPROCTITLE + /* * apparently setproctitle() already adds a `progname:' prefix to the * ps line @@ -273,7 +274,6 @@ set_ps_display(const char *activity) *cp = PS_PADDING; } #endif /* PS_USE_CLOBBER_ARGV */ - #endif /* not PS_USE_NONE */ } diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index f66e021ad5..24fd0d1793 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.41 2001/03/22 04:00:07 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/aset.c,v 1.42 2001/10/25 05:49:51 momjian Exp $ * * NOTE: * This is a new (Feb. 05, 1999) implementation of the allocation set @@ -207,7 +207,6 @@ static void AllocSetDelete(MemoryContext context); #ifdef MEMORY_CONTEXT_CHECKING static void AllocSetCheck(MemoryContext context); - #endif static void AllocSetStats(MemoryContext context); @@ -359,7 +358,6 @@ AllocSetContextCreate(MemoryContext parent, static void AllocSetInit(MemoryContext context) { - /* * Since MemoryContextCreate already zeroed the context node, we don't * have to do anything here: it's already OK. @@ -581,7 +579,6 @@ AllocSetAlloc(MemoryContext context, Size size) if (availspace < (chunk_size + ALLOC_CHUNKHDRSZ)) { - /* * The existing active (top) block does not have enough room * for the requested allocation, but it might still have a @@ -745,7 +742,6 @@ AllocSetFree(MemoryContext context, void *pointer) if (chunk->size > ALLOC_CHUNK_LIMIT) { - /* * Big chunks are certain to have been allocated as single-chunk * blocks. Find the containing block and return it to malloc(). @@ -837,7 +833,6 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) if (oldsize > ALLOC_CHUNK_LIMIT) { - /* * The chunk must been allocated as a single-chunk block. Find * the containing block and use realloc() to make it bigger with @@ -893,7 +888,6 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } else { - /* * Small-chunk case. If the chunk is the last one in its block, * there might be enough free space after it that we can just @@ -1088,5 +1082,4 @@ AllocSetCheck(MemoryContext context) name, block); } } - #endif /* MEMORY_CONTEXT_CHECKING */ diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 402e4010f7..59ecb6f3fc 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.28 2001/03/22 04:00:08 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/mcxt.c,v 1.29 2001/10/25 05:49:51 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -263,7 +263,6 @@ MemoryContextCheck(MemoryContext context) for (child = context->firstchild; child != NULL; child = child->nextchild) MemoryContextCheck(child); } - #endif /* diff --git a/src/backend/utils/mmgr/portalmem.c b/src/backend/utils/mmgr/portalmem.c index bd48394b8c..25171ea7be 100644 --- a/src/backend/utils/mmgr/portalmem.c +++ b/src/backend/utils/mmgr/portalmem.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/portalmem.c,v 1.43 2001/10/05 17:28:13 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/portalmem.c,v 1.44 2001/10/25 05:49:51 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -257,7 +257,7 @@ PortalDrop(Portal portal) * * XXX This assumes that portals can be deleted in a random order, ie, * no portal has a reference to any other (at least not one that will be - * exercised during deletion). I think this is okay at the moment, but + * exercised during deletion). I think this is okay at the moment, but * we've had bugs of that ilk in the past. Keep a close eye on cursor * references... */ @@ -270,7 +270,5 @@ AtEOXact_portals(void) hash_seq_init(&status, PortalHashTable); while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL) - { PortalDrop(hentry->portal); - } } diff --git a/src/backend/utils/sort/logtape.c b/src/backend/utils/sort/logtape.c index 30d1f0f186..6b27e5de4d 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.6 2001/01/24 19:43:17 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/sort/logtape.c,v 1.7 2001/10/25 05:49:51 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -224,7 +224,6 @@ ltsReadBlock(LogicalTapeSet *lts, long blocknum, void *buffer) static long ltsGetFreeBlock(LogicalTapeSet *lts) { - /* * If there are multiple free blocks, we select the one appearing last * in freeBlocks[]. If there are none, assign the next block at the @@ -286,7 +285,6 @@ ltsRecordBlockNum(LogicalTapeSet *lts, IndirectBlock *indirect, { if (indirect->nextSlot >= BLOCKS_PER_INDIR_BLOCK) { - /* * This indirect block is full, so dump it out and recursively * save its address in the next indirection level. Create a new @@ -365,7 +363,6 @@ static long ltsRewindFrozenIndirectBlock(LogicalTapeSet *lts, IndirectBlock *indirect) { - /* * If block is not topmost, recurse to obtain address of first block * in this hierarchy level. Read that one in. @@ -612,7 +609,6 @@ LogicalTapeRewind(LogicalTapeSet *lts, int tapenum, bool forWrite) { if (lt->writing) { - /* * Completion of a write phase. Flush last partial data * block, flush any partial indirect blocks, rewind for normal @@ -626,7 +622,6 @@ LogicalTapeRewind(LogicalTapeSet *lts, int tapenum, bool forWrite) } else { - /* * This is only OK if tape is frozen; we rewind for (another) * read pass. @@ -649,7 +644,6 @@ LogicalTapeRewind(LogicalTapeSet *lts, int tapenum, bool forWrite) } else { - /* * Completion of a read phase. Rewind and prepare for write. * diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c index f4e2faaa2b..5cf8e3ad1d 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.18 2001/08/21 16:36:05 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplesort.c,v 1.19 2001/10/25 05:49:52 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -104,12 +104,13 @@ */ typedef enum { - TSS_INITIAL, /* Loading tuples; still within memory + TSS_INITIAL, /* Loading tuples; still within memory * limit */ - TSS_BUILDRUNS, /* Loading tuples; writing to tape */ - TSS_SORTEDINMEM, /* Sort completed entirely in memory */ - TSS_SORTEDONTAPE, /* Sort completed, final run is on tape */ - TSS_FINALMERGE /* Performing final merge on-the-fly */ + TSS_BUILDRUNS, /* Loading tuples; writing to tape */ + TSS_SORTEDINMEM,/* Sort completed entirely in memory */ + TSS_SORTEDONTAPE, /* Sort completed, final run is on + * tape */ + TSS_FINALMERGE /* Performing final merge on-the-fly */ } TupSortStatus; /* @@ -135,10 +136,9 @@ struct Tuplesortstate * kind of tuple we are sorting from the routines that don't need to * know it. They are set up by the tuplesort_begin_xxx routines. * - * Function to compare two tuples; result is per qsort() convention, - * ie: + * Function to compare two tuples; result is per qsort() convention, ie: * - * <0, 0, >0 according as a<b, a=b, a>b. + * <0, 0, >0 according as a<b, a=b, a>b. */ int (*comparetup) (Tuplesortstate *state, const void *a, const void *b); @@ -584,7 +584,10 @@ tuplesort_end(Tuplesortstate *state) if (state->memtupindex) pfree(state->memtupindex); - /* this stuff might better belong in a variant-specific shutdown routine */ + /* + * this stuff might better belong in a variant-specific shutdown + * routine + */ if (state->scanKeys) pfree(state->scanKeys); if (state->sortFnKinds) @@ -601,7 +604,6 @@ tuplesort_end(Tuplesortstate *state) void tuplesort_puttuple(Tuplesortstate *state, void *tuple) { - /* * Copy the given tuple into memory we control, and decrease availMem. * Then call the code shared with the Datum case. @@ -660,7 +662,7 @@ puttuple_common(Tuplesortstate *state, void *tuple) { switch (state->status) { - case TSS_INITIAL: + case TSS_INITIAL: /* * Save the copied tuple into the unsorted array. @@ -732,7 +734,7 @@ tuplesort_performsort(Tuplesortstate *state) { switch (state->status) { - case TSS_INITIAL: + case TSS_INITIAL: /* * We were able to accumulate all the tuples within the @@ -843,7 +845,6 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward, */ if (state->eof_reached) { - /* * Seek position is pointing just past the zero tuplen at * the end of file; back up to fetch last tuple's ending @@ -858,7 +859,6 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward, } else { - /* * Back up and fetch previously-returned tuple's ending * length word. If seek fails, assume we are at start of @@ -877,7 +877,6 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward, state->result_tape, tuplen + 2 * sizeof(unsigned int))) { - /* * If that fails, presumably the prev tuple is the * first in the file. Back up so that it becomes next @@ -928,7 +927,6 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward, tuplesort_heap_siftup(state, false); if ((tupIndex = state->mergenext[srcTape]) == 0) { - /* * out of preloaded data on this tape, try to read * more @@ -1457,7 +1455,6 @@ dumptuples(Tuplesortstate *state, bool alltuples) while (alltuples || (LACKMEM(state) && state->memtupcount > 1)) { - /* * Dump the heap's frontmost entry, and sift up to remove it from * the heap. @@ -2037,10 +2034,10 @@ tuplesize_datum(Tuplesortstate *state, void *tup) /* * This routine selects an appropriate sorting function to implement - * a sort operator as efficiently as possible. The straightforward + * a sort operator as efficiently as possible. The straightforward * method is to use the operator's implementation proc --- ie, "<" - * comparison. However, that way often requires two calls of the function - * per comparison. If we can find a btree three-way comparator function + * comparison. However, that way often requires two calls of the function + * per comparison. If we can find a btree three-way comparator function * associated with the operator, we can use it to do the comparisons * more efficiently. We also support the possibility that the operator * is ">" (descending sort), in which case we have to reverse the output @@ -2061,12 +2058,12 @@ SelectSortFunction(Oid sortOperator, Oid opclass = InvalidOid; /* - * Scan 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. + * Scan 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. */ ScanKeyEntryInitialize(&skey[0], 0x0, Anum_pg_amop_amopopr, @@ -2109,6 +2106,7 @@ SelectSortFunction(Oid sortOperator, if (HeapTupleIsValid(tuple)) { Form_pg_amproc aform = (Form_pg_amproc) GETSTRUCT(tuple); + *sortFunction = aform->amproc; ReleaseSysCache(tuple); Assert(RegProcedureIsValid(*sortFunction)); @@ -2119,7 +2117,8 @@ SelectSortFunction(Oid sortOperator, /* * Can't find a comparator, so use the operator as-is. Decide whether * it is forward or reverse sort by looking at its name (grotty, but - * this only matters for deciding which end NULLs should get sorted to). + * this only matters for deciding which end NULLs should get sorted + * to). */ tuple = SearchSysCache(OPEROID, ObjectIdGetDatum(sortOperator), @@ -2202,8 +2201,8 @@ ApplySortFunction(FmgrInfo *sortFunction, SortFunctionKind kind, } if (isNull2) return 1; - return - DatumGetInt32(FunctionCall2(sortFunction, - datum1, datum2)); + return -DatumGetInt32(FunctionCall2(sortFunction, + datum1, datum2)); default: elog(ERROR, "Invalid SortFunctionKind %d", (int) kind); diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c index 7621e57297..6e241c480f 100644 --- a/src/backend/utils/sort/tuplestore.c +++ b/src/backend/utils/sort/tuplestore.c @@ -26,7 +26,7 @@ * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplestore.c,v 1.3 2001/03/22 04:00:10 momjian Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplestore.c,v 1.4 2001/10/25 05:49:52 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -43,11 +43,11 @@ */ typedef enum { - TSS_INITIAL, /* Loading tuples; still within memory + TSS_INITIAL, /* Loading tuples; still within memory * limit */ - TSS_WRITEFILE, /* Loading tuples; writing to temp file */ - TSS_READMEM, /* Reading tuples; entirely in memory */ - TSS_READFILE /* Reading tuples from temp file */ + TSS_WRITEFILE, /* Loading tuples; writing to temp file */ + TSS_READMEM, /* Reading tuples; entirely in memory */ + TSS_READFILE /* Reading tuples from temp file */ } TupStoreStatus; /* @@ -271,7 +271,6 @@ tuplestore_end(Tuplestorestate *state) void tuplestore_puttuple(Tuplestorestate *state, void *tuple) { - /* * Copy the tuple. (Must do this even in WRITEFILE case.) */ @@ -324,7 +323,7 @@ tuplestore_donestoring(Tuplestorestate *state) { switch (state->status) { - case TSS_INITIAL: + case TSS_INITIAL: /* * We were able to accumulate all the tuples within the @@ -432,7 +431,6 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward, */ if (state->eof_reached) { - /* * Seek position is pointing just past the zero tuplen at * the end of file; back up to fetch last tuple's ending @@ -447,7 +445,6 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward, } else { - /* * Back up and fetch previously-returned tuple's ending * length word. If seek fails, assume we are at start of @@ -466,7 +463,6 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward, -(long) (tuplen + 2 * sizeof(unsigned int)), SEEK_CUR) != 0) { - /* * If that fails, presumably the prev tuple is the * first in the file. Back up so that it becomes next diff --git a/src/backend/utils/time/tqual.c b/src/backend/utils/time/tqual.c index f0536d7611..194959f6cc 100644 --- a/src/backend/utils/time/tqual.c +++ b/src/backend/utils/time/tqual.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/backend/utils/time/tqual.c,v 1.42 2001/08/26 16:56:00 tgl Exp $ + * $Header: /cvsroot/pgsql/src/backend/utils/time/tqual.c,v 1.43 2001/10/25 05:49:52 momjian Exp $ * *------------------------------------------------------------------------- */ @@ -324,7 +324,7 @@ HeapTupleSatisfiesUpdate(HeapTuple tuple) { if (th->t_infomask & HEAP_MARKED_FOR_UPDATE) return HeapTupleMayBeUpdated; - return HeapTupleUpdated;/* updated by other */ + return HeapTupleUpdated; /* updated by other */ } if (TransactionIdIsCurrentTransactionId(th->t_xmax)) @@ -374,7 +374,6 @@ HeapTupleSatisfiesDirty(HeapTupleHeader tuple) if (tuple->t_infomask & HEAP_MOVED_OFF) { - /* * HeapTupleSatisfiesDirty is used by unique btree-s and so * may be used while vacuuming. @@ -592,7 +591,7 @@ HeapTupleSatisfiesSnapshot(HeapTupleHeader tuple, Snapshot snapshot) * HeapTupleSatisfiesVacuum - determine tuple status for VACUUM and related * operations * - * OldestXmin is a cutoff XID (obtained from GetOldestXmin()). Tuples + * OldestXmin is a cutoff XID (obtained from GetOldestXmin()). Tuples * deleted by XIDs >= OldestXmin are deemed "recently dead"; they might * still be visible to some open transaction, so we can't remove them, * even if we see that the deleting transaction has committed. @@ -614,9 +613,9 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) * NOTE: must check TransactionIdIsInProgress (which looks in PROC array) * before TransactionIdDidCommit/TransactionIdDidAbort (which look in * pg_clog). Otherwise we have a race condition where we might decide - * that a just-committed transaction crashed, because none of the tests - * succeed. xact.c is careful to record commit/abort in pg_clog before - * it unsets MyProc->xid in PROC array. + * that a just-committed transaction crashed, because none of the + * tests succeed. xact.c is careful to record commit/abort in pg_clog + * before it unsets MyProc->xid in PROC array. */ if (!(tuple->t_infomask & HEAP_XMIN_COMMITTED)) { @@ -655,8 +654,8 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) else { /* - * Not in Progress, Not Committed, Not Aborted - - * so it's from crashed process. - vadim 11/26/96 + * Not in Progress, Not Committed, Not Aborted - so it's from + * crashed process. - vadim 11/26/96 */ tuple->t_infomask |= HEAP_XMIN_INVALID; return HEAPTUPLE_DEAD; @@ -666,7 +665,7 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) } /* - * Okay, the inserter committed, so it was good at some point. Now + * Okay, the inserter committed, so it was good at some point. Now * what about the deleting transaction? */ if (tuple->t_infomask & HEAP_XMAX_INVALID) @@ -686,8 +685,8 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) else { /* - * Not in Progress, Not Committed, Not Aborted - - * so it's from crashed process. - vadim 06/02/97 + * Not in Progress, Not Committed, Not Aborted - so it's from + * crashed process. - vadim 06/02/97 */ tuple->t_infomask |= HEAP_XMAX_INVALID; return HEAPTUPLE_LIVE; @@ -708,7 +707,10 @@ HeapTupleSatisfiesVacuum(HeapTupleHeader tuple, TransactionId OldestXmin) if (TransactionIdEquals(tuple->t_xmin, tuple->t_xmax)) { - /* inserter also deleted it, so it was never visible to anyone else */ + /* + * inserter also deleted it, so it was never visible to anyone + * else + */ return HEAPTUPLE_DEAD; } |