diff options
author | Bruce Momjian | 2001-10-25 05:50:21 +0000 |
---|---|---|
committer | Bruce Momjian | 2001-10-25 05:50:21 +0000 |
commit | b81844b1738c584d92330a5ccd0fbd8b603d2886 (patch) | |
tree | 4fae0d4cd26048177fc5cd1a2dd91abc99ba0f99 /src/backend/commands | |
parent | 59da2105d8e6d95345b3b942a2e2aba8cead4838 (diff) |
pgindent run on all C files. Java run to follow. initdb/regression
tests pass.
Diffstat (limited to 'src/backend/commands')
23 files changed, 1247 insertions, 1172 deletions
diff --git a/src/backend/commands/_deadcode/recipe.c b/src/backend/commands/_deadcode/recipe.c index 15a1d0a5647..3cc26fa51c6 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 7ac908fa7cb..11dafaefa7e 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 2b8b3b6345c..3a5170e86ae 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 e7a7d5c0666..41c863a5ba6 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 6333efafc64..3195f5fc0b8 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 7d5d3e6cbdb..469b4cd1ce4 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 5297f7481d6..4d1792a1d36 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 14e591288a2..647cb55b7e7 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 ce7ea9fd6d3..7f1e288fab9 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 1c17714eb45..0c1e7268d7f 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 88b01fd91e9..92baacb72d5 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 02b7b0c04b3..334094fd471 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 91282ffc3f6..c14d4ce3e5a 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 a02f399f12e..f6eb6471c0a 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 4e46f7f9d20..37a338ff961 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 8d4b05567f3..c65cfcc5519 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 80e17caaa80..10954912e7b 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 de98b333469..e108840d780 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 518b9942d17..a3103e7209c 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 991af5d5f35..fa5770b0e8d 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 38405f6c6cb..8431dcdb0f4 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 9da67760745..4ed17e8fbe6 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 2bb9fd75a73..9d1254a4cb0 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. |