1
0
mirror of https://github.com/postgres/postgres.git synced 2025-04-20 00:42:27 +03:00

Reimplement the linked list data structure used throughout the backend.

In the past, we used a 'Lispy' linked list implementation: a "list" was
merely a pointer to the head node of the list. The problem with that
design is that it makes lappend() and length() linear time. This patch
fixes that problem (and others) by maintaining a count of the list
length and a pointer to the tail node along with each head node pointer.
A "list" is now a pointer to a structure containing some meta-data
about the list; the head and tail pointers in that structure refer
to ListCell structures that maintain the actual linked list of nodes.

The function names of the list API have also been changed to, I hope,
be more logically consistent. By default, the old function names are
still available; they will be disabled-by-default once the rest of
the tree has been updated to use the new API names.
This commit is contained in:
Neil Conway 2004-05-26 04:41:50 +00:00
parent 18d0d10563
commit d0b4399d81
125 changed files with 3639 additions and 3038 deletions

View File

@ -9,7 +9,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/access/common/printtup.c,v 1.80 2004/01/07 18:56:23 neilc Exp $ * $PostgreSQL: pgsql/src/backend/access/common/printtup.c,v 1.81 2004/05/26 04:41:03 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -138,7 +138,7 @@ printtup_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
List *targetlist; List *targetlist;
if (portal->strategy == PORTAL_ONE_SELECT) if (portal->strategy == PORTAL_ONE_SELECT)
targetlist = ((Query *) lfirst(portal->parseTrees))->targetList; targetlist = ((Query *) linitial(portal->parseTrees))->targetList;
else else
targetlist = NIL; targetlist = NIL;
@ -176,6 +176,7 @@ SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats)
int proto = PG_PROTOCOL_MAJOR(FrontendProtocol); int proto = PG_PROTOCOL_MAJOR(FrontendProtocol);
int i; int i;
StringInfoData buf; StringInfoData buf;
ListCell *tlist_item = list_head(targetlist);
pq_beginmessage(&buf, 'T'); /* tuple descriptor message type */ pq_beginmessage(&buf, 'T'); /* tuple descriptor message type */
pq_sendint(&buf, natts, 2); /* # of attrs in tuples */ pq_sendint(&buf, natts, 2); /* # of attrs in tuples */
@ -191,16 +192,16 @@ SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats)
if (proto >= 3) if (proto >= 3)
{ {
/* Do we have a non-resjunk tlist item? */ /* Do we have a non-resjunk tlist item? */
while (targetlist && while (tlist_item &&
((TargetEntry *) lfirst(targetlist))->resdom->resjunk) ((TargetEntry *) lfirst(tlist_item))->resdom->resjunk)
targetlist = lnext(targetlist); tlist_item = lnext(tlist_item);
if (targetlist) if (tlist_item)
{ {
Resdom *res = ((TargetEntry *) lfirst(targetlist))->resdom; Resdom *res = ((TargetEntry *) lfirst(tlist_item))->resdom;
pq_sendint(&buf, res->resorigtbl, 4); pq_sendint(&buf, res->resorigtbl, 4);
pq_sendint(&buf, res->resorigcol, 2); pq_sendint(&buf, res->resorigcol, 2);
targetlist = lnext(targetlist); tlist_item = lnext(tlist_item);
} }
else else
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/access/common/tupdesc.c,v 1.102 2004/04/01 21:28:43 tgl Exp $ * $PostgreSQL: pgsql/src/backend/access/common/tupdesc.c,v 1.103 2004/05/26 04:41:03 neilc Exp $
* *
* NOTES * NOTES
* some of the executor utility code such as "ExecTypeFromTL" should be * some of the executor utility code such as "ExecTypeFromTL" should be
@ -472,7 +472,7 @@ BuildDescForRelation(List *schema)
{ {
int natts; int natts;
AttrNumber attnum; AttrNumber attnum;
List *p; ListCell *l;
TupleDesc desc; TupleDesc desc;
AttrDefault *attrdef = NULL; AttrDefault *attrdef = NULL;
TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr)); TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
@ -490,9 +490,9 @@ BuildDescForRelation(List *schema)
attnum = 0; attnum = 0;
foreach(p, schema) foreach(l, schema)
{ {
ColumnDef *entry = lfirst(p); ColumnDef *entry = lfirst(l);
/* /*
* for each entry in the list, get the name and type information * for each entry in the list, get the name and type information
@ -661,7 +661,7 @@ TypeGetTupleDesc(Oid typeoid, List *colaliases)
errmsg("number of aliases does not match number of columns"))); errmsg("number of aliases does not match number of columns")));
/* OK, get the column alias */ /* OK, get the column alias */
attname = strVal(lfirst(colaliases)); attname = strVal(linitial(colaliases));
tupdesc = CreateTemplateTupleDesc(1, false); tupdesc = CreateTemplateTupleDesc(1, false);
TupleDescInitEntry(tupdesc, TupleDescInitEntry(tupdesc,

View File

@ -8,7 +8,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/access/nbtree/nbtxlog.c,v 1.10 2004/01/07 18:56:24 neilc Exp $ * $PostgreSQL: pgsql/src/backend/access/nbtree/nbtxlog.c,v 1.11 2004/05/26 04:41:05 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -59,7 +59,7 @@ forget_matching_split(Relation reln, RelFileNode node,
Page page; Page page;
BTItem btitem; BTItem btitem;
BlockNumber rightblk; BlockNumber rightblk;
List *l; ListCell *l;
/* Get downlink TID from page */ /* Get downlink TID from page */
buffer = XLogReadBuffer(false, reln, insertblk); buffer = XLogReadBuffer(false, reln, insertblk);
@ -964,7 +964,7 @@ btree_xlog_startup(void)
void void
btree_xlog_cleanup(void) btree_xlog_cleanup(void)
{ {
List *l; ListCell *l;
foreach(l, incomplete_splits) foreach(l, incomplete_splits)
{ {

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/bootstrap/bootparse.y,v 1.67 2004/05/21 05:07:56 tgl Exp $ * $PostgreSQL: pgsql/src/backend/bootstrap/bootparse.y,v 1.68 2004/05/26 04:41:05 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -271,7 +271,7 @@ Boot_BuildIndsStmt:
boot_index_params: boot_index_params:
boot_index_params COMMA boot_index_param { $$ = lappend($1, $3); } boot_index_params COMMA boot_index_param { $$ = lappend($1, $3); }
| boot_index_param { $$ = makeList1($1); } | boot_index_param { $$ = list_make1($1); }
; ;
boot_index_param: boot_index_param:
@ -280,7 +280,7 @@ boot_index_param:
IndexElem *n = makeNode(IndexElem); IndexElem *n = makeNode(IndexElem);
n->name = LexIDStr($1); n->name = LexIDStr($1);
n->expr = NULL; n->expr = NULL;
n->opclass = makeList1(makeString(LexIDStr($2))); n->opclass = list_make1(makeString(LexIDStr($2)));
$$ = n; $$ = n;
} }
; ;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/aclchk.c,v 1.98 2004/05/11 17:36:12 tgl Exp $ * $PostgreSQL: pgsql/src/backend/catalog/aclchk.c,v 1.99 2004/05/26 04:41:06 neilc Exp $
* *
* NOTES * NOTES
* See acl.h. * See acl.h.
@ -110,7 +110,7 @@ merge_acl_with_grant(Acl *old_acl, bool is_grant,
AclId grantor_uid, AclId owner_uid) AclId grantor_uid, AclId owner_uid)
{ {
unsigned modechg; unsigned modechg;
List *j; ListCell *j;
Acl *new_acl; Acl *new_acl;
modechg = is_grant ? ACL_MODECHG_ADD : ACL_MODECHG_DEL; modechg = is_grant ? ACL_MODECHG_ADD : ACL_MODECHG_DEL;
@ -221,16 +221,16 @@ static void
ExecuteGrantStmt_Relation(GrantStmt *stmt) ExecuteGrantStmt_Relation(GrantStmt *stmt)
{ {
AclMode privileges; AclMode privileges;
List *i; ListCell *i;
if (lfirsti(stmt->privileges) == ACL_ALL_RIGHTS) if (linitial_int(stmt->privileges) == ACL_ALL_RIGHTS)
privileges = ACL_ALL_RIGHTS_RELATION; privileges = ACL_ALL_RIGHTS_RELATION;
else else
{ {
privileges = ACL_NO_RIGHTS; privileges = ACL_NO_RIGHTS;
foreach(i, stmt->privileges) foreach(i, stmt->privileges)
{ {
AclMode priv = lfirsti(i); AclMode priv = lfirst_int(i);
if (priv & ~((AclMode) ACL_ALL_RIGHTS_RELATION)) if (priv & ~((AclMode) ACL_ALL_RIGHTS_RELATION))
ereport(ERROR, ereport(ERROR,
@ -328,16 +328,16 @@ static void
ExecuteGrantStmt_Database(GrantStmt *stmt) ExecuteGrantStmt_Database(GrantStmt *stmt)
{ {
AclMode privileges; AclMode privileges;
List *i; ListCell *i;
if (lfirsti(stmt->privileges) == ACL_ALL_RIGHTS) if (linitial_int(stmt->privileges) == ACL_ALL_RIGHTS)
privileges = ACL_ALL_RIGHTS_DATABASE; privileges = ACL_ALL_RIGHTS_DATABASE;
else else
{ {
privileges = ACL_NO_RIGHTS; privileges = ACL_NO_RIGHTS;
foreach(i, stmt->privileges) foreach(i, stmt->privileges)
{ {
AclMode priv = lfirsti(i); AclMode priv = lfirst_int(i);
if (priv & ~((AclMode) ACL_ALL_RIGHTS_DATABASE)) if (priv & ~((AclMode) ACL_ALL_RIGHTS_DATABASE))
ereport(ERROR, ereport(ERROR,
@ -433,16 +433,16 @@ static void
ExecuteGrantStmt_Function(GrantStmt *stmt) ExecuteGrantStmt_Function(GrantStmt *stmt)
{ {
AclMode privileges; AclMode privileges;
List *i; ListCell *i;
if (lfirsti(stmt->privileges) == ACL_ALL_RIGHTS) if (linitial_int(stmt->privileges) == ACL_ALL_RIGHTS)
privileges = ACL_ALL_RIGHTS_FUNCTION; privileges = ACL_ALL_RIGHTS_FUNCTION;
else else
{ {
privileges = ACL_NO_RIGHTS; privileges = ACL_NO_RIGHTS;
foreach(i, stmt->privileges) foreach(i, stmt->privileges)
{ {
AclMode priv = lfirsti(i); AclMode priv = lfirst_int(i);
if (priv & ~((AclMode) ACL_ALL_RIGHTS_FUNCTION)) if (priv & ~((AclMode) ACL_ALL_RIGHTS_FUNCTION))
ereport(ERROR, ereport(ERROR,
@ -534,16 +534,16 @@ static void
ExecuteGrantStmt_Language(GrantStmt *stmt) ExecuteGrantStmt_Language(GrantStmt *stmt)
{ {
AclMode privileges; AclMode privileges;
List *i; ListCell *i;
if (lfirsti(stmt->privileges) == ACL_ALL_RIGHTS) if (linitial_int(stmt->privileges) == ACL_ALL_RIGHTS)
privileges = ACL_ALL_RIGHTS_LANGUAGE; privileges = ACL_ALL_RIGHTS_LANGUAGE;
else else
{ {
privileges = ACL_NO_RIGHTS; privileges = ACL_NO_RIGHTS;
foreach(i, stmt->privileges) foreach(i, stmt->privileges)
{ {
AclMode priv = lfirsti(i); AclMode priv = lfirst_int(i);
if (priv & ~((AclMode) ACL_ALL_RIGHTS_LANGUAGE)) if (priv & ~((AclMode) ACL_ALL_RIGHTS_LANGUAGE))
ereport(ERROR, ereport(ERROR,
@ -643,16 +643,16 @@ static void
ExecuteGrantStmt_Namespace(GrantStmt *stmt) ExecuteGrantStmt_Namespace(GrantStmt *stmt)
{ {
AclMode privileges; AclMode privileges;
List *i; ListCell *i;
if (lfirsti(stmt->privileges) == ACL_ALL_RIGHTS) if (linitial_int(stmt->privileges) == ACL_ALL_RIGHTS)
privileges = ACL_ALL_RIGHTS_NAMESPACE; privileges = ACL_ALL_RIGHTS_NAMESPACE;
else else
{ {
privileges = ACL_NO_RIGHTS; privileges = ACL_NO_RIGHTS;
foreach(i, stmt->privileges) foreach(i, stmt->privileges)
{ {
AclMode priv = lfirsti(i); AclMode priv = lfirst_int(i);
if (priv & ~((AclMode) ACL_ALL_RIGHTS_NAMESPACE)) if (priv & ~((AclMode) ACL_ALL_RIGHTS_NAMESPACE))
ereport(ERROR, ereport(ERROR,

View File

@ -8,7 +8,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/dependency.c,v 1.35 2004/05/05 04:48:45 tgl Exp $ * $PostgreSQL: pgsql/src/backend/catalog/dependency.c,v 1.36 2004/05/26 04:41:06 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -841,7 +841,7 @@ recordDependencyOnExpr(const ObjectAddress *depender,
init_object_addresses(&context.addrs); init_object_addresses(&context.addrs);
/* Set up interpretation for Vars at varlevelsup = 0 */ /* Set up interpretation for Vars at varlevelsup = 0 */
context.rtables = makeList1(rtable); context.rtables = list_make1(rtable);
/* Scan the expression tree for referenceable objects */ /* Scan the expression tree for referenceable objects */
find_expr_references_walker(expr, &context); find_expr_references_walker(expr, &context);
@ -883,7 +883,7 @@ recordDependencyOnSingleRelExpr(const ObjectAddress *depender,
rte.rtekind = RTE_RELATION; rte.rtekind = RTE_RELATION;
rte.relid = relId; rte.relid = relId;
context.rtables = makeList1(makeList1(&rte)); context.rtables = list_make1(list_make1(&rte));
/* Scan the expression tree for referenceable objects */ /* Scan the expression tree for referenceable objects */
find_expr_references_walker(expr, &context); find_expr_references_walker(expr, &context);
@ -960,24 +960,14 @@ find_expr_references_walker(Node *node,
if (IsA(node, Var)) if (IsA(node, Var))
{ {
Var *var = (Var *) node; Var *var = (Var *) node;
int levelsup; List *rtable;
List *rtable,
*rtables;
RangeTblEntry *rte; RangeTblEntry *rte;
/* Find matching rtable entry, or complain if not found */ /* Find matching rtable entry, or complain if not found */
levelsup = var->varlevelsup; if (var->varlevelsup >= list_length(context->rtables))
rtables = context->rtables;
while (levelsup--)
{
if (rtables == NIL)
break;
rtables = lnext(rtables);
}
if (rtables == NIL)
elog(ERROR, "invalid varlevelsup %d", var->varlevelsup); elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
rtable = lfirst(rtables); rtable = (List *) list_nth(context->rtables, var->varlevelsup);
if (var->varno <= 0 || var->varno > length(rtable)) if (var->varno <= 0 || var->varno > list_length(rtable))
elog(ERROR, "invalid varno %d", var->varno); elog(ERROR, "invalid varno %d", var->varno);
rte = rt_fetch(var->varno, rtable); rte = rt_fetch(var->varno, rtable);
if (rte->rtekind == RTE_RELATION) if (rte->rtekind == RTE_RELATION)
@ -994,13 +984,15 @@ find_expr_references_walker(Node *node,
/* We must make the context appropriate for join's level */ /* We must make the context appropriate for join's level */
save_rtables = context->rtables; save_rtables = context->rtables;
context->rtables = rtables; context->rtables = list_copy_tail(context->rtables,
var->varlevelsup);
if (var->varattno <= 0 || if (var->varattno <= 0 ||
var->varattno > length(rte->joinaliasvars)) var->varattno > list_length(rte->joinaliasvars))
elog(ERROR, "invalid varattno %d", var->varattno); elog(ERROR, "invalid varattno %d", var->varattno);
find_expr_references_walker((Node *) nth(var->varattno - 1, find_expr_references_walker((Node *) list_nth(rte->joinaliasvars,
rte->joinaliasvars), var->varattno - 1),
context); context);
list_free(context->rtables);
context->rtables = save_rtables; context->rtables = save_rtables;
} }
return false; return false;
@ -1056,11 +1048,11 @@ find_expr_references_walker(Node *node,
if (IsA(node, SubLink)) if (IsA(node, SubLink))
{ {
SubLink *sublink = (SubLink *) node; SubLink *sublink = (SubLink *) node;
List *opid; ListCell *opid;
foreach(opid, sublink->operOids) foreach(opid, sublink->operOids)
{ {
add_object_address(OCLASS_OPERATOR, lfirsto(opid), 0, add_object_address(OCLASS_OPERATOR, lfirst_oid(opid), 0,
&context->addrs); &context->addrs);
} }
/* fall through to examine arguments */ /* fall through to examine arguments */
@ -1074,7 +1066,7 @@ find_expr_references_walker(Node *node,
{ {
/* Recurse into RTE subquery or not-yet-planned sublink subquery */ /* Recurse into RTE subquery or not-yet-planned sublink subquery */
Query *query = (Query *) node; Query *query = (Query *) node;
List *rtable; ListCell *rtable;
bool result; bool result;
/* /*
@ -1099,7 +1091,7 @@ find_expr_references_walker(Node *node,
find_expr_references_walker, find_expr_references_walker,
(void *) context, (void *) context,
QTW_IGNORE_JOINALIASES); QTW_IGNORE_JOINALIASES);
context->rtables = lnext(context->rtables); context->rtables = list_delete_first(context->rtables);
return result; return result;
} }
return expression_tree_walker(node, find_expr_references_walker, return expression_tree_walker(node, find_expr_references_walker,

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.264 2004/05/08 19:09:24 tgl Exp $ * $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.265 2004/05/26 04:41:07 neilc Exp $
* *
* *
* INTERFACE ROUTINES * INTERFACE ROUTINES
@ -1379,11 +1379,11 @@ StoreRelCheck(Relation rel, char *ccname, char *ccbin)
* contents of subselects. * contents of subselects.
*/ */
varList = pull_var_clause(expr, false); varList = pull_var_clause(expr, false);
keycount = length(varList); keycount = list_length(varList);
if (keycount > 0) if (keycount > 0)
{ {
List *vl; ListCell *vl;
int i = 0; int i = 0;
attNos = (int16 *) palloc(keycount * sizeof(int16)); attNos = (int16 *) palloc(keycount * sizeof(int16));
@ -1505,7 +1505,7 @@ AddRelationRawConstraints(Relation rel,
RangeTblEntry *rte; RangeTblEntry *rte;
int numchecks; int numchecks;
int constr_name_ctr = 0; int constr_name_ctr = 0;
List *listptr; ListCell *cell;
Node *expr; Node *expr;
CookedConstraint *cooked; CookedConstraint *cooked;
@ -1540,9 +1540,9 @@ AddRelationRawConstraints(Relation rel,
/* /*
* Process column default expressions. * Process column default expressions.
*/ */
foreach(listptr, rawColDefaults) foreach(cell, rawColDefaults)
{ {
RawColumnDefault *colDef = (RawColumnDefault *) lfirst(listptr); RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1]; Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
expr = cookDefault(pstate, colDef->raw_default, expr = cookDefault(pstate, colDef->raw_default,
@ -1563,9 +1563,9 @@ AddRelationRawConstraints(Relation rel,
* Process constraint expressions. * Process constraint expressions.
*/ */
numchecks = numoldchecks; numchecks = numoldchecks;
foreach(listptr, rawConstraints) foreach(cell, rawConstraints)
{ {
Constraint *cdef = (Constraint *) lfirst(listptr); Constraint *cdef = (Constraint *) lfirst(cell);
char *ccname; char *ccname;
if (cdef->contype != CONSTR_CHECK || cdef->raw_expr == NULL) if (cdef->contype != CONSTR_CHECK || cdef->raw_expr == NULL)
@ -1575,7 +1575,7 @@ AddRelationRawConstraints(Relation rel,
/* Check name uniqueness, or generate a new name */ /* Check name uniqueness, or generate a new name */
if (cdef->name != NULL) if (cdef->name != NULL)
{ {
List *listptr2; ListCell *cell2;
ccname = cdef->name; ccname = cdef->name;
/* Check against pre-existing constraints */ /* Check against pre-existing constraints */
@ -1589,9 +1589,9 @@ AddRelationRawConstraints(Relation rel,
ccname, RelationGetRelationName(rel)))); ccname, RelationGetRelationName(rel))));
/* Check against other new constraints */ /* Check against other new constraints */
/* Needed because we don't do CommandCounterIncrement in loop */ /* Needed because we don't do CommandCounterIncrement in loop */
foreach(listptr2, rawConstraints) foreach(cell2, rawConstraints)
{ {
Constraint *cdef2 = (Constraint *) lfirst(listptr2); Constraint *cdef2 = (Constraint *) lfirst(cell2);
if (cdef2 == cdef || if (cdef2 == cdef ||
cdef2->contype != CONSTR_CHECK || cdef2->contype != CONSTR_CHECK ||
@ -1611,7 +1611,7 @@ AddRelationRawConstraints(Relation rel,
do do
{ {
List *listptr2; ListCell *cell2;
/* /*
* Generate a name that does not conflict with * Generate a name that does not conflict with
@ -1629,9 +1629,9 @@ AddRelationRawConstraints(Relation rel,
* name. * name.
*/ */
success = true; success = true;
foreach(listptr2, rawConstraints) foreach(cell2, rawConstraints)
{ {
Constraint *cdef2 = (Constraint *) lfirst(listptr2); Constraint *cdef2 = (Constraint *) lfirst(cell2);
if (cdef2 == cdef || if (cdef2 == cdef ||
cdef2->contype != CONSTR_CHECK || cdef2->contype != CONSTR_CHECK ||
@ -1660,7 +1660,7 @@ AddRelationRawConstraints(Relation rel,
/* /*
* Make sure no outside relations are referred to. * Make sure no outside relations are referred to.
*/ */
if (length(pstate->p_rtable) != 1) if (list_length(pstate->p_rtable) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE), (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("only table \"%s\" can be referenced in check constraint", errmsg("only table \"%s\" can be referenced in check constraint",
@ -1949,7 +1949,7 @@ static void
RelationTruncateIndexes(Oid heapId) RelationTruncateIndexes(Oid heapId)
{ {
Relation heapRelation; Relation heapRelation;
List *indlist; ListCell *indlist;
/* /*
* Open the heap rel. We need grab no lock because we assume * Open the heap rel. We need grab no lock because we assume
@ -1960,7 +1960,7 @@ RelationTruncateIndexes(Oid heapId)
/* Ask the relcache to produce a list of the indexes of the rel */ /* Ask the relcache to produce a list of the indexes of the rel */
foreach(indlist, RelationGetIndexList(heapRelation)) foreach(indlist, RelationGetIndexList(heapRelation))
{ {
Oid indexId = lfirsto(indlist); Oid indexId = lfirst_oid(indlist);
Relation currentIndex; Relation currentIndex;
IndexInfo *indexInfo; IndexInfo *indexInfo;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/index.c,v 1.231 2004/05/08 19:09:24 tgl Exp $ * $PostgreSQL: pgsql/src/backend/catalog/index.c,v 1.232 2004/05/26 04:41:07 neilc Exp $
* *
* *
* INTERFACE ROUTINES * INTERFACE ROUTINES
@ -88,7 +88,7 @@ ConstructTupleDescriptor(Relation heapRelation,
Oid *classObjectId) Oid *classObjectId)
{ {
int numatts = indexInfo->ii_NumIndexAttrs; int numatts = indexInfo->ii_NumIndexAttrs;
List *indexprs = indexInfo->ii_Expressions; ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
TupleDesc heapTupDesc; TupleDesc heapTupDesc;
TupleDesc indexTupDesc; TupleDesc indexTupDesc;
int natts; /* #atts in heap rel --- for error checks */ int natts; /* #atts in heap rel --- for error checks */
@ -165,10 +165,10 @@ ConstructTupleDescriptor(Relation heapRelation,
/* Expressional index */ /* Expressional index */
Node *indexkey; Node *indexkey;
if (indexprs == NIL) /* shouldn't happen */ if (indexpr_item == NULL) /* shouldn't happen */
elog(ERROR, "too few entries in indexprs list"); elog(ERROR, "too few entries in indexprs list");
indexkey = (Node *) lfirst(indexprs); indexkey = (Node *) lfirst(indexpr_item);
indexprs = lnext(indexprs); indexpr_item = lnext(indexpr_item);
/* /*
* Make the attribute's name "pg_expresssion_nnn" (maybe think * Make the attribute's name "pg_expresssion_nnn" (maybe think
@ -928,7 +928,7 @@ FormIndexDatum(IndexInfo *indexInfo,
Datum *datum, Datum *datum,
char *nullv) char *nullv)
{ {
List *indexprs; ListCell *indexpr_item;
int i; int i;
if (indexInfo->ii_Expressions != NIL && if (indexInfo->ii_Expressions != NIL &&
@ -941,7 +941,7 @@ FormIndexDatum(IndexInfo *indexInfo,
/* Check caller has set up context correctly */ /* Check caller has set up context correctly */
Assert(GetPerTupleExprContext(estate)->ecxt_scantuple->val == heapTuple); Assert(GetPerTupleExprContext(estate)->ecxt_scantuple->val == heapTuple);
} }
indexprs = indexInfo->ii_ExpressionsState; indexpr_item = list_head(indexInfo->ii_ExpressionsState);
for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++) for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
{ {
@ -962,19 +962,19 @@ FormIndexDatum(IndexInfo *indexInfo,
/* /*
* Index expression --- need to evaluate it. * Index expression --- need to evaluate it.
*/ */
if (indexprs == NIL) if (indexpr_item == NULL)
elog(ERROR, "wrong number of index expressions"); elog(ERROR, "wrong number of index expressions");
iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexprs), iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
GetPerTupleExprContext(estate), GetPerTupleExprContext(estate),
&isNull, &isNull,
NULL); NULL);
indexprs = lnext(indexprs); indexpr_item = lnext(indexpr_item);
} }
datum[i] = iDatum; datum[i] = iDatum;
nullv[i] = (isNull) ? 'n' : ' '; nullv[i] = (isNull) ? 'n' : ' ';
} }
if (indexprs != NIL) if (indexpr_item != NULL)
elog(ERROR, "wrong number of index expressions"); elog(ERROR, "wrong number of index expressions");
} }
@ -1738,8 +1738,8 @@ reindex_relation(Oid relid, bool toast_too)
bool is_pg_class; bool is_pg_class;
bool result; bool result;
List *indexIds, List *indexIds,
*doneIndexes, *doneIndexes;
*indexId; ListCell *indexId;
/* /*
* Ensure to hold an exclusive lock throughout the transaction. The * Ensure to hold an exclusive lock throughout the transaction. The
@ -1780,7 +1780,7 @@ reindex_relation(Oid relid, bool toast_too)
/* Reindex all the indexes. */ /* Reindex all the indexes. */
foreach(indexId, indexIds) foreach(indexId, indexIds)
{ {
Oid indexOid = lfirsto(indexId); Oid indexOid = lfirst_oid(indexId);
if (is_pg_class) if (is_pg_class)
RelationSetIndexList(rel, doneIndexes); RelationSetIndexList(rel, doneIndexes);
@ -1790,7 +1790,7 @@ reindex_relation(Oid relid, bool toast_too)
CommandCounterIncrement(); CommandCounterIncrement();
if (is_pg_class) if (is_pg_class)
doneIndexes = lappendo(doneIndexes, indexOid); doneIndexes = lappend_oid(doneIndexes, indexOid);
} }
if (is_pg_class) if (is_pg_class)

View File

@ -13,7 +13,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/namespace.c,v 1.63 2004/02/13 01:08:20 tgl Exp $ * $PostgreSQL: pgsql/src/backend/catalog/namespace.c,v 1.64 2004/05/26 04:41:07 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -276,13 +276,13 @@ Oid
RelnameGetRelid(const char *relname) RelnameGetRelid(const char *relname)
{ {
Oid relid; Oid relid;
List *lptr; ListCell *l;
recomputeNamespacePath(); recomputeNamespacePath();
foreach(lptr, namespaceSearchPath) foreach(l, namespaceSearchPath)
{ {
Oid namespaceId = lfirsto(lptr); Oid namespaceId = lfirst_oid(l);
relid = get_relname_relid(relname, namespaceId); relid = get_relname_relid(relname, namespaceId);
if (OidIsValid(relid)) if (OidIsValid(relid))
@ -320,11 +320,11 @@ RelationIsVisible(Oid relid)
/* /*
* Quick check: if it ain't in the path at all, it ain't visible. * Quick check: if it ain't in the path at all, it ain't visible.
* Items in the system namespace are surely in the path and so we * Items in the system namespace are surely in the path and so we
* needn't even do oidMember() for them. * needn't even do list_member_oid() for them.
*/ */
relnamespace = relform->relnamespace; relnamespace = relform->relnamespace;
if (relnamespace != PG_CATALOG_NAMESPACE && if (relnamespace != PG_CATALOG_NAMESPACE &&
!oidMember(relnamespace, namespaceSearchPath)) !list_member_oid(namespaceSearchPath, relnamespace))
visible = false; visible = false;
else else
{ {
@ -356,13 +356,13 @@ Oid
TypenameGetTypid(const char *typname) TypenameGetTypid(const char *typname)
{ {
Oid typid; Oid typid;
List *lptr; ListCell *l;
recomputeNamespacePath(); recomputeNamespacePath();
foreach(lptr, namespaceSearchPath) foreach(l, namespaceSearchPath)
{ {
Oid namespaceId = lfirsto(lptr); Oid namespaceId = lfirst_oid(l);
typid = GetSysCacheOid(TYPENAMENSP, typid = GetSysCacheOid(TYPENAMENSP,
PointerGetDatum(typname), PointerGetDatum(typname),
@ -402,11 +402,11 @@ TypeIsVisible(Oid typid)
/* /*
* Quick check: if it ain't in the path at all, it ain't visible. * Quick check: if it ain't in the path at all, it ain't visible.
* Items in the system namespace are surely in the path and so we * Items in the system namespace are surely in the path and so we
* needn't even do oidMember() for them. * needn't even do list_member_oid() for them.
*/ */
typnamespace = typform->typnamespace; typnamespace = typform->typnamespace;
if (typnamespace != PG_CATALOG_NAMESPACE && if (typnamespace != PG_CATALOG_NAMESPACE &&
!oidMember(typnamespace, namespaceSearchPath)) !list_member_oid(namespaceSearchPath, typnamespace))
visible = false; visible = false;
else else
{ {
@ -496,15 +496,15 @@ FuncnameGetCandidates(List *names, int nargs)
else else
{ {
/* Consider only procs that are in the search path */ /* Consider only procs that are in the search path */
List *nsp; ListCell *nsp;
foreach(nsp, namespaceSearchPath) foreach(nsp, namespaceSearchPath)
{ {
if (procform->pronamespace == lfirsto(nsp)) if (procform->pronamespace == lfirst_oid(nsp))
break; break;
pathpos++; pathpos++;
} }
if (nsp == NIL) if (nsp == NULL)
continue; /* proc is not in search path */ continue; /* proc is not in search path */
/* /*
@ -603,11 +603,11 @@ FunctionIsVisible(Oid funcid)
/* /*
* Quick check: if it ain't in the path at all, it ain't visible. * Quick check: if it ain't in the path at all, it ain't visible.
* Items in the system namespace are surely in the path and so we * Items in the system namespace are surely in the path and so we
* needn't even do oidMember() for them. * needn't even do list_member_oid() for them.
*/ */
pronamespace = procform->pronamespace; pronamespace = procform->pronamespace;
if (pronamespace != PG_CATALOG_NAMESPACE && if (pronamespace != PG_CATALOG_NAMESPACE &&
!oidMember(pronamespace, namespaceSearchPath)) !list_member_oid(namespaceSearchPath, pronamespace))
visible = false; visible = false;
else else
{ {
@ -623,7 +623,7 @@ FunctionIsVisible(Oid funcid)
visible = false; visible = false;
clist = FuncnameGetCandidates(makeList1(makeString(proname)), nargs); clist = FuncnameGetCandidates(list_make1(makeString(proname)), nargs);
for (; clist; clist = clist->next) for (; clist; clist = clist->next)
{ {
@ -727,15 +727,15 @@ OpernameGetCandidates(List *names, char oprkind)
else else
{ {
/* Consider only opers that are in the search path */ /* Consider only opers that are in the search path */
List *nsp; ListCell *nsp;
foreach(nsp, namespaceSearchPath) foreach(nsp, namespaceSearchPath)
{ {
if (operform->oprnamespace == lfirsto(nsp)) if (operform->oprnamespace == lfirst_oid(nsp))
break; break;
pathpos++; pathpos++;
} }
if (nsp == NIL) if (nsp == NULL)
continue; /* oper is not in search path */ continue; /* oper is not in search path */
/* /*
@ -832,11 +832,11 @@ OperatorIsVisible(Oid oprid)
/* /*
* Quick check: if it ain't in the path at all, it ain't visible. * Quick check: if it ain't in the path at all, it ain't visible.
* Items in the system namespace are surely in the path and so we * Items in the system namespace are surely in the path and so we
* needn't even do oidMember() for them. * needn't even do list_member_oid() for them.
*/ */
oprnamespace = oprform->oprnamespace; oprnamespace = oprform->oprnamespace;
if (oprnamespace != PG_CATALOG_NAMESPACE && if (oprnamespace != PG_CATALOG_NAMESPACE &&
!oidMember(oprnamespace, namespaceSearchPath)) !list_member_oid(namespaceSearchPath, oprnamespace))
visible = false; visible = false;
else else
{ {
@ -852,7 +852,7 @@ OperatorIsVisible(Oid oprid)
visible = false; visible = false;
clist = OpernameGetCandidates(makeList1(makeString(oprname)), clist = OpernameGetCandidates(list_make1(makeString(oprname)),
oprform->oprkind); oprform->oprkind);
for (; clist; clist = clist->next) for (; clist; clist = clist->next)
@ -903,16 +903,16 @@ OpclassGetCandidates(Oid amid)
Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup); Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
int pathpos = 0; int pathpos = 0;
OpclassCandidateList newResult; OpclassCandidateList newResult;
List *nsp; ListCell *nsp;
/* Consider only opclasses that are in the search path */ /* Consider only opclasses that are in the search path */
foreach(nsp, namespaceSearchPath) foreach(nsp, namespaceSearchPath)
{ {
if (opcform->opcnamespace == lfirsto(nsp)) if (opcform->opcnamespace == lfirst_oid(nsp))
break; break;
pathpos++; pathpos++;
} }
if (nsp == NIL) if (nsp == NULL)
continue; /* opclass is not in search path */ continue; /* opclass is not in search path */
/* /*
@ -998,13 +998,13 @@ Oid
OpclassnameGetOpcid(Oid amid, const char *opcname) OpclassnameGetOpcid(Oid amid, const char *opcname)
{ {
Oid opcid; Oid opcid;
List *lptr; ListCell *l;
recomputeNamespacePath(); recomputeNamespacePath();
foreach(lptr, namespaceSearchPath) foreach(l, namespaceSearchPath)
{ {
Oid namespaceId = lfirsto(lptr); Oid namespaceId = lfirst_oid(l);
opcid = GetSysCacheOid(CLAAMNAMENSP, opcid = GetSysCacheOid(CLAAMNAMENSP,
ObjectIdGetDatum(amid), ObjectIdGetDatum(amid),
@ -1045,11 +1045,11 @@ OpclassIsVisible(Oid opcid)
/* /*
* Quick check: if it ain't in the path at all, it ain't visible. * Quick check: if it ain't in the path at all, it ain't visible.
* Items in the system namespace are surely in the path and so we * Items in the system namespace are surely in the path and so we
* needn't even do oidMember() for them. * needn't even do list_member_oid() for them.
*/ */
opcnamespace = opcform->opcnamespace; opcnamespace = opcform->opcnamespace;
if (opcnamespace != PG_CATALOG_NAMESPACE && if (opcnamespace != PG_CATALOG_NAMESPACE &&
!oidMember(opcnamespace, namespaceSearchPath)) !list_member_oid(namespaceSearchPath, opcnamespace))
visible = false; visible = false;
else else
{ {
@ -1080,13 +1080,13 @@ Oid
ConversionGetConid(const char *conname) ConversionGetConid(const char *conname)
{ {
Oid conid; Oid conid;
List *lptr; ListCell *l;
recomputeNamespacePath(); recomputeNamespacePath();
foreach(lptr, namespaceSearchPath) foreach(l, namespaceSearchPath)
{ {
Oid namespaceId = lfirsto(lptr); Oid namespaceId = lfirst_oid(l);
conid = GetSysCacheOid(CONNAMENSP, conid = GetSysCacheOid(CONNAMENSP,
PointerGetDatum(conname), PointerGetDatum(conname),
@ -1126,11 +1126,11 @@ ConversionIsVisible(Oid conid)
/* /*
* Quick check: if it ain't in the path at all, it ain't visible. * Quick check: if it ain't in the path at all, it ain't visible.
* Items in the system namespace are surely in the path and so we * Items in the system namespace are surely in the path and so we
* needn't even do oidMember() for them. * needn't even do list_member_oid() for them.
*/ */
connamespace = conform->connamespace; connamespace = conform->connamespace;
if (connamespace != PG_CATALOG_NAMESPACE && if (connamespace != PG_CATALOG_NAMESPACE &&
!oidMember(connamespace, namespaceSearchPath)) !list_member_oid(namespaceSearchPath, connamespace))
visible = false; visible = false;
else else
{ {
@ -1166,17 +1166,17 @@ DeconstructQualifiedName(List *names,
char *schemaname = NULL; char *schemaname = NULL;
char *objname = NULL; char *objname = NULL;
switch (length(names)) switch (list_length(names))
{ {
case 1: case 1:
objname = strVal(lfirst(names)); objname = strVal(linitial(names));
break; break;
case 2: case 2:
schemaname = strVal(lfirst(names)); schemaname = strVal(linitial(names));
objname = strVal(lsecond(names)); objname = strVal(lsecond(names));
break; break;
case 3: case 3:
catalogname = strVal(lfirst(names)); catalogname = strVal(linitial(names));
schemaname = strVal(lsecond(names)); schemaname = strVal(lsecond(names));
objname = strVal(lthird(names)); objname = strVal(lthird(names));
@ -1287,17 +1287,17 @@ makeRangeVarFromNameList(List *names)
{ {
RangeVar *rel = makeRangeVar(NULL, NULL); RangeVar *rel = makeRangeVar(NULL, NULL);
switch (length(names)) switch (list_length(names))
{ {
case 1: case 1:
rel->relname = strVal(lfirst(names)); rel->relname = strVal(linitial(names));
break; break;
case 2: case 2:
rel->schemaname = strVal(lfirst(names)); rel->schemaname = strVal(linitial(names));
rel->relname = strVal(lsecond(names)); rel->relname = strVal(lsecond(names));
break; break;
case 3: case 3:
rel->catalogname = strVal(lfirst(names)); rel->catalogname = strVal(linitial(names));
rel->schemaname = strVal(lsecond(names)); rel->schemaname = strVal(lsecond(names));
rel->relname = strVal(lthird(names)); rel->relname = strVal(lthird(names));
break; break;
@ -1323,13 +1323,13 @@ char *
NameListToString(List *names) NameListToString(List *names)
{ {
StringInfoData string; StringInfoData string;
List *l; ListCell *l;
initStringInfo(&string); initStringInfo(&string);
foreach(l, names) foreach(l, names)
{ {
if (l != names) if (l != list_head(names))
appendStringInfoChar(&string, '.'); appendStringInfoChar(&string, '.');
appendStringInfoString(&string, strVal(lfirst(l))); appendStringInfoString(&string, strVal(lfirst(l)));
} }
@ -1348,13 +1348,13 @@ char *
NameListToQuotedString(List *names) NameListToQuotedString(List *names)
{ {
StringInfoData string; StringInfoData string;
List *l; ListCell *l;
initStringInfo(&string); initStringInfo(&string);
foreach(l, names) foreach(l, names)
{ {
if (l != names) if (l != list_head(names))
appendStringInfoChar(&string, '.'); appendStringInfoChar(&string, '.');
appendStringInfoString(&string, quote_identifier(strVal(lfirst(l)))); appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
} }
@ -1435,7 +1435,7 @@ FindConversionByName(List *name)
char *conversion_name; char *conversion_name;
Oid namespaceId; Oid namespaceId;
Oid conoid; Oid conoid;
List *lptr; ListCell *l;
/* deconstruct the name list */ /* deconstruct the name list */
DeconstructQualifiedName(name, &schemaname, &conversion_name); DeconstructQualifiedName(name, &schemaname, &conversion_name);
@ -1451,9 +1451,9 @@ FindConversionByName(List *name)
/* search for it in search path */ /* search for it in search path */
recomputeNamespacePath(); recomputeNamespacePath();
foreach(lptr, namespaceSearchPath) foreach(l, namespaceSearchPath)
{ {
namespaceId = lfirsto(lptr); namespaceId = lfirst_oid(l);
conoid = FindConversion(conversion_name, namespaceId); conoid = FindConversion(conversion_name, namespaceId);
if (OidIsValid(conoid)) if (OidIsValid(conoid))
return conoid; return conoid;
@ -1471,13 +1471,13 @@ Oid
FindDefaultConversionProc(int4 for_encoding, int4 to_encoding) FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
{ {
Oid proc; Oid proc;
List *lptr; ListCell *l;
recomputeNamespacePath(); recomputeNamespacePath();
foreach(lptr, namespaceSearchPath) foreach(l, namespaceSearchPath)
{ {
Oid namespaceId = lfirsto(lptr); Oid namespaceId = lfirst_oid(l);
proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding); proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
if (OidIsValid(proc)) if (OidIsValid(proc))
@ -1499,7 +1499,7 @@ recomputeNamespacePath(void)
List *namelist; List *namelist;
List *oidlist; List *oidlist;
List *newpath; List *newpath;
List *l; ListCell *l;
Oid firstNS; Oid firstNS;
MemoryContext oldcxt; MemoryContext oldcxt;
@ -1550,10 +1550,10 @@ recomputeNamespacePath(void)
0, 0, 0); 0, 0, 0);
ReleaseSysCache(tuple); ReleaseSysCache(tuple);
if (OidIsValid(namespaceId) && if (OidIsValid(namespaceId) &&
!oidMember(namespaceId, oidlist) && !list_member_oid(oidlist, namespaceId) &&
pg_namespace_aclcheck(namespaceId, userId, pg_namespace_aclcheck(namespaceId, userId,
ACL_USAGE) == ACLCHECK_OK) ACL_USAGE) == ACLCHECK_OK)
oidlist = lappendo(oidlist, namespaceId); oidlist = lappend_oid(oidlist, namespaceId);
} }
} }
else else
@ -1563,10 +1563,10 @@ recomputeNamespacePath(void)
CStringGetDatum(curname), CStringGetDatum(curname),
0, 0, 0); 0, 0, 0);
if (OidIsValid(namespaceId) && if (OidIsValid(namespaceId) &&
!oidMember(namespaceId, oidlist) && !list_member_oid(oidlist, namespaceId) &&
pg_namespace_aclcheck(namespaceId, userId, pg_namespace_aclcheck(namespaceId, userId,
ACL_USAGE) == ACLCHECK_OK) ACL_USAGE) == ACLCHECK_OK)
oidlist = lappendo(oidlist, namespaceId); oidlist = lappend_oid(oidlist, namespaceId);
} }
} }
@ -1576,34 +1576,34 @@ recomputeNamespacePath(void)
if (oidlist == NIL) if (oidlist == NIL)
firstNS = InvalidOid; firstNS = InvalidOid;
else else
firstNS = lfirsto(oidlist); firstNS = linitial_oid(oidlist);
/* /*
* Add any implicitly-searched namespaces to the list. Note these go * Add any implicitly-searched namespaces to the list. Note these go
* on the front, not the back; also notice that we do not check USAGE * on the front, not the back; also notice that we do not check USAGE
* permissions for these. * permissions for these.
*/ */
if (!oidMember(PG_CATALOG_NAMESPACE, oidlist)) if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
oidlist = lconso(PG_CATALOG_NAMESPACE, oidlist); oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
if (OidIsValid(myTempNamespace) && if (OidIsValid(myTempNamespace) &&
!oidMember(myTempNamespace, oidlist)) !list_member_oid(oidlist, myTempNamespace))
oidlist = lconso(myTempNamespace, oidlist); oidlist = lcons_oid(myTempNamespace, oidlist);
if (OidIsValid(mySpecialNamespace) && if (OidIsValid(mySpecialNamespace) &&
!oidMember(mySpecialNamespace, oidlist)) !list_member_oid(oidlist, mySpecialNamespace))
oidlist = lconso(mySpecialNamespace, oidlist); oidlist = lcons_oid(mySpecialNamespace, oidlist);
/* /*
* Now that we've successfully built the new list of namespace OIDs, * Now that we've successfully built the new list of namespace OIDs,
* save it in permanent storage. * save it in permanent storage.
*/ */
oldcxt = MemoryContextSwitchTo(TopMemoryContext); oldcxt = MemoryContextSwitchTo(TopMemoryContext);
newpath = listCopy(oidlist); newpath = list_copy(oidlist);
MemoryContextSwitchTo(oldcxt); MemoryContextSwitchTo(oldcxt);
/* Now safe to assign to state variable. */ /* Now safe to assign to state variable. */
freeList(namespaceSearchPath); list_free(namespaceSearchPath);
namespaceSearchPath = newpath; namespaceSearchPath = newpath;
/* /*
@ -1621,8 +1621,8 @@ recomputeNamespacePath(void)
/* Clean up. */ /* Clean up. */
pfree(rawname); pfree(rawname);
freeList(namelist); list_free(namelist);
freeList(oidlist); list_free(oidlist);
} }
/* /*
@ -1783,7 +1783,7 @@ assign_search_path(const char *newval, bool doit, GucSource source)
{ {
char *rawname; char *rawname;
List *namelist; List *namelist;
List *l; ListCell *l;
/* Need a modifiable copy of string */ /* Need a modifiable copy of string */
rawname = pstrdup(newval); rawname = pstrdup(newval);
@ -1793,7 +1793,7 @@ assign_search_path(const char *newval, bool doit, GucSource source)
{ {
/* syntax error in name list */ /* syntax error in name list */
pfree(rawname); pfree(rawname);
freeList(namelist); list_free(namelist);
return NULL; return NULL;
} }
@ -1831,7 +1831,7 @@ assign_search_path(const char *newval, bool doit, GucSource source)
} }
pfree(rawname); pfree(rawname);
freeList(namelist); list_free(namelist);
/* /*
* We mark the path as needing recomputation, but don't do anything * We mark the path as needing recomputation, but don't do anything
@ -1862,7 +1862,7 @@ InitializeSearchPath(void)
MemoryContext oldcxt; MemoryContext oldcxt;
oldcxt = MemoryContextSwitchTo(TopMemoryContext); oldcxt = MemoryContextSwitchTo(TopMemoryContext);
namespaceSearchPath = makeListo1(PG_CATALOG_NAMESPACE); namespaceSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
MemoryContextSwitchTo(oldcxt); MemoryContextSwitchTo(oldcxt);
defaultCreationNamespace = PG_CATALOG_NAMESPACE; defaultCreationNamespace = PG_CATALOG_NAMESPACE;
firstExplicitNamespace = PG_CATALOG_NAMESPACE; firstExplicitNamespace = PG_CATALOG_NAMESPACE;
@ -1895,12 +1895,12 @@ NamespaceCallback(Datum arg, Oid relid)
} }
/* /*
* Fetch the active search path, expressed as a List of OIDs. * Fetch the active search path. The return value is a palloc'ed list
* of OIDs; the caller is responsible for freeing this storage as
* appropriate.
* *
* The returned list includes the implicitly-prepended namespaces only if * The returned list includes the implicitly-prepended namespaces only if
* includeImplicit is true. * includeImplicit is true.
*
* NB: caller must treat the list as read-only!
*/ */
List * List *
fetch_search_path(bool includeImplicit) fetch_search_path(bool includeImplicit)
@ -1909,11 +1909,11 @@ fetch_search_path(bool includeImplicit)
recomputeNamespacePath(); recomputeNamespacePath();
result = namespaceSearchPath; result = list_copy(namespaceSearchPath);
if (!includeImplicit) if (!includeImplicit)
{ {
while (result && lfirsto(result) != firstExplicitNamespace) while (result && linitial_oid(result) != firstExplicitNamespace)
result = lnext(result); result = list_delete_first(result);
} }
return result; return result;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/pg_proc.c,v 1.115 2004/04/02 23:14:05 tgl Exp $ * $PostgreSQL: pgsql/src/backend/catalog/pg_proc.c,v 1.116 2004/05/26 04:41:08 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -374,7 +374,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList)
Query *parse; Query *parse;
int cmd; int cmd;
List *tlist; List *tlist;
List *tlistitem; ListCell *tlistitem;
int tlistlen; int tlistlen;
Oid typerelid; Oid typerelid;
Oid restype; Oid restype;
@ -396,7 +396,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList)
} }
/* find the final query */ /* find the final query */
parse = (Query *) llast(queryTreeList); parse = (Query *) lfirst(list_tail(queryTreeList));
cmd = parse->commandType; cmd = parse->commandType;
tlist = parse->targetList; tlist = parse->targetList;
@ -448,7 +448,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList)
format_type_be(rettype)), format_type_be(rettype)),
errdetail("Final SELECT must return exactly one column."))); errdetail("Final SELECT must return exactly one column.")));
restype = ((TargetEntry *) lfirst(tlist))->resdom->restype; restype = ((TargetEntry *) linitial(tlist))->resdom->restype;
if (!IsBinaryCoercible(restype, rettype)) if (!IsBinaryCoercible(restype, rettype))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
@ -471,7 +471,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList)
*/ */
if (tlistlen == 1) if (tlistlen == 1)
{ {
restype = ((TargetEntry *) lfirst(tlist))->resdom->restype; restype = ((TargetEntry *) linitial(tlist))->resdom->restype;
if (IsBinaryCoercible(restype, rettype)) if (IsBinaryCoercible(restype, rettype))
return false; /* NOT returning whole tuple */ return false; /* NOT returning whole tuple */
} }
@ -556,7 +556,7 @@ check_sql_fn_retval(Oid rettype, char fn_typtype, List *queryTreeList)
*/ */
if (tlistlen == 1) if (tlistlen == 1)
{ {
restype = ((TargetEntry *) lfirst(tlist))->resdom->restype; restype = ((TargetEntry *) linitial(tlist))->resdom->restype;
if (IsBinaryCoercible(restype, rettype)) if (IsBinaryCoercible(restype, rettype))
return false; /* NOT returning whole tuple */ return false; /* NOT returning whole tuple */
} }

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/aggregatecmds.c,v 1.17 2004/05/07 00:24:57 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/aggregatecmds.c,v 1.18 2004/05/26 04:41:09 neilc Exp $
* *
* DESCRIPTION * DESCRIPTION
* The "DefineFoo" routines take the parse tree and pick out the * The "DefineFoo" routines take the parse tree and pick out the
@ -56,7 +56,7 @@ DefineAggregate(List *names, List *parameters)
char *initval = NULL; char *initval = NULL;
Oid baseTypeId; Oid baseTypeId;
Oid transTypeId; Oid transTypeId;
List *pl; ListCell *pl;
/* Convert list of names to a name and namespace */ /* Convert list of names to a name and namespace */
aggNamespace = QualifiedNameGetCreationNamespace(names, &aggName); aggNamespace = QualifiedNameGetCreationNamespace(names, &aggName);

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/alter.c,v 1.6 2003/11/29 19:51:47 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/commands/alter.c,v 1.7 2004/05/26 04:41:09 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -41,7 +41,9 @@ ExecRenameStmt(RenameStmt *stmt)
switch (stmt->renameType) switch (stmt->renameType)
{ {
case OBJECT_AGGREGATE: case OBJECT_AGGREGATE:
RenameAggregate(stmt->object, (TypeName *) lfirst(stmt->objarg), stmt->newname); RenameAggregate(stmt->object,
(TypeName *) linitial(stmt->objarg),
stmt->newname);
break; break;
case OBJECT_CONVERSION: case OBJECT_CONVERSION:

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/analyze.c,v 1.72 2004/05/23 21:24:02 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/analyze.c,v 1.73 2004/05/26 04:41:09 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -207,9 +207,9 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt)
*/ */
if (vacstmt->va_cols != NIL) if (vacstmt->va_cols != NIL)
{ {
List *le; ListCell *le;
vacattrstats = (VacAttrStats **) palloc(length(vacstmt->va_cols) * vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
sizeof(VacAttrStats *)); sizeof(VacAttrStats *));
tcnt = 0; tcnt = 0;
foreach(le, vacstmt->va_cols) foreach(le, vacstmt->va_cols)
@ -260,7 +260,7 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt)
thisdata->tupleFract = 1.0; /* fix later if partial */ thisdata->tupleFract = 1.0; /* fix later if partial */
if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL) if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
{ {
List *indexprs = indexInfo->ii_Expressions; ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
thisdata->vacattrstats = (VacAttrStats **) thisdata->vacattrstats = (VacAttrStats **)
palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *)); palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
@ -274,10 +274,10 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt)
/* Found an index expression */ /* Found an index expression */
Node *indexkey; Node *indexkey;
if (indexprs == NIL) /* shouldn't happen */ if (indexpr_item == NULL) /* shouldn't happen */
elog(ERROR, "too few entries in indexprs list"); elog(ERROR, "too few entries in indexprs list");
indexkey = (Node *) lfirst(indexprs); indexkey = (Node *) lfirst(indexpr_item);
indexprs = lnext(indexprs); indexpr_item = lnext(indexpr_item);
/* /*
* Can't analyze if the opclass uses a storage type * Can't analyze if the opclass uses a storage type

View File

@ -7,7 +7,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/async.c,v 1.111 2004/05/23 03:50:45 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/async.c,v 1.112 2004/05/26 04:41:10 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -932,7 +932,7 @@ NotifyMyFrontEnd(char *relname, int32 listenerPID)
static bool static bool
AsyncExistsPendingNotify(const char *relname) AsyncExistsPendingNotify(const char *relname)
{ {
List *p; ListCell *p;
foreach(p, pendingNotifies) foreach(p, pendingNotifies)
{ {

View File

@ -11,7 +11,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/cluster.c,v 1.123 2004/05/08 00:34:49 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/cluster.c,v 1.124 2004/05/26 04:41:10 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -103,7 +103,7 @@ cluster(ClusterStmt *stmt)
if (stmt->indexname == NULL) if (stmt->indexname == NULL)
{ {
List *index; ListCell *index;
/* We need to find the index that has indisclustered set. */ /* We need to find the index that has indisclustered set. */
foreach(index, RelationGetIndexList(rel)) foreach(index, RelationGetIndexList(rel))
@ -111,7 +111,7 @@ cluster(ClusterStmt *stmt)
HeapTuple idxtuple; HeapTuple idxtuple;
Form_pg_index indexForm; Form_pg_index indexForm;
indexOid = lfirsto(index); indexOid = lfirst_oid(index);
idxtuple = SearchSysCache(INDEXRELID, idxtuple = SearchSysCache(INDEXRELID,
ObjectIdGetDatum(indexOid), ObjectIdGetDatum(indexOid),
0, 0, 0); 0, 0, 0);
@ -165,8 +165,8 @@ cluster(ClusterStmt *stmt)
* tables that have some index with indisclustered set. * tables that have some index with indisclustered set.
*/ */
MemoryContext cluster_context; MemoryContext cluster_context;
List *rv, List *rvs;
*rvs; ListCell *rv;
/* /*
* We cannot run this form of CLUSTER inside a user transaction * We cannot run this form of CLUSTER inside a user transaction
@ -408,7 +408,7 @@ mark_index_clustered(Relation rel, Oid indexOid)
HeapTuple indexTuple; HeapTuple indexTuple;
Form_pg_index indexForm; Form_pg_index indexForm;
Relation pg_index; Relation pg_index;
List *index; ListCell *index;
/* /*
* If the index is already marked clustered, no need to do anything. * If the index is already marked clustered, no need to do anything.
@ -438,7 +438,7 @@ mark_index_clustered(Relation rel, Oid indexOid)
foreach(index, RelationGetIndexList(rel)) foreach(index, RelationGetIndexList(rel))
{ {
Oid thisIndexOid = lfirsto(index); Oid thisIndexOid = lfirst_oid(index);
indexTuple = SearchSysCacheCopy(INDEXRELID, indexTuple = SearchSysCacheCopy(INDEXRELID,
ObjectIdGetDatum(thisIndexOid), ObjectIdGetDatum(thisIndexOid),

View File

@ -7,7 +7,7 @@
* Copyright (c) 1996-2003, PostgreSQL Global Development Group * Copyright (c) 1996-2003, PostgreSQL Global Development Group
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/comment.c,v 1.76 2004/03/08 21:35:59 momjian Exp $ * $PostgreSQL: pgsql/src/backend/commands/comment.c,v 1.77 2004/05/26 04:41:10 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -379,11 +379,11 @@ CommentAttribute(List *qualname, char *comment)
AttrNumber attnum; AttrNumber attnum;
/* Separate relname and attr name */ /* Separate relname and attr name */
nnames = length(qualname); nnames = list_length(qualname);
if (nnames < 2) /* parser messed up */ if (nnames < 2) /* parser messed up */
elog(ERROR, "must specify relation and attribute"); elog(ERROR, "must specify relation and attribute");
relname = ltruncate(nnames - 1, listCopy(qualname)); relname = list_truncate(list_copy(qualname), nnames - 1);
attrname = strVal(llast(qualname)); attrname = strVal(lfirst(list_tail(qualname)));
/* Open the containing relation to ensure it won't go away meanwhile */ /* Open the containing relation to ensure it won't go away meanwhile */
rel = makeRangeVarFromNameList(relname); rel = makeRangeVarFromNameList(relname);
@ -429,11 +429,11 @@ CommentDatabase(List *qualname, char *comment)
char *database; char *database;
Oid oid; Oid oid;
if (length(qualname) != 1) if (list_length(qualname) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("database name may not be qualified"))); errmsg("database name may not be qualified")));
database = strVal(lfirst(qualname)); database = strVal(linitial(qualname));
/* /*
* We cannot currently support cross-database comments (since other * We cannot currently support cross-database comments (since other
@ -493,11 +493,11 @@ CommentNamespace(List *qualname, char *comment)
Oid classoid; Oid classoid;
char *namespace; char *namespace;
if (length(qualname) != 1) if (list_length(qualname) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("schema name may not be qualified"))); errmsg("schema name may not be qualified")));
namespace = strVal(lfirst(qualname)); namespace = strVal(linitial(qualname));
oid = GetSysCacheOid(NAMESPACENAME, oid = GetSysCacheOid(NAMESPACENAME,
CStringGetDatum(namespace), CStringGetDatum(namespace),
@ -548,7 +548,7 @@ CommentRule(List *qualname, char *comment)
AclResult aclcheck; AclResult aclcheck;
/* Separate relname and trig name */ /* Separate relname and trig name */
nnames = length(qualname); nnames = list_length(qualname);
if (nnames == 1) if (nnames == 1)
{ {
/* Old-style: only a rule name is given */ /* Old-style: only a rule name is given */
@ -556,7 +556,7 @@ CommentRule(List *qualname, char *comment)
HeapScanDesc scanDesc; HeapScanDesc scanDesc;
ScanKeyData scanKeyData; ScanKeyData scanKeyData;
rulename = strVal(lfirst(qualname)); rulename = strVal(linitial(qualname));
/* Search pg_rewrite for such a rule */ /* Search pg_rewrite for such a rule */
ScanKeyInit(&scanKeyData, ScanKeyInit(&scanKeyData,
@ -599,8 +599,8 @@ CommentRule(List *qualname, char *comment)
{ {
/* New-style: rule and relname both provided */ /* New-style: rule and relname both provided */
Assert(nnames >= 2); Assert(nnames >= 2);
relname = ltruncate(nnames - 1, listCopy(qualname)); relname = list_truncate(list_copy(qualname), nnames - 1);
rulename = strVal(llast(qualname)); rulename = strVal(lfirst(list_tail(qualname)));
/* Open the owning relation to ensure it won't go away meanwhile */ /* Open the owning relation to ensure it won't go away meanwhile */
rel = makeRangeVarFromNameList(relname); rel = makeRangeVarFromNameList(relname);
@ -683,7 +683,7 @@ CommentType(List *typename, char *comment)
static void static void
CommentAggregate(List *aggregate, List *arguments, char *comment) CommentAggregate(List *aggregate, List *arguments, char *comment)
{ {
TypeName *aggtype = (TypeName *) lfirst(arguments); TypeName *aggtype = (TypeName *) linitial(arguments);
Oid baseoid, Oid baseoid,
oid; oid;
@ -750,7 +750,7 @@ CommentProc(List *function, List *arguments, char *comment)
static void static void
CommentOperator(List *opername, List *arguments, char *comment) CommentOperator(List *opername, List *arguments, char *comment)
{ {
TypeName *typenode1 = (TypeName *) lfirst(arguments); TypeName *typenode1 = (TypeName *) linitial(arguments);
TypeName *typenode2 = (TypeName *) lsecond(arguments); TypeName *typenode2 = (TypeName *) lsecond(arguments);
Oid oid; Oid oid;
Oid classoid; Oid classoid;
@ -794,11 +794,11 @@ CommentTrigger(List *qualname, char *comment)
Oid oid; Oid oid;
/* Separate relname and trig name */ /* Separate relname and trig name */
nnames = length(qualname); nnames = list_length(qualname);
if (nnames < 2) /* parser messed up */ if (nnames < 2) /* parser messed up */
elog(ERROR, "must specify relation and trigger"); elog(ERROR, "must specify relation and trigger");
relname = ltruncate(nnames - 1, listCopy(qualname)); relname = list_truncate(list_copy(qualname), nnames - 1);
trigname = strVal(llast(qualname)); trigname = strVal(lfirst(list_tail(qualname)));
/* Open the owning relation to ensure it won't go away meanwhile */ /* Open the owning relation to ensure it won't go away meanwhile */
rel = makeRangeVarFromNameList(relname); rel = makeRangeVarFromNameList(relname);
@ -872,11 +872,11 @@ CommentConstraint(List *qualname, char *comment)
Oid conOid = InvalidOid; Oid conOid = InvalidOid;
/* Separate relname and constraint name */ /* Separate relname and constraint name */
nnames = length(qualname); nnames = list_length(qualname);
if (nnames < 2) /* parser messed up */ if (nnames < 2) /* parser messed up */
elog(ERROR, "must specify relation and constraint"); elog(ERROR, "must specify relation and constraint");
relName = ltruncate(nnames - 1, listCopy(qualname)); relName = list_truncate(list_copy(qualname), nnames - 1);
conName = strVal(llast(qualname)); conName = strVal(lfirst(list_tail(qualname)));
/* Open the owning relation to ensure it won't go away meanwhile */ /* Open the owning relation to ensure it won't go away meanwhile */
rel = makeRangeVarFromNameList(relName); rel = makeRangeVarFromNameList(relName);
@ -985,11 +985,11 @@ CommentLanguage(List *qualname, char *comment)
Oid classoid; Oid classoid;
char *language; char *language;
if (length(qualname) != 1) if (list_length(qualname) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("language name may not be qualified"))); errmsg("language name may not be qualified")));
language = strVal(lfirst(qualname)); language = strVal(linitial(qualname));
oid = GetSysCacheOid(LANGNAME, oid = GetSysCacheOid(LANGNAME,
CStringGetDatum(language), CStringGetDatum(language),
@ -1032,8 +1032,8 @@ CommentOpClass(List *qualname, List *arguments, char *comment)
Oid classoid; Oid classoid;
HeapTuple tuple; HeapTuple tuple;
Assert(length(arguments) == 1); Assert(list_length(arguments) == 1);
amname = strVal(lfirst(arguments)); amname = strVal(linitial(arguments));
/* /*
* Get the access method's OID. * Get the access method's OID.
@ -1118,8 +1118,8 @@ CommentLargeObject(List *qualname, char *comment)
Oid classoid; Oid classoid;
Node *node; Node *node;
Assert(length(qualname) == 1); Assert(list_length(qualname) == 1);
node = (Node *) lfirst(qualname); node = (Node *) linitial(qualname);
switch (nodeTag(node)) switch (nodeTag(node))
{ {
@ -1176,11 +1176,11 @@ CommentCast(List *qualname, List *arguments, char *comment)
Oid castOid; Oid castOid;
Oid classoid; Oid classoid;
Assert(length(qualname) == 1); Assert(list_length(qualname) == 1);
sourcetype = (TypeName *) lfirst(qualname); sourcetype = (TypeName *) linitial(qualname);
Assert(IsA(sourcetype, TypeName)); Assert(IsA(sourcetype, TypeName));
Assert(length(arguments) == 1); Assert(list_length(arguments) == 1);
targettype = (TypeName *) lfirst(arguments); targettype = (TypeName *) linitial(arguments);
Assert(IsA(targettype, TypeName)); Assert(IsA(targettype, TypeName));
sourcetypeid = typenameTypeId(sourcetype); sourcetypeid = typenameTypeId(sourcetype);

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/copy.c,v 1.223 2004/04/21 00:34:18 momjian Exp $ * $PostgreSQL: pgsql/src/backend/commands/copy.c,v 1.224 2004/05/26 04:41:10 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -685,7 +685,7 @@ DoCopy(const CopyStmt *stmt)
char *filename = stmt->filename; char *filename = stmt->filename;
bool is_from = stmt->is_from; bool is_from = stmt->is_from;
bool pipe = (stmt->filename == NULL); bool pipe = (stmt->filename == NULL);
List *option; ListCell *option;
List *attnamelist = stmt->attlist; List *attnamelist = stmt->attlist;
List *attnumlist; List *attnumlist;
bool binary = false; bool binary = false;
@ -934,15 +934,15 @@ DoCopy(const CopyStmt *stmt)
{ {
TupleDesc tupDesc = RelationGetDescr(rel); TupleDesc tupDesc = RelationGetDescr(rel);
Form_pg_attribute *attr = tupDesc->attrs; Form_pg_attribute *attr = tupDesc->attrs;
List *cur; ListCell *cur;
force_quote_atts = CopyGetAttnums(rel, force_quote); force_quote_atts = CopyGetAttnums(rel, force_quote);
foreach(cur, force_quote_atts) foreach(cur, force_quote_atts)
{ {
int attnum = lfirsti(cur); int attnum = lfirst_int(cur);
if (!intMember(attnum, attnumlist)) if (!list_member_int(attnumlist, attnum))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE), (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("FORCE QUOTE column \"%s\" not referenced by COPY", errmsg("FORCE QUOTE column \"%s\" not referenced by COPY",
@ -955,7 +955,7 @@ DoCopy(const CopyStmt *stmt)
*/ */
if (force_notnull) if (force_notnull)
{ {
List *cur; ListCell *cur;
TupleDesc tupDesc = RelationGetDescr(rel); TupleDesc tupDesc = RelationGetDescr(rel);
Form_pg_attribute *attr = tupDesc->attrs; Form_pg_attribute *attr = tupDesc->attrs;
@ -963,9 +963,9 @@ DoCopy(const CopyStmt *stmt)
foreach(cur, force_notnull_atts) foreach(cur, force_notnull_atts)
{ {
int attnum = lfirsti(cur); int attnum = lfirst_int(cur);
if (!intMember(attnum, attnumlist)) if (!list_member_int(attnumlist, attnum))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE), (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY", errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY",
@ -1011,7 +1011,7 @@ DoCopy(const CopyStmt *stmt)
if (pipe) if (pipe)
{ {
if (whereToSendOutput == Remote) if (whereToSendOutput == Remote)
ReceiveCopyBegin(binary, length(attnumlist)); ReceiveCopyBegin(binary, list_length(attnumlist));
else else
copy_file = stdin; copy_file = stdin;
} }
@ -1062,7 +1062,7 @@ DoCopy(const CopyStmt *stmt)
if (pipe) if (pipe)
{ {
if (whereToSendOutput == Remote) if (whereToSendOutput == Remote)
SendCopyBegin(binary, length(attnumlist)); SendCopyBegin(binary, list_length(attnumlist));
else else
copy_file = stdout; copy_file = stdout;
} }
@ -1147,14 +1147,14 @@ CopyTo(Relation rel, List *attnumlist, bool binary, bool oids,
bool *isvarlena; bool *isvarlena;
char *string; char *string;
Snapshot mySnapshot; Snapshot mySnapshot;
List *cur; ListCell *cur;
MemoryContext oldcontext; MemoryContext oldcontext;
MemoryContext mycontext; MemoryContext mycontext;
tupDesc = rel->rd_att; tupDesc = rel->rd_att;
attr = tupDesc->attrs; attr = tupDesc->attrs;
num_phys_attrs = tupDesc->natts; num_phys_attrs = tupDesc->natts;
attr_count = length(attnumlist); attr_count = list_length(attnumlist);
/* /*
* Get info about the columns we need to process. * Get info about the columns we need to process.
@ -1167,7 +1167,7 @@ CopyTo(Relation rel, List *attnumlist, bool binary, bool oids,
force_quote = (bool *) palloc((num_phys_attrs + 1) * sizeof(bool)); force_quote = (bool *) palloc((num_phys_attrs + 1) * sizeof(bool));
foreach(cur, attnumlist) foreach(cur, attnumlist)
{ {
int attnum = lfirsti(cur); int attnum = lfirst_int(cur);
Oid out_func_oid; Oid out_func_oid;
if (binary) if (binary)
@ -1180,7 +1180,7 @@ CopyTo(Relation rel, List *attnumlist, bool binary, bool oids,
&isvarlena[attnum - 1]); &isvarlena[attnum - 1]);
fmgr_info(out_func_oid, &out_functions[attnum - 1]); fmgr_info(out_func_oid, &out_functions[attnum - 1]);
if (intMember(attnum, force_quote_atts)) if (list_member_int(force_quote_atts, attnum))
force_quote[attnum - 1] = true; force_quote[attnum - 1] = true;
else else
force_quote[attnum - 1] = false; force_quote[attnum - 1] = false;
@ -1266,7 +1266,7 @@ CopyTo(Relation rel, List *attnumlist, bool binary, bool oids,
foreach(cur, attnumlist) foreach(cur, attnumlist)
{ {
int attnum = lfirsti(cur); int attnum = lfirst_int(cur);
Datum value; Datum value;
bool isnull; bool isnull;
@ -1451,7 +1451,6 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
bool hasConstraints = false; bool hasConstraints = false;
int attnum; int attnum;
int i; int i;
List *cur;
Oid in_func_oid; Oid in_func_oid;
Datum *values; Datum *values;
char *nulls; char *nulls;
@ -1471,7 +1470,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
tupDesc = RelationGetDescr(rel); tupDesc = RelationGetDescr(rel);
attr = tupDesc->attrs; attr = tupDesc->attrs;
num_phys_attrs = tupDesc->natts; num_phys_attrs = tupDesc->natts;
attr_count = length(attnumlist); attr_count = list_length(attnumlist);
num_defaults = 0; num_defaults = 0;
/* /*
@ -1526,13 +1525,13 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
&in_func_oid, &elements[attnum - 1]); &in_func_oid, &elements[attnum - 1]);
fmgr_info(in_func_oid, &in_functions[attnum - 1]); fmgr_info(in_func_oid, &in_functions[attnum - 1]);
if (intMember(attnum, force_notnull_atts)) if (list_member_int(force_notnull_atts, attnum))
force_notnull[attnum - 1] = true; force_notnull[attnum - 1] = true;
else else
force_notnull[attnum - 1] = false; force_notnull[attnum - 1] = false;
/* Get default info if needed */ /* Get default info if needed */
if (!intMember(attnum, attnumlist)) if (!list_member_int(attnumlist, attnum))
{ {
/* attribute is NOT to be copied from input */ /* attribute is NOT to be copied from input */
/* use default value if one exists */ /* use default value if one exists */
@ -1681,6 +1680,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
{ {
CopyReadResult result = NORMAL_ATTR; CopyReadResult result = NORMAL_ATTR;
char *string; char *string;
ListCell *cur;
/* Actually read the line into memory here */ /* Actually read the line into memory here */
done = CopyReadLine(); done = CopyReadLine();
@ -1722,7 +1722,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
*/ */
foreach(cur, attnumlist) foreach(cur, attnumlist)
{ {
int attnum = lfirsti(cur); int attnum = lfirst_int(cur);
int m = attnum - 1; int m = attnum - 1;
/* /*
@ -1783,6 +1783,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
{ {
/* binary */ /* binary */
int16 fld_count; int16 fld_count;
ListCell *cur;
fld_count = CopyGetInt16(); fld_count = CopyGetInt16();
if (CopyGetEof() || fld_count == -1) if (CopyGetEof() || fld_count == -1)
@ -1815,7 +1816,7 @@ CopyFrom(Relation rel, List *attnumlist, bool binary, bool oids,
i = 0; i = 0;
foreach(cur, attnumlist) foreach(cur, attnumlist)
{ {
int attnum = lfirsti(cur); int attnum = lfirst_int(cur);
int m = attnum - 1; int m = attnum - 1;
copy_attname = NameStr(attr[m]->attname); copy_attname = NameStr(attr[m]->attname);
@ -2642,13 +2643,13 @@ CopyGetAttnums(Relation rel, List *attnamelist)
{ {
if (attr[i]->attisdropped) if (attr[i]->attisdropped)
continue; continue;
attnums = lappendi(attnums, i + 1); attnums = lappend_int(attnums, i + 1);
} }
} }
else else
{ {
/* Validate the user-supplied list and extract attnums */ /* Validate the user-supplied list and extract attnums */
List *l; ListCell *l;
foreach(l, attnamelist) foreach(l, attnamelist)
{ {
@ -2659,12 +2660,12 @@ CopyGetAttnums(Relation rel, List *attnamelist)
/* Note we disallow system columns here */ /* Note we disallow system columns here */
attnum = attnameAttNum(rel, name, false); attnum = attnameAttNum(rel, name, false);
/* Check for duplicates */ /* Check for duplicates */
if (intMember(attnum, attnums)) if (list_member_int(attnums, attnum))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_COLUMN), (errcode(ERRCODE_DUPLICATE_COLUMN),
errmsg("column \"%s\" specified more than once", errmsg("column \"%s\" specified more than once",
name))); name)));
attnums = lappendi(attnums, attnum); attnums = lappend_int(attnums, attnum);
} }
} }

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/dbcommands.c,v 1.132 2004/04/19 17:42:57 momjian Exp $ * $PostgreSQL: pgsql/src/backend/commands/dbcommands.c,v 1.133 2004/05/26 04:41:10 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -82,7 +82,7 @@ createdb(const CreatedbStmt *stmt)
char new_record_nulls[Natts_pg_database]; char new_record_nulls[Natts_pg_database];
Oid dboid; Oid dboid;
AclId datdba; AclId datdba;
List *option; ListCell *option;
DefElem *downer = NULL; DefElem *downer = NULL;
DefElem *dpath = NULL; DefElem *dpath = NULL;
DefElem *dtemplate = NULL; DefElem *dtemplate = NULL;

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/define.c,v 1.88 2004/05/14 16:11:25 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/define.c,v 1.89 2004/05/26 04:41:10 neilc Exp $
* *
* DESCRIPTION * DESCRIPTION
* The "DefineFoo" routines take the parse tree and pick out the * The "DefineFoo" routines take the parse tree and pick out the
@ -190,7 +190,7 @@ defGetQualifiedName(DefElem *def)
return (List *) def->arg; return (List *) def->arg;
case T_String: case T_String:
/* Allow quoted name for backwards compatibility */ /* Allow quoted name for backwards compatibility */
return makeList1(def->arg); return list_make1(def->arg);
default: default:
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
@ -223,7 +223,7 @@ defGetTypeName(DefElem *def)
/* Allow quoted typename for backwards compatibility */ /* Allow quoted typename for backwards compatibility */
TypeName *n = makeNode(TypeName); TypeName *n = makeNode(TypeName);
n->names = makeList1(def->arg); n->names = list_make1(def->arg);
n->typmod = -1; n->typmod = -1;
return n; return n;
} }

View File

@ -7,7 +7,7 @@
* Portions Copyright (c) 1994-5, Regents of the University of California * Portions Copyright (c) 1994-5, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/explain.c,v 1.120 2004/04/01 21:28:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/explain.c,v 1.121 2004/05/26 04:41:10 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -72,7 +72,7 @@ ExplainQuery(ExplainStmt *stmt, DestReceiver *dest)
Query *query = stmt->query; Query *query = stmt->query;
TupOutputState *tstate; TupOutputState *tstate;
List *rewritten; List *rewritten;
List *l; ListCell *l;
/* prepare for projection of tuples */ /* prepare for projection of tuples */
tstate = begin_tup_output_tupdesc(dest, ExplainResultDesc(stmt)); tstate = begin_tup_output_tupdesc(dest, ExplainResultDesc(stmt));
@ -104,7 +104,7 @@ ExplainQuery(ExplainStmt *stmt, DestReceiver *dest)
{ {
ExplainOneQuery(lfirst(l), stmt, tstate); ExplainOneQuery(lfirst(l), stmt, tstate);
/* put a blank line between plans */ /* put a blank line between plans */
if (lnext(l) != NIL) if (lnext(l) != NULL)
do_text_output_oneline(tstate, ""); do_text_output_oneline(tstate, "");
} }
} }
@ -156,9 +156,9 @@ ExplainOneQuery(Query *query, ExplainStmt *stmt, TupOutputState *tstate)
/* Still need to rewrite cursor command */ /* Still need to rewrite cursor command */
Assert(query->commandType == CMD_SELECT); Assert(query->commandType == CMD_SELECT);
rewritten = QueryRewrite(query); rewritten = QueryRewrite(query);
if (length(rewritten) != 1) if (list_length(rewritten) != 1)
elog(ERROR, "unexpected rewrite result"); elog(ERROR, "unexpected rewrite result");
query = (Query *) lfirst(rewritten); query = (Query *) linitial(rewritten);
Assert(query->commandType == CMD_SELECT); Assert(query->commandType == CMD_SELECT);
/* do not actually execute the underlying query! */ /* do not actually execute the underlying query! */
stmt->analyze = false; stmt->analyze = false;
@ -317,7 +317,7 @@ explain_outNode(StringInfo str,
Plan *outer_plan, Plan *outer_plan,
int indent, ExplainState *es) int indent, ExplainState *es)
{ {
List *l; ListCell *l;
char *pname; char *pname;
int i; int i;
@ -491,7 +491,7 @@ explain_outNode(StringInfo str,
{ {
Relation relation; Relation relation;
relation = index_open(lfirsto(l)); relation = index_open(lfirst_oid(l));
appendStringInfo(str, "%s%s", appendStringInfo(str, "%s%s",
(++i > 1) ? ", " : "", (++i > 1) ? ", " : "",
quote_identifier(RelationGetRelationName(relation))); quote_identifier(RelationGetRelationName(relation)));
@ -699,7 +699,7 @@ explain_outNode(StringInfo str,
if (plan->initPlan) if (plan->initPlan)
{ {
List *saved_rtable = es->rtable; List *saved_rtable = es->rtable;
List *lst; ListCell *lst;
for (i = 0; i < indent; i++) for (i = 0; i < indent; i++)
appendStringInfo(str, " "); appendStringInfo(str, " ");
@ -749,7 +749,7 @@ explain_outNode(StringInfo str,
{ {
Append *appendplan = (Append *) plan; Append *appendplan = (Append *) plan;
AppendState *appendstate = (AppendState *) planstate; AppendState *appendstate = (AppendState *) planstate;
List *lst; ListCell *lst;
int j; int j;
j = 0; j = 0;
@ -797,7 +797,7 @@ explain_outNode(StringInfo str,
if (planstate->subPlan) if (planstate->subPlan)
{ {
List *saved_rtable = es->rtable; List *saved_rtable = es->rtable;
List *lst; ListCell *lst;
for (i = 0; i < indent; i++) for (i = 0; i < indent; i++)
appendStringInfo(str, " "); appendStringInfo(str, " ");
@ -839,11 +839,8 @@ show_scan_qual(List *qual, bool is_or_qual, const char *qlabel,
/* No work if empty qual */ /* No work if empty qual */
if (qual == NIL) if (qual == NIL)
return; return;
if (is_or_qual) if (is_or_qual && list_length(qual) == 1 && linitial(qual) == NIL)
{
if (lfirst(qual) == NIL && lnext(qual) == NIL)
return; return;
}
/* Fix qual --- indexqual requires different processing */ /* Fix qual --- indexqual requires different processing */
if (is_or_qual) if (is_or_qual)
@ -852,7 +849,7 @@ show_scan_qual(List *qual, bool is_or_qual, const char *qlabel,
node = (Node *) make_ands_explicit(qual); node = (Node *) make_ands_explicit(qual);
/* Generate deparse context */ /* Generate deparse context */
Assert(scanrelid > 0 && scanrelid <= length(es->rtable)); Assert(scanrelid > 0 && scanrelid <= list_length(es->rtable));
rte = rt_fetch(scanrelid, es->rtable); rte = rt_fetch(scanrelid, es->rtable);
scancontext = deparse_context_for_rte(rte); scancontext = deparse_context_for_rte(rte);
@ -984,7 +981,7 @@ show_sort_keys(List *tlist, int nkeys, AttrNumber *keycols,
context = deparse_context_for_plan(0, NULL, context = deparse_context_for_plan(0, NULL,
0, NULL, 0, NULL,
es->rtable); es->rtable);
useprefix = length(es->rtable) > 1; useprefix = list_length(es->rtable) > 1;
} }
bms_free(varnos); bms_free(varnos);
@ -1017,17 +1014,16 @@ make_ors_ands_explicit(List *orclauses)
{ {
if (orclauses == NIL) if (orclauses == NIL)
return NULL; /* probably can't happen */ return NULL; /* probably can't happen */
else if (lnext(orclauses) == NIL) else if (list_length(orclauses) == 1)
return (Node *) make_ands_explicit(lfirst(orclauses)); return (Node *) make_ands_explicit(linitial(orclauses));
else else
{ {
FastList args; List *args = NIL;
List *orptr; ListCell *orptr;
FastListInit(&args);
foreach(orptr, orclauses) foreach(orptr, orclauses)
FastAppend(&args, make_ands_explicit(lfirst(orptr))); args = lappend(args, make_ands_explicit(lfirst(orptr)));
return (Node *) make_orclause(FastListValue(&args)); return (Node *) make_orclause(args);
} }
} }

View File

@ -10,7 +10,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/functioncmds.c,v 1.46 2004/05/14 16:11:25 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/functioncmds.c,v 1.47 2004/05/26 04:41:11 neilc Exp $
* *
* DESCRIPTION * DESCRIPTION
* These routines take the parse tree and pick out the * These routines take the parse tree and pick out the
@ -137,7 +137,7 @@ examine_parameter_list(List *parameter, Oid languageOid,
Oid *parameterTypes, const char *parameterNames[]) Oid *parameterTypes, const char *parameterNames[])
{ {
int parameterCount = 0; int parameterCount = 0;
List *x; ListCell *x;
MemSet(parameterTypes, 0, FUNC_MAX_ARGS * sizeof(Oid)); MemSet(parameterTypes, 0, FUNC_MAX_ARGS * sizeof(Oid));
MemSet(parameterNames, 0, FUNC_MAX_ARGS * sizeof(char *)); MemSet(parameterNames, 0, FUNC_MAX_ARGS * sizeof(char *));
@ -202,14 +202,14 @@ examine_parameter_list(List *parameter, Oid languageOid,
*/ */
static void static void
compute_attributes_sql_style(const List *options, compute_attributes_sql_style(List *options,
List **as, List **as,
char **language, char **language,
char *volatility_p, char *volatility_p,
bool *strict_p, bool *strict_p,
bool *security_definer) bool *security_definer)
{ {
const List *option; ListCell *option;
DefElem *as_item = NULL; DefElem *as_item = NULL;
DefElem *language_item = NULL; DefElem *language_item = NULL;
DefElem *volatility_item = NULL; DefElem *volatility_item = NULL;
@ -322,7 +322,7 @@ compute_attributes_sql_style(const List *options,
static void static void
compute_attributes_with_style(List *parameters, bool *isStrict_p, char *volatility_p) compute_attributes_with_style(List *parameters, bool *isStrict_p, char *volatility_p)
{ {
List *pl; ListCell *pl;
foreach(pl, parameters) foreach(pl, parameters)
{ {
@ -357,7 +357,7 @@ compute_attributes_with_style(List *parameters, bool *isStrict_p, char *volatili
*/ */
static void static void
interpret_AS_clause(Oid languageOid, const char *languageName, const List *as, interpret_AS_clause(Oid languageOid, const char *languageName, List *as,
char **prosrc_str_p, char **probin_str_p) char **prosrc_str_p, char **probin_str_p)
{ {
Assert(as != NIL); Assert(as != NIL);
@ -368,8 +368,8 @@ interpret_AS_clause(Oid languageOid, const char *languageName, const List *as,
* For "C" language, store the file name in probin and, when * For "C" language, store the file name in probin and, when
* given, the link symbol name in prosrc. * given, the link symbol name in prosrc.
*/ */
*probin_str_p = strVal(lfirst(as)); *probin_str_p = strVal(linitial(as));
if (lnext(as) == NULL) if (list_length(as) == 1)
*prosrc_str_p = "-"; *prosrc_str_p = "-";
else else
*prosrc_str_p = strVal(lsecond(as)); *prosrc_str_p = strVal(lsecond(as));
@ -377,10 +377,10 @@ interpret_AS_clause(Oid languageOid, const char *languageName, const List *as,
else else
{ {
/* Everything else wants the given string in prosrc. */ /* Everything else wants the given string in prosrc. */
*prosrc_str_p = strVal(lfirst(as)); *prosrc_str_p = strVal(linitial(as));
*probin_str_p = "-"; *probin_str_p = "-";
if (lnext(as) != NIL) if (list_length(as) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("only one AS item needed for language \"%s\"", errmsg("only one AS item needed for language \"%s\"",

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/indexcmds.c,v 1.119 2004/05/08 00:34:49 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/indexcmds.c,v 1.120 2004/05/26 04:41:11 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -109,7 +109,7 @@ DefineIndex(RangeVar *heapRelation,
/* /*
* count attributes in index * count attributes in index
*/ */
numberOfAttributes = length(attributeList); numberOfAttributes = list_length(attributeList);
if (numberOfAttributes <= 0) if (numberOfAttributes <= 0)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
@ -165,7 +165,7 @@ DefineIndex(RangeVar *heapRelation,
namespaceId); namespaceId);
else else
{ {
IndexElem *iparam = (IndexElem *) lfirst(attributeList); IndexElem *iparam = (IndexElem *) linitial(attributeList);
indexRelationName = CreateIndexName(RelationGetRelationName(rel), indexRelationName = CreateIndexName(RelationGetRelationName(rel),
iparam->name, iparam->name,
@ -208,7 +208,7 @@ DefineIndex(RangeVar *heapRelation,
*/ */
if (rangetable != NIL) if (rangetable != NIL)
{ {
if (length(rangetable) != 1 || getrelid(1, rangetable) != relationId) if (list_length(rangetable) != 1 || getrelid(1, rangetable) != relationId)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE), (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("index expressions and predicates may refer only to the table being indexed"))); errmsg("index expressions and predicates may refer only to the table being indexed")));
@ -226,7 +226,7 @@ DefineIndex(RangeVar *heapRelation,
if (primary) if (primary)
{ {
List *cmds; List *cmds;
List *keys; ListCell *keys;
/* /*
* If ALTER TABLE, check that there isn't already a PRIMARY KEY. * If ALTER TABLE, check that there isn't already a PRIMARY KEY.
@ -399,7 +399,7 @@ ComputeIndexAttrs(IndexInfo *indexInfo,
Oid accessMethodId, Oid accessMethodId,
bool isconstraint) bool isconstraint)
{ {
List *rest; ListCell *rest;
int attn = 0; int attn = 0;
/* /*
@ -516,9 +516,9 @@ GetIndexOpClass(List *opclass, Oid attrType,
* Release 7.5 removes bigbox_ops (which was dead code for a long while * Release 7.5 removes bigbox_ops (which was dead code for a long while
* anyway). tgl 2003/11/11 * anyway). tgl 2003/11/11
*/ */
if (length(opclass) == 1) if (list_length(opclass) == 1)
{ {
char *claname = strVal(lfirst(opclass)); char *claname = strVal(linitial(opclass));
if (strcmp(claname, "network_ops") == 0 || if (strcmp(claname, "network_ops") == 0 ||
strcmp(claname, "timespan_ops") == 0 || strcmp(claname, "timespan_ops") == 0 ||
@ -697,8 +697,8 @@ static bool
relationHasPrimaryKey(Relation rel) relationHasPrimaryKey(Relation rel)
{ {
bool result = false; bool result = false;
List *indexoidlist, List *indexoidlist;
*indexoidscan; ListCell *indexoidscan;
/* /*
* Get the list of index OIDs for the table from the relcache, and * Get the list of index OIDs for the table from the relcache, and
@ -709,7 +709,7 @@ relationHasPrimaryKey(Relation rel)
foreach(indexoidscan, indexoidlist) foreach(indexoidscan, indexoidlist)
{ {
Oid indexoid = lfirsto(indexoidscan); Oid indexoid = lfirst_oid(indexoidscan);
HeapTuple indexTuple; HeapTuple indexTuple;
indexTuple = SearchSysCache(INDEXRELID, indexTuple = SearchSysCache(INDEXRELID,
@ -723,7 +723,7 @@ relationHasPrimaryKey(Relation rel)
break; break;
} }
freeList(indexoidlist); list_free(indexoidlist);
return result; return result;
} }
@ -849,6 +849,7 @@ ReindexDatabase(const char *dbname, bool force /* currently unused */,
MemoryContext private_context; MemoryContext private_context;
MemoryContext old; MemoryContext old;
List *relids = NIL; List *relids = NIL;
ListCell *l;
AssertArg(dbname); AssertArg(dbname);
@ -887,7 +888,7 @@ ReindexDatabase(const char *dbname, bool force /* currently unused */,
* reindexing itself will try to update pg_class. * reindexing itself will try to update pg_class.
*/ */
old = MemoryContextSwitchTo(private_context); old = MemoryContextSwitchTo(private_context);
relids = lappendo(relids, RelOid_pg_class); relids = lappend_oid(relids, RelOid_pg_class);
MemoryContextSwitchTo(old); MemoryContextSwitchTo(old);
/* /*
@ -921,7 +922,7 @@ ReindexDatabase(const char *dbname, bool force /* currently unused */,
continue; /* got it already */ continue; /* got it already */
old = MemoryContextSwitchTo(private_context); old = MemoryContextSwitchTo(private_context);
relids = lappendo(relids, HeapTupleGetOid(tuple)); relids = lappend_oid(relids, HeapTupleGetOid(tuple));
MemoryContextSwitchTo(old); MemoryContextSwitchTo(old);
} }
heap_endscan(scan); heap_endscan(scan);
@ -929,9 +930,9 @@ ReindexDatabase(const char *dbname, bool force /* currently unused */,
/* Now reindex each rel in a separate transaction */ /* Now reindex each rel in a separate transaction */
CommitTransactionCommand(); CommitTransactionCommand();
while (relids) foreach(l, relids)
{ {
Oid relid = lfirsto(relids); Oid relid = lfirst_oid(l);
StartTransactionCommand(); StartTransactionCommand();
SetQuerySnapshot(); /* might be needed for functions in SetQuerySnapshot(); /* might be needed for functions in
@ -941,7 +942,6 @@ ReindexDatabase(const char *dbname, bool force /* currently unused */,
(errmsg("table \"%s\" was reindexed", (errmsg("table \"%s\" was reindexed",
get_rel_name(relid)))); get_rel_name(relid))));
CommitTransactionCommand(); CommitTransactionCommand();
relids = lnext(relids);
} }
StartTransactionCommand(); StartTransactionCommand();

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/lockcmds.c,v 1.9 2004/03/11 01:47:35 ishii Exp $ * $PostgreSQL: pgsql/src/backend/commands/lockcmds.c,v 1.10 2004/05/26 04:41:11 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -28,7 +28,7 @@
void void
LockTableCommand(LockStmt *lockstmt) LockTableCommand(LockStmt *lockstmt)
{ {
List *p; ListCell *p;
/* /*
* Iterate over the list and open, lock, and close the relations one * Iterate over the list and open, lock, and close the relations one

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/opclasscmds.c,v 1.24 2003/11/29 19:51:47 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/commands/opclasscmds.c,v 1.25 2004/05/26 04:41:11 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -77,7 +77,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
numProcs; /* amsupport value */ numProcs; /* amsupport value */
List *operators; /* OpClassMember list for operators */ List *operators; /* OpClassMember list for operators */
List *procedures; /* OpClassMember list for support procs */ List *procedures; /* OpClassMember list for support procs */
List *l; ListCell *l;
Relation rel; Relation rel;
HeapTuple tup; HeapTuple tup;
Datum values[Natts_pg_opclass]; Datum values[Natts_pg_opclass];
@ -168,7 +168,7 @@ DefineOpClass(CreateOpClassStmt *stmt)
item->number, numOperators))); item->number, numOperators)));
if (item->args != NIL) if (item->args != NIL)
{ {
TypeName *typeName1 = (TypeName *) lfirst(item->args); TypeName *typeName1 = (TypeName *) linitial(item->args);
TypeName *typeName2 = (TypeName *) lsecond(item->args); TypeName *typeName2 = (TypeName *) lsecond(item->args);
operOid = LookupOperNameTypeNames(item->name, operOid = LookupOperNameTypeNames(item->name,
@ -506,7 +506,7 @@ assignProcSubtype(Oid amoid, Oid typeoid, Oid procOid)
static void static void
addClassMember(List **list, OpClassMember *member, bool isProc) addClassMember(List **list, OpClassMember *member, bool isProc)
{ {
List *l; ListCell *l;
foreach(l, *list) foreach(l, *list)
{ {
@ -540,7 +540,7 @@ storeOperators(Oid opclassoid, List *operators)
Datum values[Natts_pg_amop]; Datum values[Natts_pg_amop];
char nulls[Natts_pg_amop]; char nulls[Natts_pg_amop];
HeapTuple tup; HeapTuple tup;
List *l; ListCell *l;
int i; int i;
rel = heap_openr(AccessMethodOperatorRelationName, RowExclusiveLock); rel = heap_openr(AccessMethodOperatorRelationName, RowExclusiveLock);
@ -584,7 +584,7 @@ storeProcedures(Oid opclassoid, List *procedures)
Datum values[Natts_pg_amproc]; Datum values[Natts_pg_amproc];
char nulls[Natts_pg_amproc]; char nulls[Natts_pg_amproc];
HeapTuple tup; HeapTuple tup;
List *l; ListCell *l;
int i; int i;
rel = heap_openr(AccessMethodProcedureRelationName, RowExclusiveLock); rel = heap_openr(AccessMethodProcedureRelationName, RowExclusiveLock);

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/operatorcmds.c,v 1.15 2004/05/14 16:11:25 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/operatorcmds.c,v 1.16 2004/05/26 04:41:11 neilc Exp $
* *
* DESCRIPTION * DESCRIPTION
* The "DefineFoo" routines take the parse tree and pick out the * The "DefineFoo" routines take the parse tree and pick out the
@ -79,7 +79,7 @@ DefineOperator(List *names, List *parameters)
List *rightSortName = NIL; /* optional right sort operator */ List *rightSortName = NIL; /* optional right sort operator */
List *ltCompareName = NIL; /* optional < compare operator */ List *ltCompareName = NIL; /* optional < compare operator */
List *gtCompareName = NIL; /* optional > compare operator */ List *gtCompareName = NIL; /* optional > compare operator */
List *pl; ListCell *pl;
/* Convert list of names to a name and namespace */ /* Convert list of names to a name and namespace */
oprNamespace = QualifiedNameGetCreationNamespace(names, &oprName); oprNamespace = QualifiedNameGetCreationNamespace(names, &oprName);
@ -167,13 +167,13 @@ DefineOperator(List *names, List *parameters)
if (canMerge) if (canMerge)
{ {
if (!leftSortName) if (!leftSortName)
leftSortName = makeList1(makeString("<")); leftSortName = list_make1(makeString("<"));
if (!rightSortName) if (!rightSortName)
rightSortName = makeList1(makeString("<")); rightSortName = list_make1(makeString("<"));
if (!ltCompareName) if (!ltCompareName)
ltCompareName = makeList1(makeString("<")); ltCompareName = list_make1(makeString("<"));
if (!gtCompareName) if (!gtCompareName)
gtCompareName = makeList1(makeString(">")); gtCompareName = list_make1(makeString(">"));
} }
/* /*
@ -206,7 +206,7 @@ void
RemoveOperator(RemoveOperStmt *stmt) RemoveOperator(RemoveOperStmt *stmt)
{ {
List *operatorName = stmt->opname; List *operatorName = stmt->opname;
TypeName *typeName1 = (TypeName *) lfirst(stmt->args); TypeName *typeName1 = (TypeName *) linitial(stmt->args);
TypeName *typeName2 = (TypeName *) lsecond(stmt->args); TypeName *typeName2 = (TypeName *) lsecond(stmt->args);
Oid operOid; Oid operOid;
HeapTuple tup; HeapTuple tup;

View File

@ -14,7 +14,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/portalcmds.c,v 1.26 2004/03/21 22:29:10 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/portalcmds.c,v 1.27 2004/05/26 04:41:11 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -68,9 +68,9 @@ PerformCursorOpen(DeclareCursorStmt *stmt)
* strange. * strange.
*/ */
rewritten = QueryRewrite((Query *) stmt->query); rewritten = QueryRewrite((Query *) stmt->query);
if (length(rewritten) != 1 || !IsA(lfirst(rewritten), Query)) if (list_length(rewritten) != 1 || !IsA(linitial(rewritten), Query))
elog(ERROR, "unexpected rewrite result"); elog(ERROR, "unexpected rewrite result");
query = (Query *) lfirst(rewritten); query = (Query *) linitial(rewritten);
if (query->commandType != CMD_SELECT) if (query->commandType != CMD_SELECT)
elog(ERROR, "unexpected rewrite result"); elog(ERROR, "unexpected rewrite result");
@ -100,8 +100,8 @@ PerformCursorOpen(DeclareCursorStmt *stmt)
PortalDefineQuery(portal, PortalDefineQuery(portal,
NULL, /* unfortunately don't have sourceText */ NULL, /* unfortunately don't have sourceText */
"SELECT", /* cursor's query is always a SELECT */ "SELECT", /* cursor's query is always a SELECT */
makeList1(query), list_make1(query),
makeList1(plan), list_make1(plan),
PortalGetHeapMemory(portal)); PortalGetHeapMemory(portal));
MemoryContextSwitchTo(oldContext); MemoryContextSwitchTo(oldContext);

View File

@ -10,7 +10,7 @@
* Copyright (c) 2002-2003, PostgreSQL Global Development Group * Copyright (c) 2002-2003, PostgreSQL Global Development Group
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/prepare.c,v 1.26 2004/04/22 02:58:20 momjian Exp $ * $PostgreSQL: pgsql/src/backend/commands/prepare.c,v 1.27 2004/05/26 04:41:11 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -125,7 +125,7 @@ ExecuteQuery(ExecuteStmt *stmt, DestReceiver *dest, char *completionTag)
plan_list = entry->plan_list; plan_list = entry->plan_list;
qcontext = entry->context; qcontext = entry->context;
Assert(length(query_list) == length(plan_list)); Assert(list_length(query_list) == list_length(plan_list));
/* Evaluate parameters, if any */ /* Evaluate parameters, if any */
if (entry->argtype_list != NIL) if (entry->argtype_list != NIL)
@ -162,11 +162,11 @@ ExecuteQuery(ExecuteStmt *stmt, DestReceiver *dest, char *completionTag)
plan_list = copyObject(plan_list); plan_list = copyObject(plan_list);
qcontext = PortalGetHeapMemory(portal); qcontext = PortalGetHeapMemory(portal);
if (length(query_list) != 1) if (list_length(query_list) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("prepared statement is not a SELECT"))); errmsg("prepared statement is not a SELECT")));
query = (Query *) lfirst(query_list); query = (Query *) linitial(query_list);
if (query->commandType != CMD_SELECT) if (query->commandType != CMD_SELECT)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
@ -208,14 +208,14 @@ ExecuteQuery(ExecuteStmt *stmt, DestReceiver *dest, char *completionTag)
static ParamListInfo static ParamListInfo
EvaluateParams(EState *estate, List *params, List *argtypes) EvaluateParams(EState *estate, List *params, List *argtypes)
{ {
int nargs = length(argtypes); int nargs = list_length(argtypes);
ParamListInfo paramLI; ParamListInfo paramLI;
List *exprstates; List *exprstates;
List *l; ListCell *l;
int i = 0; int i = 0;
/* Parser should have caught this error, but check for safety */ /* Parser should have caught this error, but check for safety */
if (length(params) != nargs) if (list_length(params) != nargs)
elog(ERROR, "wrong number of arguments"); elog(ERROR, "wrong number of arguments");
exprstates = (List *) ExecPrepareExpr((Expr *) params, estate); exprstates = (List *) ExecPrepareExpr((Expr *) params, estate);
@ -326,7 +326,7 @@ StorePreparedStatement(const char *stmt_name,
qstring = query_string ? pstrdup(query_string) : NULL; qstring = query_string ? pstrdup(query_string) : NULL;
query_list = (List *) copyObject(query_list); query_list = (List *) copyObject(query_list);
plan_list = (List *) copyObject(plan_list); plan_list = (List *) copyObject(plan_list);
argtype_list = listCopy(argtype_list); argtype_list = list_copy(argtype_list);
/* Now we can add entry to hash table */ /* Now we can add entry to hash table */
entry = (PreparedStatement *) hash_search(prepared_queries, entry = (PreparedStatement *) hash_search(prepared_queries,
@ -419,11 +419,11 @@ FetchPreparedStatementResultDesc(PreparedStatement *stmt)
switch (ChoosePortalStrategy(stmt->query_list)) switch (ChoosePortalStrategy(stmt->query_list))
{ {
case PORTAL_ONE_SELECT: case PORTAL_ONE_SELECT:
query = (Query *) lfirst(stmt->query_list); query = (Query *) linitial(stmt->query_list);
return ExecCleanTypeFromTL(query->targetList, false); return ExecCleanTypeFromTL(query->targetList, false);
case PORTAL_UTIL_SELECT: case PORTAL_UTIL_SELECT:
query = (Query *) lfirst(stmt->query_list); query = (Query *) linitial(stmt->query_list);
return UtilityTupleDescriptor(query->utilityStmt); return UtilityTupleDescriptor(query->utilityStmt);
case PORTAL_MULTI_QUERY: case PORTAL_MULTI_QUERY:
@ -478,8 +478,9 @@ ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate)
{ {
ExecuteStmt *execstmt = (ExecuteStmt *) stmt->query->utilityStmt; ExecuteStmt *execstmt = (ExecuteStmt *) stmt->query->utilityStmt;
PreparedStatement *entry; PreparedStatement *entry;
List *l, ListCell *q,
*query_list, *p;
List *query_list,
*plan_list; *plan_list;
ParamListInfo paramLI = NULL; ParamListInfo paramLI = NULL;
EState *estate = NULL; EState *estate = NULL;
@ -493,7 +494,7 @@ ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate)
query_list = entry->query_list; query_list = entry->query_list;
plan_list = entry->plan_list; plan_list = entry->plan_list;
Assert(length(query_list) == length(plan_list)); Assert(list_length(query_list) == list_length(plan_list));
/* Evaluate parameters, if any */ /* Evaluate parameters, if any */
if (entry->argtype_list != NIL) if (entry->argtype_list != NIL)
@ -508,14 +509,13 @@ ExplainExecuteQuery(ExplainStmt *stmt, TupOutputState *tstate)
} }
/* Explain each query */ /* Explain each query */
foreach(l, query_list) forboth (q, query_list, p, plan_list)
{ {
Query *query = (Query *) lfirst(l); Query *query = (Query *) lfirst(q);
Plan *plan = (Plan *) lfirst(plan_list); Plan *plan = (Plan *) lfirst(p);
bool is_last_query; bool is_last_query;
plan_list = lnext(plan_list); is_last_query = (lnext(p) == NULL);
is_last_query = (plan_list == NIL);
if (query->commandType == CMD_UTILITY) if (query->commandType == CMD_UTILITY)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/schemacmds.c,v 1.17 2003/11/29 19:51:47 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/commands/schemacmds.c,v 1.18 2004/05/26 04:41:11 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -42,7 +42,7 @@ CreateSchemaCommand(CreateSchemaStmt *stmt)
const char *authId = stmt->authid; const char *authId = stmt->authid;
Oid namespaceId; Oid namespaceId;
List *parsetree_list; List *parsetree_list;
List *parsetree_item; ListCell *parsetree_item;
const char *owner_name; const char *owner_name;
AclId owner_userid; AclId owner_userid;
AclId saved_userid; AclId saved_userid;
@ -129,8 +129,8 @@ CreateSchemaCommand(CreateSchemaStmt *stmt)
foreach(parsetree_item, parsetree_list) foreach(parsetree_item, parsetree_list)
{ {
Node *parsetree = (Node *) lfirst(parsetree_item); Node *parsetree = (Node *) lfirst(parsetree_item);
List *querytree_list, List *querytree_list;
*querytree_item; ListCell *querytree_item;
querytree_list = parse_analyze(parsetree, NULL, 0); querytree_list = parse_analyze(parsetree, NULL, 0);
@ -166,11 +166,11 @@ RemoveSchema(List *names, DropBehavior behavior)
Oid namespaceId; Oid namespaceId;
ObjectAddress object; ObjectAddress object;
if (length(names) != 1) if (list_length(names) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("schema name may not be qualified"))); errmsg("schema name may not be qualified")));
namespaceName = strVal(lfirst(names)); namespaceName = strVal(linitial(names));
namespaceId = GetSysCacheOid(NAMESPACENAME, namespaceId = GetSysCacheOid(NAMESPACENAME,
CStringGetDatum(namespaceName), CStringGetDatum(namespaceName),

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/sequence.c,v 1.110 2004/05/08 19:09:24 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/sequence.c,v 1.111 2004/05/26 04:41:11 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -862,7 +862,7 @@ init_params(List *options, Form_pg_sequence new, bool isInit)
DefElem *min_value = NULL; DefElem *min_value = NULL;
DefElem *cache_value = NULL; DefElem *cache_value = NULL;
DefElem *is_cycled = NULL; DefElem *is_cycled = NULL;
List *option; ListCell *option;
foreach(option, options) foreach(option, options)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.107 2004/05/08 22:46:29 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.108 2004/05/26 04:41:12 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -262,7 +262,7 @@ DefineRelation(CreateStmt *stmt, char relkind)
bool localHasOids; bool localHasOids;
int parentOidCount; int parentOidCount;
List *rawDefaults; List *rawDefaults;
List *listptr; ListCell *listptr;
int i; int i;
AttrNumber attnum; AttrNumber attnum;
@ -320,7 +320,7 @@ DefineRelation(CreateStmt *stmt, char relkind)
if (old_constraints != NIL) if (old_constraints != NIL)
{ {
ConstrCheck *check = (ConstrCheck *) palloc(length(old_constraints) * ConstrCheck *check = (ConstrCheck *) palloc(list_length(old_constraints) *
sizeof(ConstrCheck)); sizeof(ConstrCheck));
int ncheck = 0; int ncheck = 0;
int constr_name_ctr = 0; int constr_name_ctr = 0;
@ -634,7 +634,7 @@ static List *
MergeAttributes(List *schema, List *supers, bool istemp, MergeAttributes(List *schema, List *supers, bool istemp,
List **supOids, List **supconstr, int *supOidCount) List **supOids, List **supconstr, int *supOidCount)
{ {
List *entry; ListCell *entry;
List *inhSchema = NIL; List *inhSchema = NIL;
List *parentOids = NIL; List *parentOids = NIL;
List *constraints = NIL; List *constraints = NIL;
@ -654,9 +654,9 @@ MergeAttributes(List *schema, List *supers, bool istemp,
foreach(entry, schema) foreach(entry, schema)
{ {
ColumnDef *coldef = lfirst(entry); ColumnDef *coldef = lfirst(entry);
List *rest; ListCell *rest;
foreach(rest, lnext(entry)) for_each_cell(rest, lnext(entry))
{ {
ColumnDef *restdef = lfirst(rest); ColumnDef *restdef = lfirst(rest);
@ -708,13 +708,13 @@ MergeAttributes(List *schema, List *supers, bool istemp,
/* /*
* Reject duplications in the list of parents. * Reject duplications in the list of parents.
*/ */
if (oidMember(RelationGetRelid(relation), parentOids)) if (list_member_oid(parentOids, RelationGetRelid(relation)))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_TABLE), (errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("inherited relation \"%s\" duplicated", errmsg("inherited relation \"%s\" duplicated",
parent->relname))); parent->relname)));
parentOids = lappendo(parentOids, RelationGetRelid(relation)); parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
if (relation->rd_rel->relhasoids) if (relation->rd_rel->relhasoids)
parentsWithOids++; parentsWithOids++;
@ -767,7 +767,7 @@ MergeAttributes(List *schema, List *supers, bool istemp,
ereport(NOTICE, ereport(NOTICE,
(errmsg("merging multiple inherited definitions of column \"%s\"", (errmsg("merging multiple inherited definitions of column \"%s\"",
attributeName))); attributeName)));
def = (ColumnDef *) nth(exist_attno - 1, inhSchema); def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
if (typenameTypeId(def->typename) != attribute->atttypid || if (typenameTypeId(def->typename) != attribute->atttypid ||
def->typename->typmod != attribute->atttypmod) def->typename->typmod != attribute->atttypmod)
ereport(ERROR, ereport(ERROR,
@ -922,7 +922,7 @@ MergeAttributes(List *schema, List *supers, bool istemp,
ereport(NOTICE, ereport(NOTICE,
(errmsg("merging column \"%s\" with inherited definition", (errmsg("merging column \"%s\" with inherited definition",
attributeName))); attributeName)));
def = (ColumnDef *) nth(exist_attno - 1, inhSchema); def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
if (typenameTypeId(def->typename) != typenameTypeId(newdef->typename) || if (typenameTypeId(def->typename) != typenameTypeId(newdef->typename) ||
def->typename->typmod != newdef->typename->typmod) def->typename->typmod != newdef->typename->typmod)
ereport(ERROR, ereport(ERROR,
@ -1033,7 +1033,7 @@ StoreCatalogInheritance(Oid relationId, List *supers)
Relation relation; Relation relation;
TupleDesc desc; TupleDesc desc;
int16 seqNumber; int16 seqNumber;
List *entry; ListCell *entry;
HeapTuple tuple; HeapTuple tuple;
/* /*
@ -1059,7 +1059,7 @@ StoreCatalogInheritance(Oid relationId, List *supers)
seqNumber = 1; seqNumber = 1;
foreach(entry, supers) foreach(entry, supers)
{ {
Oid parentOid = lfirsto(entry); Oid parentOid = lfirst_oid(entry);
Datum datum[Natts_pg_inherits]; Datum datum[Natts_pg_inherits];
char nullarr[Natts_pg_inherits]; char nullarr[Natts_pg_inherits];
ObjectAddress childobject, ObjectAddress childobject,
@ -1113,16 +1113,17 @@ StoreCatalogInheritance(Oid relationId, List *supers)
static int static int
findAttrByName(const char *attributeName, List *schema) findAttrByName(const char *attributeName, List *schema)
{ {
List *s; ListCell *s;
int i = 0; int i = 1;
foreach(s, schema) foreach(s, schema)
{ {
ColumnDef *def = lfirst(s); ColumnDef *def = lfirst(s);
++i;
if (strcmp(attributeName, def->colname) == 0) if (strcmp(attributeName, def->colname) == 0)
return i; return i;
i++;
} }
return 0; return 0;
} }
@ -1198,7 +1199,7 @@ renameatt(Oid myrelid,
Form_pg_attribute attform; Form_pg_attribute attform;
int attnum; int attnum;
List *indexoidlist; List *indexoidlist;
List *indexoidscan; ListCell *indexoidscan;
/* /*
* Grab an exclusive lock on the target table, which we will NOT * Grab an exclusive lock on the target table, which we will NOT
@ -1232,8 +1233,8 @@ renameatt(Oid myrelid,
*/ */
if (recurse) if (recurse)
{ {
List *child, ListCell *child;
*children; List *children;
/* this routine is actually in the planner */ /* this routine is actually in the planner */
children = find_all_inheritors(myrelid); children = find_all_inheritors(myrelid);
@ -1245,7 +1246,7 @@ renameatt(Oid myrelid,
*/ */
foreach(child, children) foreach(child, children)
{ {
Oid childrelid = lfirsto(child); Oid childrelid = lfirst_oid(child);
if (childrelid == myrelid) if (childrelid == myrelid)
continue; continue;
@ -1322,7 +1323,7 @@ renameatt(Oid myrelid,
foreach(indexoidscan, indexoidlist) foreach(indexoidscan, indexoidlist)
{ {
Oid indexoid = lfirsto(indexoidscan); Oid indexoid = lfirst_oid(indexoidscan);
HeapTuple indextup; HeapTuple indextup;
Form_pg_index indexform; Form_pg_index indexform;
int i; int i;
@ -1370,7 +1371,7 @@ renameatt(Oid myrelid,
ReleaseSysCache(indextup); ReleaseSysCache(indextup);
} }
freeList(indexoidlist); list_free(indexoidlist);
heap_close(attrelation, RowExclusiveLock); heap_close(attrelation, RowExclusiveLock);
@ -1765,7 +1766,7 @@ static void
ATController(Relation rel, List *cmds, bool recurse) ATController(Relation rel, List *cmds, bool recurse)
{ {
List *wqueue = NIL; List *wqueue = NIL;
List *lcmd; ListCell *lcmd;
/* Phase 1: preliminary examination of commands, create work queue */ /* Phase 1: preliminary examination of commands, create work queue */
foreach(lcmd, cmds) foreach(lcmd, cmds)
@ -1962,7 +1963,7 @@ static void
ATRewriteCatalogs(List **wqueue) ATRewriteCatalogs(List **wqueue)
{ {
int pass; int pass;
List *ltab; ListCell *ltab;
/* /*
* We process all the tables "in parallel", one pass at a time. This * We process all the tables "in parallel", one pass at a time. This
@ -1979,7 +1980,7 @@ ATRewriteCatalogs(List **wqueue)
AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab); AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
List *subcmds = tab->subcmds[pass]; List *subcmds = tab->subcmds[pass];
Relation rel; Relation rel;
List *lcmd; ListCell *lcmd;
if (subcmds == NIL) if (subcmds == NIL)
continue; continue;
@ -2107,7 +2108,7 @@ ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd)
static void static void
ATRewriteTables(List **wqueue) ATRewriteTables(List **wqueue)
{ {
List *ltab; ListCell *ltab;
/* Go through each table that needs to be checked or rewritten */ /* Go through each table that needs to be checked or rewritten */
foreach(ltab, *wqueue) foreach(ltab, *wqueue)
@ -2215,7 +2216,7 @@ ATRewriteTables(List **wqueue)
{ {
AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab); AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
Relation rel = NULL; Relation rel = NULL;
List *lcon; ListCell *lcon;
foreach(lcon, tab->constraints) foreach(lcon, tab->constraints)
{ {
@ -2259,7 +2260,7 @@ ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
TupleDesc newTupDesc; TupleDesc newTupDesc;
bool needscan = false; bool needscan = false;
int i; int i;
List *l; ListCell *l;
EState *estate; EState *estate;
/* /*
@ -2473,7 +2474,7 @@ ATGetQueueEntry(List **wqueue, Relation rel)
{ {
Oid relid = RelationGetRelid(rel); Oid relid = RelationGetRelid(rel);
AlteredTableInfo *tab; AlteredTableInfo *tab;
List *ltab; ListCell *ltab;
foreach(ltab, *wqueue) foreach(ltab, *wqueue)
{ {
@ -2554,8 +2555,8 @@ ATSimpleRecursion(List **wqueue, Relation rel,
if (recurse && rel->rd_rel->relkind == RELKIND_RELATION) if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
{ {
Oid relid = RelationGetRelid(rel); Oid relid = RelationGetRelid(rel);
List *child, ListCell *child;
*children; List *children;
/* this routine is actually in the planner */ /* this routine is actually in the planner */
children = find_all_inheritors(relid); children = find_all_inheritors(relid);
@ -2567,7 +2568,7 @@ ATSimpleRecursion(List **wqueue, Relation rel,
*/ */
foreach(child, children) foreach(child, children)
{ {
Oid childrelid = lfirsto(child); Oid childrelid = lfirst_oid(child);
Relation childrel; Relation childrel;
if (childrelid == relid) if (childrelid == relid)
@ -2592,15 +2593,15 @@ ATOneLevelRecursion(List **wqueue, Relation rel,
AlterTableCmd *cmd) AlterTableCmd *cmd)
{ {
Oid relid = RelationGetRelid(rel); Oid relid = RelationGetRelid(rel);
List *child, ListCell *child;
*children; List *children;
/* this routine is actually in the planner */ /* this routine is actually in the planner */
children = find_inheritance_children(relid); children = find_inheritance_children(relid);
foreach(child, children) foreach(child, children)
{ {
Oid childrelid = lfirsto(child); Oid childrelid = lfirst_oid(child);
Relation childrel; Relation childrel;
childrel = relation_open(childrelid, AccessExclusiveLock); childrel = relation_open(childrelid, AccessExclusiveLock);
@ -2764,7 +2765,7 @@ ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
attribute->atttypmod = colDef->typename->typmod; attribute->atttypmod = colDef->typename->typmod;
attribute->attnum = i; attribute->attnum = i;
attribute->attbyval = tform->typbyval; attribute->attbyval = tform->typbyval;
attribute->attndims = length(colDef->typename->arrayBounds); attribute->attndims = list_length(colDef->typename->arrayBounds);
attribute->attstorage = tform->typstorage; attribute->attstorage = tform->typstorage;
attribute->attalign = tform->typalign; attribute->attalign = tform->typalign;
attribute->attnotnull = colDef->is_not_null; attribute->attnotnull = colDef->is_not_null;
@ -2814,7 +2815,7 @@ ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
* This function is intended for CREATE TABLE, so it processes a * This function is intended for CREATE TABLE, so it processes a
* _list_ of defaults, but we just do one. * _list_ of defaults, but we just do one.
*/ */
AddRelationRawConstraints(rel, makeList1(rawEnt), NIL); AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
/* Make the additional catalog changes visible */ /* Make the additional catalog changes visible */
CommandCounterIncrement(); CommandCounterIncrement();
@ -2880,7 +2881,7 @@ ATExecDropNotNull(Relation rel, const char *colName)
AttrNumber attnum; AttrNumber attnum;
Relation attr_rel; Relation attr_rel;
List *indexoidlist; List *indexoidlist;
List *indexoidscan; ListCell *indexoidscan;
/* /*
* lookup the attribute * lookup the attribute
@ -2913,7 +2914,7 @@ ATExecDropNotNull(Relation rel, const char *colName)
foreach(indexoidscan, indexoidlist) foreach(indexoidscan, indexoidlist)
{ {
Oid indexoid = lfirsto(indexoidscan); Oid indexoid = lfirst_oid(indexoidscan);
HeapTuple indexTuple; HeapTuple indexTuple;
Form_pg_index indexStruct; Form_pg_index indexStruct;
int i; int i;
@ -2945,7 +2946,7 @@ ATExecDropNotNull(Relation rel, const char *colName)
ReleaseSysCache(indexTuple); ReleaseSysCache(indexTuple);
} }
freeList(indexoidlist); list_free(indexoidlist);
/* /*
* Okay, actually perform the catalog change ... if needed * Okay, actually perform the catalog change ... if needed
@ -3067,7 +3068,7 @@ ATExecColumnDefault(Relation rel, const char *colName,
* This function is intended for CREATE TABLE, so it processes a * This function is intended for CREATE TABLE, so it processes a
* _list_ of defaults, but we just do one. * _list_ of defaults, but we just do one.
*/ */
AddRelationRawConstraints(rel, makeList1(rawEnt), NIL); AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
} }
} }
@ -3292,12 +3293,12 @@ ATExecDropColumn(Relation rel, const char *colName,
if (children) if (children)
{ {
Relation attr_rel; Relation attr_rel;
List *child; ListCell *child;
attr_rel = heap_openr(AttributeRelationName, RowExclusiveLock); attr_rel = heap_openr(AttributeRelationName, RowExclusiveLock);
foreach(child, children) foreach(child, children)
{ {
Oid childrelid = lfirsto(child); Oid childrelid = lfirst_oid(child);
Relation childrel; Relation childrel;
Form_pg_attribute childatt; Form_pg_attribute childatt;
@ -3464,14 +3465,14 @@ ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
case CONSTR_CHECK: case CONSTR_CHECK:
{ {
List *newcons; List *newcons;
List *lcon; ListCell *lcon;
/* /*
* Call AddRelationRawConstraints to do the work. * Call AddRelationRawConstraints to do the work.
* It returns a list of cooked constraints. * It returns a list of cooked constraints.
*/ */
newcons = AddRelationRawConstraints(rel, NIL, newcons = AddRelationRawConstraints(rel, NIL,
makeList1(constr)); list_make1(constr));
/* Add each constraint to Phase 3's queue */ /* Add each constraint to Phase 3's queue */
foreach(lcon, newcons) foreach(lcon, newcons)
{ {
@ -3676,7 +3677,7 @@ ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
* get the right answer from the test below on opclass membership * get the right answer from the test below on opclass membership
* unless we select the proper operator.) * unless we select the proper operator.)
*/ */
Operator o = oper(makeList1(makeString("=")), Operator o = oper(list_make1(makeString("=")),
pktypoid[i], fktypoid[i], true); pktypoid[i], fktypoid[i], true);
if (o == NULL) if (o == NULL)
@ -3687,8 +3688,8 @@ ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
fkconstraint->constr_name), fkconstraint->constr_name),
errdetail("Key columns \"%s\" and \"%s\" " errdetail("Key columns \"%s\" and \"%s\" "
"are of incompatible types: %s and %s.", "are of incompatible types: %s and %s.",
strVal(nth(i, fkconstraint->fk_attrs)), strVal(list_nth(fkconstraint->fk_attrs, i)),
strVal(nth(i, fkconstraint->pk_attrs)), strVal(list_nth(fkconstraint->pk_attrs, i)),
format_type_be(fktypoid[i]), format_type_be(fktypoid[i]),
format_type_be(pktypoid[i])))); format_type_be(pktypoid[i]))));
@ -3704,8 +3705,8 @@ ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
fkconstraint->constr_name), fkconstraint->constr_name),
errdetail("Key columns \"%s\" and \"%s\" " errdetail("Key columns \"%s\" and \"%s\" "
"are of different types: %s and %s.", "are of different types: %s and %s.",
strVal(nth(i, fkconstraint->fk_attrs)), strVal(list_nth(fkconstraint->fk_attrs, i)),
strVal(nth(i, fkconstraint->pk_attrs)), strVal(list_nth(fkconstraint->pk_attrs, i)),
format_type_be(fktypoid[i]), format_type_be(fktypoid[i]),
format_type_be(pktypoid[i])))); format_type_be(pktypoid[i]))));
@ -3774,7 +3775,7 @@ static int
transformColumnNameList(Oid relId, List *colList, transformColumnNameList(Oid relId, List *colList,
int16 *attnums, Oid *atttypids) int16 *attnums, Oid *atttypids)
{ {
List *l; ListCell *l;
int attnum; int attnum;
attnum = 0; attnum = 0;
@ -3821,8 +3822,8 @@ transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
int16 *attnums, Oid *atttypids, int16 *attnums, Oid *atttypids,
Oid *opclasses) Oid *opclasses)
{ {
List *indexoidlist, List *indexoidlist;
*indexoidscan; ListCell *indexoidscan;
HeapTuple indexTuple = NULL; HeapTuple indexTuple = NULL;
Form_pg_index indexStruct = NULL; Form_pg_index indexStruct = NULL;
int i; int i;
@ -3836,7 +3837,7 @@ transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
foreach(indexoidscan, indexoidlist) foreach(indexoidscan, indexoidlist)
{ {
Oid indexoid = lfirsto(indexoidscan); Oid indexoid = lfirst_oid(indexoidscan);
indexTuple = SearchSysCache(INDEXRELID, indexTuple = SearchSysCache(INDEXRELID,
ObjectIdGetDatum(indexoid), ObjectIdGetDatum(indexoid),
@ -3853,7 +3854,7 @@ transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
indexStruct = NULL; indexStruct = NULL;
} }
freeList(indexoidlist); list_free(indexoidlist);
/* /*
* Check that we found it * Check that we found it
@ -3900,8 +3901,8 @@ transformFkeyCheckAttrs(Relation pkrel,
{ {
Oid indexoid = InvalidOid; Oid indexoid = InvalidOid;
bool found = false; bool found = false;
List *indexoidlist, List *indexoidlist;
*indexoidscan; ListCell *indexoidscan;
/* /*
* Get the list of index OIDs for the table from the relcache, and * Get the list of index OIDs for the table from the relcache, and
@ -3917,7 +3918,7 @@ transformFkeyCheckAttrs(Relation pkrel,
int i, int i,
j; j;
indexoid = lfirsto(indexoidscan); indexoid = lfirst_oid(indexoidscan);
indexTuple = SearchSysCache(INDEXRELID, indexTuple = SearchSysCache(INDEXRELID,
ObjectIdGetDatum(indexoid), ObjectIdGetDatum(indexoid),
0, 0, 0); 0, 0, 0);
@ -3982,7 +3983,7 @@ transformFkeyCheckAttrs(Relation pkrel,
errmsg("there is no unique constraint matching given keys for referenced table \"%s\"", errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
RelationGetRelationName(pkrel)))); RelationGetRelationName(pkrel))));
freeList(indexoidlist); list_free(indexoidlist);
return indexoid; return indexoid;
} }
@ -4001,7 +4002,7 @@ validateForeignKeyConstraint(FkConstraint *fkconstraint,
HeapScanDesc scan; HeapScanDesc scan;
HeapTuple tuple; HeapTuple tuple;
Trigger trig; Trigger trig;
List *list; ListCell *list;
int count; int count;
/* /*
@ -4026,8 +4027,8 @@ validateForeignKeyConstraint(FkConstraint *fkconstraint,
trig.tginitdeferred = FALSE; trig.tginitdeferred = FALSE;
trig.tgargs = (char **) palloc(sizeof(char *) * trig.tgargs = (char **) palloc(sizeof(char *) *
(4 + length(fkconstraint->fk_attrs) (4 + list_length(fkconstraint->fk_attrs)
+ length(fkconstraint->pk_attrs))); + list_length(fkconstraint->pk_attrs)));
trig.tgargs[0] = trig.tgname; trig.tgargs[0] = trig.tgname;
trig.tgargs[1] = RelationGetRelationName(rel); trig.tgargs[1] = RelationGetRelationName(rel);
@ -4094,8 +4095,8 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
{ {
RangeVar *myRel; RangeVar *myRel;
CreateTrigStmt *fk_trigger; CreateTrigStmt *fk_trigger;
List *fk_attr; ListCell *fk_attr;
List *pk_attr; ListCell *pk_attr;
ObjectAddress trigobj, ObjectAddress trigobj,
constrobj; constrobj;
@ -4146,19 +4147,16 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
makeString(fkconstraint->pktable->relname)); makeString(fkconstraint->pktable->relname));
fk_trigger->args = lappend(fk_trigger->args, fk_trigger->args = lappend(fk_trigger->args,
makeString(fkMatchTypeToString(fkconstraint->fk_matchtype))); makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
fk_attr = fkconstraint->fk_attrs; if (list_length(fkconstraint->fk_attrs) != list_length(fkconstraint->pk_attrs))
pk_attr = fkconstraint->pk_attrs;
if (length(fk_attr) != length(pk_attr))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_FOREIGN_KEY), (errcode(ERRCODE_INVALID_FOREIGN_KEY),
errmsg("number of referencing and referenced columns for foreign key disagree"))); errmsg("number of referencing and referenced columns for foreign key disagree")));
while (fk_attr != NIL) forboth(fk_attr, fkconstraint->fk_attrs,
pk_attr, fkconstraint->pk_attrs)
{ {
fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr)); fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr));
fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr)); fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr));
fk_attr = lnext(fk_attr);
pk_attr = lnext(pk_attr);
} }
trigobj.objectId = CreateTrigger(fk_trigger, true); trigobj.objectId = CreateTrigger(fk_trigger, true);
@ -4219,14 +4217,11 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
makeString(fkconstraint->pktable->relname)); makeString(fkconstraint->pktable->relname));
fk_trigger->args = lappend(fk_trigger->args, fk_trigger->args = lappend(fk_trigger->args,
makeString(fkMatchTypeToString(fkconstraint->fk_matchtype))); makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
fk_attr = fkconstraint->fk_attrs; forboth(fk_attr, fkconstraint->fk_attrs,
pk_attr = fkconstraint->pk_attrs; pk_attr, fkconstraint->pk_attrs)
while (fk_attr != NIL)
{ {
fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr)); fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr));
fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr)); fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr));
fk_attr = lnext(fk_attr);
pk_attr = lnext(pk_attr);
} }
trigobj.objectId = CreateTrigger(fk_trigger, true); trigobj.objectId = CreateTrigger(fk_trigger, true);
@ -4286,14 +4281,11 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
makeString(fkconstraint->pktable->relname)); makeString(fkconstraint->pktable->relname));
fk_trigger->args = lappend(fk_trigger->args, fk_trigger->args = lappend(fk_trigger->args,
makeString(fkMatchTypeToString(fkconstraint->fk_matchtype))); makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
fk_attr = fkconstraint->fk_attrs; forboth(fk_attr, fkconstraint->fk_attrs,
pk_attr = fkconstraint->pk_attrs; pk_attr, fkconstraint->pk_attrs)
while (fk_attr != NIL)
{ {
fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr)); fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr));
fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr)); fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr));
fk_attr = lnext(fk_attr);
pk_attr = lnext(pk_attr);
} }
trigobj.objectId = CreateTrigger(fk_trigger, true); trigobj.objectId = CreateTrigger(fk_trigger, true);
@ -4626,9 +4618,9 @@ ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
if (relKind == RELKIND_INDEX) if (relKind == RELKIND_INDEX)
{ {
Assert(foundObject.objectSubId == 0); Assert(foundObject.objectSubId == 0);
if (!oidMember(foundObject.objectId, tab->changedIndexOids)) if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
{ {
tab->changedIndexOids = lappendo(tab->changedIndexOids, tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
foundObject.objectId); foundObject.objectId);
tab->changedIndexDefs = lappend(tab->changedIndexDefs, tab->changedIndexDefs = lappend(tab->changedIndexDefs,
pg_get_indexdef_string(foundObject.objectId)); pg_get_indexdef_string(foundObject.objectId));
@ -4653,9 +4645,9 @@ ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
case OCLASS_CONSTRAINT: case OCLASS_CONSTRAINT:
Assert(foundObject.objectSubId == 0); Assert(foundObject.objectSubId == 0);
if (!oidMember(foundObject.objectId, tab->changedConstraintOids)) if (!list_member_oid(tab->changedConstraintOids, foundObject.objectId))
{ {
tab->changedConstraintOids = lappendo(tab->changedConstraintOids, tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
foundObject.objectId); foundObject.objectId);
tab->changedConstraintDefs = lappend(tab->changedConstraintDefs, tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
pg_get_constraintdef_string(foundObject.objectId)); pg_get_constraintdef_string(foundObject.objectId));
@ -4750,7 +4742,7 @@ ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
*/ */
attTup->atttypid = targettype; attTup->atttypid = targettype;
attTup->atttypmod = typename->typmod; attTup->atttypmod = typename->typmod;
attTup->attndims = length(typename->arrayBounds); attTup->attndims = list_length(typename->arrayBounds);
attTup->attlen = tform->typlen; attTup->attlen = tform->typlen;
attTup->attbyval = tform->typbyval; attTup->attbyval = tform->typbyval;
attTup->attalign = tform->typalign; attTup->attalign = tform->typalign;
@ -4805,7 +4797,7 @@ static void
ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab) ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
{ {
ObjectAddress obj; ObjectAddress obj;
List *l; ListCell *l;
/* /*
* Re-parse the index and constraint definitions, and attach them to * Re-parse the index and constraint definitions, and attach them to
@ -4835,7 +4827,7 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
obj.classId = get_system_catalog_relid(ConstraintRelationName); obj.classId = get_system_catalog_relid(ConstraintRelationName);
foreach(l, tab->changedConstraintOids) foreach(l, tab->changedConstraintOids)
{ {
obj.objectId = lfirsto(l); obj.objectId = lfirst_oid(l);
obj.objectSubId = 0; obj.objectSubId = 0;
performDeletion(&obj, DROP_RESTRICT); performDeletion(&obj, DROP_RESTRICT);
} }
@ -4843,7 +4835,7 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
obj.classId = RelOid_pg_class; obj.classId = RelOid_pg_class;
foreach(l, tab->changedIndexOids) foreach(l, tab->changedIndexOids)
{ {
obj.objectId = lfirsto(l); obj.objectId = lfirst_oid(l);
obj.objectSubId = 0; obj.objectSubId = 0;
performDeletion(&obj, DROP_RESTRICT); performDeletion(&obj, DROP_RESTRICT);
} }
@ -4859,7 +4851,7 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
{ {
List *raw_parsetree_list; List *raw_parsetree_list;
List *querytree_list; List *querytree_list;
List *list_item; ListCell *list_item;
/* /*
* We expect that we only have to do raw parsing and parse analysis, not * We expect that we only have to do raw parsing and parse analysis, not
@ -4871,7 +4863,7 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
{ {
Node *parsetree = (Node *) lfirst(list_item); Node *parsetree = (Node *) lfirst(list_item);
querytree_list = nconc(querytree_list, querytree_list = list_concat(querytree_list,
parse_analyze(parsetree, NULL, 0)); parse_analyze(parsetree, NULL, 0));
} }
@ -4907,7 +4899,7 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
case T_AlterTableStmt: case T_AlterTableStmt:
{ {
AlterTableStmt *stmt = (AlterTableStmt *) query->utilityStmt; AlterTableStmt *stmt = (AlterTableStmt *) query->utilityStmt;
List *lcmd; ListCell *lcmd;
rel = relation_openrv(stmt->relation, AccessExclusiveLock); rel = relation_openrv(stmt->relation, AccessExclusiveLock);
tab = ATGetQueueEntry(wqueue, rel); tab = ATGetQueueEntry(wqueue, rel);
@ -5002,17 +4994,17 @@ ATExecChangeOwner(Oid relationOid, int32 newOwnerSysId)
if (tuple_class->relkind == RELKIND_RELATION || if (tuple_class->relkind == RELKIND_RELATION ||
tuple_class->relkind == RELKIND_TOASTVALUE) tuple_class->relkind == RELKIND_TOASTVALUE)
{ {
List *index_oid_list, List *index_oid_list;
*i; ListCell *i;
/* Find all the indexes belonging to this relation */ /* Find all the indexes belonging to this relation */
index_oid_list = RelationGetIndexList(target_rel); index_oid_list = RelationGetIndexList(target_rel);
/* For each index, recursively change its ownership */ /* For each index, recursively change its ownership */
foreach(i, index_oid_list) foreach(i, index_oid_list)
ATExecChangeOwner(lfirsto(i), newOwnerSysId); ATExecChangeOwner(lfirst_oid(i), newOwnerSysId);
freeList(index_oid_list); list_free(index_oid_list);
} }
if (tuple_class->relkind == RELKIND_RELATION) if (tuple_class->relkind == RELKIND_RELATION)
@ -5362,7 +5354,7 @@ register_on_commit_action(Oid relid, OnCommitAction action)
void void
remove_on_commit_action(Oid relid) remove_on_commit_action(Oid relid)
{ {
List *l; ListCell *l;
foreach(l, on_commits) foreach(l, on_commits)
{ {
@ -5385,7 +5377,7 @@ remove_on_commit_action(Oid relid)
void void
PreCommit_on_commit_actions(void) PreCommit_on_commit_actions(void)
{ {
List *l; ListCell *l;
foreach(l, on_commits) foreach(l, on_commits)
{ {
@ -5437,40 +5429,34 @@ PreCommit_on_commit_actions(void)
void void
AtEOXact_on_commit_actions(bool isCommit) AtEOXact_on_commit_actions(bool isCommit)
{ {
List *l, ListCell *cur_item;
*prev; ListCell *prev_item;
prev = NIL; prev_item = NULL;
l = on_commits; cur_item = list_head(on_commits);
while (l != NIL)
while (cur_item != NULL)
{ {
OnCommitItem *oc = (OnCommitItem *) lfirst(l); OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
if (isCommit ? oc->deleted_in_cur_xact : if (isCommit ? oc->deleted_in_cur_xact :
oc->created_in_cur_xact) oc->created_in_cur_xact)
{ {
/* This entry must be removed */ /* cur_item must be removed */
if (prev != NIL) on_commits = list_delete_cell(on_commits, cur_item, prev_item);
{
lnext(prev) = lnext(l);
pfree(l);
l = lnext(prev);
}
else
{
on_commits = lnext(l);
pfree(l);
l = on_commits;
}
pfree(oc); pfree(oc);
if (prev_item)
cur_item = lnext(prev_item);
else
cur_item = list_head(on_commits);
} }
else else
{ {
/* This entry must be preserved */ /* cur_item must be preserved */
oc->created_in_cur_xact = false;
oc->deleted_in_cur_xact = false; oc->deleted_in_cur_xact = false;
prev = l; oc->created_in_cur_xact = false;
l = lnext(l); prev_item = cur_item;
cur_item = lnext(prev_item);
} }
} }
} }

View File

@ -7,7 +7,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/trigger.c,v 1.164 2004/02/10 01:55:25 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/trigger.c,v 1.165 2004/05/26 04:41:12 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -111,19 +111,19 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint)
bool needconstrrelid = false; bool needconstrrelid = false;
void *elem = NULL; void *elem = NULL;
if (strncmp(strVal(llast(stmt->funcname)), "RI_FKey_check_", 14) == 0) if (strncmp(strVal(lfirst(list_tail((stmt->funcname)))), "RI_FKey_check_", 14) == 0)
{ {
/* A trigger on FK table. */ /* A trigger on FK table. */
needconstrrelid = true; needconstrrelid = true;
if (length(stmt->args) > RI_PK_RELNAME_ARGNO) if (list_length(stmt->args) > RI_PK_RELNAME_ARGNO)
elem = nth(RI_PK_RELNAME_ARGNO, stmt->args); elem = list_nth(stmt->args, RI_PK_RELNAME_ARGNO);
} }
else if (strncmp(strVal(llast(stmt->funcname)), "RI_FKey_", 8) == 0) else if (strncmp(strVal(lfirst(list_tail((stmt->funcname)))), "RI_FKey_", 8) == 0)
{ {
/* A trigger on PK table. */ /* A trigger on PK table. */
needconstrrelid = true; needconstrrelid = true;
if (length(stmt->args) > RI_FK_RELNAME_ARGNO) if (list_length(stmt->args) > RI_FK_RELNAME_ARGNO)
elem = nth(RI_FK_RELNAME_ARGNO, stmt->args); elem = list_nth(stmt->args, RI_FK_RELNAME_ARGNO);
} }
if (elem != NULL) if (elem != NULL)
{ {
@ -318,9 +318,9 @@ CreateTrigger(CreateTrigStmt *stmt, bool forConstraint)
if (stmt->args) if (stmt->args)
{ {
List *le; ListCell *le;
char *args; char *args;
int16 nargs = length(stmt->args); int16 nargs = list_length(stmt->args);
int len = 0; int len = 0;
foreach(le, stmt->args) foreach(le, stmt->args)
@ -1691,7 +1691,7 @@ static bool
deferredTriggerCheckState(Oid tgoid, int32 itemstate) deferredTriggerCheckState(Oid tgoid, int32 itemstate)
{ {
MemoryContext oldcxt; MemoryContext oldcxt;
List *sl; ListCell *sl;
DeferredTriggerStatus trigstate; DeferredTriggerStatus trigstate;
/* /*
@ -2193,7 +2193,7 @@ DeferredTriggerAbortXact(void)
void void
DeferredTriggerSetState(ConstraintsSetStmt *stmt) DeferredTriggerSetState(ConstraintsSetStmt *stmt)
{ {
List *l; ListCell *l;
/* /*
* Ignore call if we aren't in a transaction. * Ignore call if we aren't in a transaction.
@ -2210,15 +2210,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
* Drop all per-transaction information about individual trigger * Drop all per-transaction information about individual trigger
* states. * states.
*/ */
l = deferredTriggers->deftrig_trigstates; list_free_deep(deferredTriggers->deftrig_trigstates);
while (l != NIL)
{
List *next = lnext(l);
pfree(lfirst(l));
pfree(l);
l = next;
}
deferredTriggers->deftrig_trigstates = NIL; deferredTriggers->deftrig_trigstates = NIL;
/* /*
@ -2233,7 +2225,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
MemoryContext oldcxt; MemoryContext oldcxt;
bool found; bool found;
DeferredTriggerStatus state; DeferredTriggerStatus state;
List *ls; ListCell *ls;
List *loid = NIL; List *loid = NIL;
/* ---------- /* ----------
@ -2293,7 +2285,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
cname))); cname)));
constr_oid = HeapTupleGetOid(htup); constr_oid = HeapTupleGetOid(htup);
loid = lappendo(loid, constr_oid); loid = lappend_oid(loid, constr_oid);
found = true; found = true;
} }
@ -2321,7 +2313,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
foreach(ls, deferredTriggers->deftrig_trigstates) foreach(ls, deferredTriggers->deftrig_trigstates)
{ {
state = (DeferredTriggerStatus) lfirst(ls); state = (DeferredTriggerStatus) lfirst(ls);
if (state->dts_tgoid == lfirsto(l)) if (state->dts_tgoid == lfirst_oid(l))
{ {
state->dts_tgisdeferred = stmt->deferred; state->dts_tgisdeferred = stmt->deferred;
found = true; found = true;
@ -2332,7 +2324,7 @@ DeferredTriggerSetState(ConstraintsSetStmt *stmt)
{ {
state = (DeferredTriggerStatus) state = (DeferredTriggerStatus)
palloc(sizeof(DeferredTriggerStatusData)); palloc(sizeof(DeferredTriggerStatusData));
state->dts_tgoid = lfirsto(l); state->dts_tgoid = lfirst_oid(l);
state->dts_tgisdeferred = stmt->deferred; state->dts_tgisdeferred = stmt->deferred;
deferredTriggers->deftrig_trigstates = deferredTriggers->deftrig_trigstates =

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/typecmds.c,v 1.56 2004/05/14 16:11:25 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/typecmds.c,v 1.57 2004/05/26 04:41:12 neilc Exp $
* *
* DESCRIPTION * DESCRIPTION
* The "DefineFoo" routines take the parse tree and pick out the * The "DefineFoo" routines take the parse tree and pick out the
@ -114,7 +114,7 @@ DefineType(List *names, List *parameters)
Oid sendOid = InvalidOid; Oid sendOid = InvalidOid;
Oid analyzeOid = InvalidOid; Oid analyzeOid = InvalidOid;
char *shadow_type; char *shadow_type;
List *pl; ListCell *pl;
Oid typoid; Oid typoid;
Oid resulttype; Oid resulttype;
@ -502,10 +502,10 @@ DefineDomain(CreateDomainStmt *stmt)
bool typNotNull = false; bool typNotNull = false;
bool nullDefined = false; bool nullDefined = false;
Oid basetypelem; Oid basetypelem;
int32 typNDims = length(stmt->typename->arrayBounds); int32 typNDims = list_length(stmt->typename->arrayBounds);
HeapTuple typeTup; HeapTuple typeTup;
List *schema = stmt->constraints; List *schema = stmt->constraints;
List *listptr; ListCell *listptr;
Oid basetypeoid; Oid basetypeoid;
Oid domainoid; Oid domainoid;
Form_pg_type baseType; Form_pg_type baseType;
@ -1304,7 +1304,7 @@ AlterDomainNotNull(List *names, bool notNull)
if (notNull) if (notNull)
{ {
List *rels; List *rels;
List *rt; ListCell *rt;
/* Fetch relation list with attributes based on this domain */ /* Fetch relation list with attributes based on this domain */
/* ShareLock is sufficient to prevent concurrent data changes */ /* ShareLock is sufficient to prevent concurrent data changes */
@ -1461,7 +1461,7 @@ AlterDomainAddConstraint(List *names, Node *newConstraint)
HeapTuple tup; HeapTuple tup;
Form_pg_type typTup; Form_pg_type typTup;
List *rels; List *rels;
List *rt; ListCell *rt;
EState *estate; EState *estate;
ExprContext *econtext; ExprContext *econtext;
char *ccbin; char *ccbin;
@ -1681,7 +1681,7 @@ get_rels_with_domain(Oid domainOid, LOCKMODE lockmode)
{ {
Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup); Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
RelToCheck *rtc = NULL; RelToCheck *rtc = NULL;
List *rellist; ListCell *rellist;
Form_pg_attribute pg_att; Form_pg_attribute pg_att;
int ptr; int ptr;
@ -1848,7 +1848,7 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
/* /*
* Make sure no outside relations are referred to. * Make sure no outside relations are referred to.
*/ */
if (length(pstate->p_rtable) != 0) if (list_length(pstate->p_rtable) != 0)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE), (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("cannot use table references in domain check constraint"))); errmsg("cannot use table references in domain check constraint")));

View File

@ -6,7 +6,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* $PostgreSQL: pgsql/src/backend/commands/user.c,v 1.140 2004/05/06 16:59:16 momjian Exp $ * $PostgreSQL: pgsql/src/backend/commands/user.c,v 1.141 2004/05/26 04:41:12 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -491,8 +491,8 @@ CreateUser(CreateUserStmt *stmt)
sysid_exists = false, sysid_exists = false,
havesysid = false; havesysid = false;
int max_id; int max_id;
List *item, ListCell *item;
*option; ListCell *option;
char *password = NULL; /* PostgreSQL user password */ char *password = NULL; /* PostgreSQL user password */
bool encrypt_password = Password_encryption; /* encrypt password? */ bool encrypt_password = Password_encryption; /* encrypt password? */
char encrypted_password[MD5_PASSWD_LEN + 1]; char encrypted_password[MD5_PASSWD_LEN + 1];
@ -715,7 +715,7 @@ CreateUser(CreateUserStmt *stmt)
ags.name = strVal(lfirst(item)); /* the group name to add ags.name = strVal(lfirst(item)); /* the group name to add
* this in */ * this in */
ags.action = +1; ags.action = +1;
ags.listUsers = makeList1(makeInteger(sysid)); ags.listUsers = list_make1(makeInteger(sysid));
AlterGroup(&ags, "CREATE USER"); AlterGroup(&ags, "CREATE USER");
} }
@ -746,7 +746,7 @@ AlterUser(AlterUserStmt *stmt)
TupleDesc pg_shadow_dsc; TupleDesc pg_shadow_dsc;
HeapTuple tuple, HeapTuple tuple,
new_tuple; new_tuple;
List *option; ListCell *option;
char *password = NULL; /* PostgreSQL user password */ char *password = NULL; /* PostgreSQL user password */
bool encrypt_password = Password_encryption; /* encrypt password? */ bool encrypt_password = Password_encryption; /* encrypt password? */
char encrypted_password[MD5_PASSWD_LEN + 1]; char encrypted_password[MD5_PASSWD_LEN + 1];
@ -1017,7 +1017,7 @@ DropUser(DropUserStmt *stmt)
{ {
Relation pg_shadow_rel; Relation pg_shadow_rel;
TupleDesc pg_shadow_dsc; TupleDesc pg_shadow_dsc;
List *item; ListCell *item;
if (!superuser()) if (!superuser())
ereport(ERROR, ereport(ERROR,
@ -1122,7 +1122,7 @@ DropUser(DropUserStmt *stmt)
/* the group name from which to try to drop the user: */ /* the group name from which to try to drop the user: */
ags.name = pstrdup(NameStr(((Form_pg_group) GETSTRUCT(tmp_tuple))->groname)); ags.name = pstrdup(NameStr(((Form_pg_group) GETSTRUCT(tmp_tuple))->groname));
ags.action = -1; ags.action = -1;
ags.listUsers = makeList1(makeInteger(usesysid)); ags.listUsers = list_make1(makeInteger(usesysid));
AlterGroup(&ags, "DROP USER"); AlterGroup(&ags, "DROP USER");
} }
heap_endscan(scan); heap_endscan(scan);
@ -1283,9 +1283,9 @@ CreateGroup(CreateGroupStmt *stmt)
int max_id; int max_id;
Datum new_record[Natts_pg_group]; Datum new_record[Natts_pg_group];
char new_record_nulls[Natts_pg_group]; char new_record_nulls[Natts_pg_group];
List *item, ListCell *item;
*option, ListCell *option;
*newlist = NIL; List *newlist = NIL;
IdList *grolist; IdList *grolist;
int sysid = 0; int sysid = 0;
List *userElts = NIL; List *userElts = NIL;
@ -1397,8 +1397,8 @@ CreateGroup(CreateGroupStmt *stmt)
const char *groupuser = strVal(lfirst(item)); const char *groupuser = strVal(lfirst(item));
int32 userid = get_usesysid(groupuser); int32 userid = get_usesysid(groupuser);
if (!intMember(userid, newlist)) if (!list_member_int(newlist, userid))
newlist = lappendi(newlist, userid); newlist = lappend_int(newlist, userid);
} }
/* build an array to insert */ /* build an array to insert */
@ -1454,8 +1454,8 @@ AlterGroup(AlterGroupStmt *stmt, const char *tag)
IdList *oldarray; IdList *oldarray;
Datum datum; Datum datum;
bool null; bool null;
List *newlist, List *newlist;
*item; ListCell *item;
/* /*
* Make sure the user can do this. * Make sure the user can do this.
@ -1525,8 +1525,8 @@ AlterGroup(AlterGroupStmt *stmt, const char *tag)
sysid = 0; /* keep compiler quiet */ sysid = 0; /* keep compiler quiet */
} }
if (!intMember(sysid, newlist)) if (!list_member_int(newlist, sysid))
newlist = lappendi(newlist, sysid); newlist = lappend_int(newlist, sysid);
} }
/* Do the update */ /* Do the update */
@ -1565,8 +1565,8 @@ AlterGroup(AlterGroupStmt *stmt, const char *tag)
/* for dropuser we already know the uid */ /* for dropuser we already know the uid */
sysid = intVal(lfirst(item)); sysid = intVal(lfirst(item));
} }
if (intMember(sysid, newlist)) if (list_member_int(newlist, sysid))
newlist = lremovei(sysid, newlist); newlist = list_delete_int(newlist, sysid);
else if (!is_dropuser) else if (!is_dropuser)
ereport(WARNING, ereport(WARNING,
(errcode(ERRCODE_WARNING), (errcode(ERRCODE_WARNING),
@ -1636,9 +1636,9 @@ UpdateGroupMembership(Relation group_rel, HeapTuple group_tuple,
static IdList * static IdList *
IdListToArray(List *members) IdListToArray(List *members)
{ {
int nmembers = length(members); int nmembers = list_length(members);
IdList *newarray; IdList *newarray;
List *item; ListCell *item;
int i; int i;
newarray = palloc(ARR_OVERHEAD(1) + nmembers * sizeof(int32)); newarray = palloc(ARR_OVERHEAD(1) + nmembers * sizeof(int32));
@ -1650,7 +1650,7 @@ IdListToArray(List *members)
ARR_DIMS(newarray)[0] = nmembers; /* axis is this long */ ARR_DIMS(newarray)[0] = nmembers; /* axis is this long */
i = 0; i = 0;
foreach(item, members) foreach(item, members)
((int *) ARR_DATA_PTR(newarray))[i++] = lfirsti(item); ((int *) ARR_DATA_PTR(newarray))[i++] = lfirst_int(item);
return newarray; return newarray;
} }
@ -1679,8 +1679,8 @@ IdArrayToList(IdList *oldarray)
sysid = ((int32 *) ARR_DATA_PTR(oldarray))[i]; sysid = ((int32 *) ARR_DATA_PTR(oldarray))[i];
/* filter out any duplicates --- probably a waste of time */ /* filter out any duplicates --- probably a waste of time */
if (!intMember(sysid, newlist)) if (!list_member_int(newlist, sysid))
newlist = lappendi(newlist, sysid); newlist = lappend_int(newlist, sysid);
} }
return newlist; return newlist;

View File

@ -13,7 +13,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/vacuum.c,v 1.277 2004/05/22 23:14:38 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/vacuum.c,v 1.278 2004/05/26 04:41:12 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -164,8 +164,8 @@ vacuum(VacuumStmt *vacstmt)
bool all_rels, bool all_rels,
in_outer_xact, in_outer_xact,
use_own_xacts; use_own_xacts;
List *relations, List *relations;
*cur; ListCell *cur;
if (vacstmt->verbose) if (vacstmt->verbose)
elevel = INFO; elevel = INFO;
@ -276,7 +276,7 @@ vacuum(VacuumStmt *vacstmt)
Assert(vacstmt->analyze); Assert(vacstmt->analyze);
if (in_outer_xact) if (in_outer_xact)
use_own_xacts = false; use_own_xacts = false;
else if (length(relations) > 1) else if (list_length(relations) > 1)
use_own_xacts = true; use_own_xacts = true;
else else
use_own_xacts = false; use_own_xacts = false;
@ -312,7 +312,7 @@ vacuum(VacuumStmt *vacstmt)
*/ */
foreach(cur, relations) foreach(cur, relations)
{ {
Oid relid = lfirsto(cur); Oid relid = lfirst_oid(cur);
if (vacstmt->vacuum) if (vacstmt->vacuum)
{ {
@ -431,7 +431,7 @@ get_rel_oids(const RangeVar *vacrel, const char *stmttype)
/* Make a relation list entry for this guy */ /* Make a relation list entry for this guy */
oldcontext = MemoryContextSwitchTo(vac_context); oldcontext = MemoryContextSwitchTo(vac_context);
oid_list = lappendo(oid_list, relid); oid_list = lappend_oid(oid_list, relid);
MemoryContextSwitchTo(oldcontext); MemoryContextSwitchTo(oldcontext);
} }
else else
@ -455,7 +455,7 @@ get_rel_oids(const RangeVar *vacrel, const char *stmttype)
{ {
/* Make a relation list entry for this guy */ /* Make a relation list entry for this guy */
oldcontext = MemoryContextSwitchTo(vac_context); oldcontext = MemoryContextSwitchTo(vac_context);
oid_list = lappendo(oid_list, HeapTupleGetOid(tuple)); oid_list = lappend_oid(oid_list, HeapTupleGetOid(tuple));
MemoryContextSwitchTo(oldcontext); MemoryContextSwitchTo(oldcontext);
} }
@ -3061,13 +3061,13 @@ vac_cmp_vtlinks(const void *left, const void *right)
void void
vac_open_indexes(Relation relation, int *nindexes, Relation **Irel) vac_open_indexes(Relation relation, int *nindexes, Relation **Irel)
{ {
List *indexoidlist, List *indexoidlist;
*indexoidscan; ListCell *indexoidscan;
int i; int i;
indexoidlist = RelationGetIndexList(relation); indexoidlist = RelationGetIndexList(relation);
*nindexes = length(indexoidlist); *nindexes = list_length(indexoidlist);
if (*nindexes > 0) if (*nindexes > 0)
*Irel = (Relation *) palloc(*nindexes * sizeof(Relation)); *Irel = (Relation *) palloc(*nindexes * sizeof(Relation));
@ -3077,13 +3077,13 @@ vac_open_indexes(Relation relation, int *nindexes, Relation **Irel)
i = 0; i = 0;
foreach(indexoidscan, indexoidlist) foreach(indexoidscan, indexoidlist)
{ {
Oid indexoid = lfirsto(indexoidscan); Oid indexoid = lfirst_oid(indexoidscan);
(*Irel)[i] = index_open(indexoid); (*Irel)[i] = index_open(indexoid);
i++; i++;
} }
freeList(indexoidlist); list_free(indexoidlist);
} }

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/variable.c,v 1.96 2004/05/23 23:12:11 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/variable.c,v 1.97 2004/05/26 04:41:13 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -48,7 +48,7 @@ assign_datestyle(const char *value, bool doit, GucSource source)
char *rawstring; char *rawstring;
char *result; char *result;
List *elemlist; List *elemlist;
List *l; ListCell *l;
/* Need a modifiable copy of string */ /* Need a modifiable copy of string */
rawstring = pstrdup(value); rawstring = pstrdup(value);
@ -58,7 +58,7 @@ assign_datestyle(const char *value, bool doit, GucSource source)
{ {
/* syntax error in list */ /* syntax error in list */
pfree(rawstring); pfree(rawstring);
freeList(elemlist); list_free(elemlist);
if (source >= PGC_S_INTERACTIVE) if (source >= PGC_S_INTERACTIVE)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@ -159,7 +159,7 @@ assign_datestyle(const char *value, bool doit, GucSource source)
ok = false; ok = false;
pfree(rawstring); pfree(rawstring);
freeList(elemlist); list_free(elemlist);
if (!ok) if (!ok)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/view.c,v 1.81 2004/01/14 23:01:54 tgl Exp $ * $PostgreSQL: pgsql/src/backend/commands/view.c,v 1.82 2004/05/26 04:41:13 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -47,8 +47,8 @@ DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
Oid viewOid, Oid viewOid,
namespaceId; namespaceId;
CreateStmt *createStmt = makeNode(CreateStmt); CreateStmt *createStmt = makeNode(CreateStmt);
List *attrList, List *attrList;
*t; ListCell *t;
/* /*
* create a list of ColumnDef nodes based on the names and types of * create a list of ColumnDef nodes based on the names and types of
@ -217,7 +217,7 @@ FormViewRetrieveRule(const RangeVar *view, Query *viewParse, bool replace)
rule->whereClause = NULL; rule->whereClause = NULL;
rule->event = CMD_SELECT; rule->event = CMD_SELECT;
rule->instead = true; rule->instead = true;
rule->actions = makeList1(viewParse); rule->actions = list_make1(viewParse);
rule->replace = replace; rule->replace = replace;
return rule; return rule;

View File

@ -6,7 +6,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* $PostgreSQL: pgsql/src/backend/executor/execAmi.c,v 1.78 2004/03/02 18:56:15 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execAmi.c,v 1.79 2004/05/26 04:41:14 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -64,11 +64,11 @@ ExecReScan(PlanState *node, ExprContext *exprCtxt)
/* If we have changed parameters, propagate that info */ /* If we have changed parameters, propagate that info */
if (node->chgParam != NULL) if (node->chgParam != NULL)
{ {
List *lst; ListCell *l;
foreach(lst, node->initPlan) foreach(l, node->initPlan)
{ {
SubPlanState *sstate = (SubPlanState *) lfirst(lst); SubPlanState *sstate = (SubPlanState *) lfirst(l);
PlanState *splan = sstate->planstate; PlanState *splan = sstate->planstate;
if (splan->plan->extParam != NULL) /* don't care about child if (splan->plan->extParam != NULL) /* don't care about child
@ -77,9 +77,9 @@ ExecReScan(PlanState *node, ExprContext *exprCtxt)
if (splan->chgParam != NULL) if (splan->chgParam != NULL)
ExecReScanSetParamPlan(sstate, node); ExecReScanSetParamPlan(sstate, node);
} }
foreach(lst, node->subPlan) foreach(l, node->subPlan)
{ {
SubPlanState *sstate = (SubPlanState *) lfirst(lst); SubPlanState *sstate = (SubPlanState *) lfirst(l);
PlanState *splan = sstate->planstate; PlanState *splan = sstate->planstate;
if (splan->plan->extParam != NULL) if (splan->plan->extParam != NULL)
@ -315,7 +315,7 @@ ExecSupportsBackwardScan(Plan *node)
case T_Append: case T_Append:
{ {
List *l; ListCell *l;
foreach(l, ((Append *) node)->appendplans) foreach(l, ((Append *) node)->appendplans)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/execJunk.c,v 1.39 2004/04/07 18:46:12 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execJunk.c,v 1.40 2004/05/26 04:41:14 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -68,7 +68,7 @@ ExecInitJunkFilter(List *targetList, TupleDesc tupType,
int len, int len,
cleanLength; cleanLength;
TupleDesc cleanTupType; TupleDesc cleanTupType;
List *t; ListCell *t;
TargetEntry *tle; TargetEntry *tle;
Resdom *resdom, Resdom *resdom,
*cleanResdom; *cleanResdom;
@ -184,7 +184,7 @@ ExecGetJunkAttribute(JunkFilter *junkfilter,
bool *isNull) bool *isNull)
{ {
List *targetList; List *targetList;
List *t; ListCell *t;
AttrNumber resno; AttrNumber resno;
TupleDesc tupType; TupleDesc tupType;
HeapTuple tuple; HeapTuple tuple;

View File

@ -26,7 +26,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.231 2004/05/11 17:36:12 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.232 2004/05/26 04:41:14 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -353,11 +353,11 @@ ExecutorRewind(QueryDesc *queryDesc)
void void
ExecCheckRTPerms(List *rangeTable) ExecCheckRTPerms(List *rangeTable)
{ {
List *lp; ListCell *l;
foreach(lp, rangeTable) foreach(l, rangeTable)
{ {
RangeTblEntry *rte = lfirst(lp); RangeTblEntry *rte = lfirst(l);
ExecCheckRTEPerms(rte); ExecCheckRTEPerms(rte);
} }
@ -427,7 +427,7 @@ ExecCheckRTEPerms(RangeTblEntry *rte)
static void static void
ExecCheckXactReadOnly(Query *parsetree) ExecCheckXactReadOnly(Query *parsetree)
{ {
List *lp; ListCell *l;
/* /*
* CREATE TABLE AS or SELECT INTO? * CREATE TABLE AS or SELECT INTO?
@ -438,9 +438,9 @@ ExecCheckXactReadOnly(Query *parsetree)
goto fail; goto fail;
/* Fail if write permissions are requested on any non-temp table */ /* Fail if write permissions are requested on any non-temp table */
foreach(lp, parsetree->rtable) foreach(l, parsetree->rtable)
{ {
RangeTblEntry *rte = lfirst(lp); RangeTblEntry *rte = lfirst(l);
if (rte->rtekind == RTE_SUBQUERY) if (rte->rtekind == RTE_SUBQUERY)
{ {
@ -522,19 +522,19 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly)
* parseTree->resultRelations identifies them all * parseTree->resultRelations identifies them all
*/ */
ResultRelInfo *resultRelInfo; ResultRelInfo *resultRelInfo;
ListCell *l;
numResultRelations = length(resultRelations); numResultRelations = length(resultRelations);
resultRelInfos = (ResultRelInfo *) resultRelInfos = (ResultRelInfo *)
palloc(numResultRelations * sizeof(ResultRelInfo)); palloc(numResultRelations * sizeof(ResultRelInfo));
resultRelInfo = resultRelInfos; resultRelInfo = resultRelInfos;
while (resultRelations != NIL) foreach(l, resultRelations)
{ {
initResultRelInfo(resultRelInfo, initResultRelInfo(resultRelInfo,
lfirsti(resultRelations), lfirst_int(l),
rangeTable, rangeTable,
operation); operation);
resultRelInfo++; resultRelInfo++;
resultRelations = lnext(resultRelations);
} }
} }
else else
@ -586,7 +586,7 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly)
estate->es_rowMark = NIL; estate->es_rowMark = NIL;
if (parseTree->rowMarks != NIL) if (parseTree->rowMarks != NIL)
{ {
List *l; ListCell *l;
foreach(l, parseTree->rowMarks) foreach(l, parseTree->rowMarks)
{ {
@ -651,7 +651,7 @@ InitPlan(QueryDesc *queryDesc, bool explainOnly)
*/ */
{ {
bool junk_filter_needed = false; bool junk_filter_needed = false;
List *tlist; ListCell *tlist;
switch (operation) switch (operation)
{ {
@ -950,7 +950,7 @@ ExecEndPlan(PlanState *planstate, EState *estate)
{ {
ResultRelInfo *resultRelInfo; ResultRelInfo *resultRelInfo;
int i; int i;
List *l; ListCell *l;
/* /*
* shut down any PlanQual processing we were doing * shut down any PlanQual processing we were doing
@ -1132,7 +1132,7 @@ lnext: ;
} }
else if (estate->es_rowMark != NIL) else if (estate->es_rowMark != NIL)
{ {
List *l; ListCell *l;
lmark: ; lmark: ;
foreach(l, estate->es_rowMark) foreach(l, estate->es_rowMark)
@ -1785,7 +1785,7 @@ EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
relation = estate->es_result_relation_info->ri_RelationDesc; relation = estate->es_result_relation_info->ri_RelationDesc;
else else
{ {
List *l; ListCell *l;
relation = NULL; relation = NULL;
foreach(l, estate->es_rowMark) foreach(l, estate->es_rowMark)

View File

@ -12,7 +12,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/execProcnode.c,v 1.42 2004/03/02 22:17:34 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execProcnode.c,v 1.43 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -119,7 +119,7 @@ ExecInitNode(Plan *node, EState *estate)
{ {
PlanState *result; PlanState *result;
List *subps; List *subps;
List *subp; ListCell *l;
/* /*
* do nothing when we get to the end of a leaf on tree. * do nothing when we get to the end of a leaf on tree.
@ -224,9 +224,9 @@ ExecInitNode(Plan *node, EState *estate)
* them in a separate list for us. * them in a separate list for us.
*/ */
subps = NIL; subps = NIL;
foreach(subp, node->initPlan) foreach(l, node->initPlan)
{ {
SubPlan *subplan = (SubPlan *) lfirst(subp); SubPlan *subplan = (SubPlan *) lfirst(l);
SubPlanState *sstate; SubPlanState *sstate;
Assert(IsA(subplan, SubPlan)); Assert(IsA(subplan, SubPlan));
@ -242,9 +242,9 @@ ExecInitNode(Plan *node, EState *estate)
* do this after initializing initPlans, in case their arguments * do this after initializing initPlans, in case their arguments
* contain subPlans (is that actually possible? perhaps not). * contain subPlans (is that actually possible? perhaps not).
*/ */
foreach(subp, result->subPlan) foreach(l, result->subPlan)
{ {
SubPlanState *sstate = (SubPlanState *) lfirst(subp); SubPlanState *sstate = (SubPlanState *) lfirst(l);
Assert(IsA(sstate, SubPlanState)); Assert(IsA(sstate, SubPlanState));
ExecInitSubPlan(sstate, estate); ExecInitSubPlan(sstate, estate);
@ -483,7 +483,7 @@ ExecCountSlotsNode(Plan *node)
void void
ExecEndNode(PlanState *node) ExecEndNode(PlanState *node)
{ {
List *subp; ListCell *subp;
/* /*
* do nothing when we get to the end of a leaf on tree. * do nothing when we get to the end of a leaf on tree.

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/execQual.c,v 1.159 2004/05/10 22:44:43 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execQual.c,v 1.160 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -217,7 +217,7 @@ ExecEvalArrayRef(ArrayRefExprState *astate,
ArrayType *array_source; ArrayType *array_source;
ArrayType *resultArray; ArrayType *resultArray;
bool isAssignment = (arrayRef->refassgnexpr != NULL); bool isAssignment = (arrayRef->refassgnexpr != NULL);
List *elt; ListCell *l;
int i = 0, int i = 0,
j = 0; j = 0;
IntArray upper, IntArray upper,
@ -258,9 +258,9 @@ ExecEvalArrayRef(ArrayRefExprState *astate,
array_source = NULL; array_source = NULL;
} }
foreach(elt, astate->refupperindexpr) foreach(l, astate->refupperindexpr)
{ {
ExprState *eltstate = (ExprState *) lfirst(elt); ExprState *eltstate = (ExprState *) lfirst(l);
if (i >= MAXDIM) if (i >= MAXDIM)
ereport(ERROR, ereport(ERROR,
@ -284,9 +284,9 @@ ExecEvalArrayRef(ArrayRefExprState *astate,
if (astate->reflowerindexpr != NIL) if (astate->reflowerindexpr != NIL)
{ {
foreach(elt, astate->reflowerindexpr) foreach(l, astate->reflowerindexpr)
{ {
ExprState *eltstate = (ExprState *) lfirst(elt); ExprState *eltstate = (ExprState *) lfirst(l);
if (j >= MAXDIM) if (j >= MAXDIM)
ereport(ERROR, ereport(ERROR,
@ -798,7 +798,7 @@ ExecEvalFuncArgs(FunctionCallInfo fcinfo,
{ {
ExprDoneCond argIsDone; ExprDoneCond argIsDone;
int i; int i;
List *arg; ListCell *arg;
argIsDone = ExprSingleResult; /* default assumption */ argIsDone = ExprSingleResult; /* default assumption */
@ -1070,7 +1070,7 @@ ExecMakeFunctionResultNoSets(FuncExprState *fcache,
bool *isNull, bool *isNull,
ExprDoneCond *isDone) ExprDoneCond *isDone)
{ {
List *arg; ListCell *arg;
Datum result; Datum result;
FunctionCallInfoData fcinfo; FunctionCallInfoData fcinfo;
int i; int i;
@ -1703,7 +1703,7 @@ static Datum
ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
bool *isNull, ExprDoneCond *isDone) bool *isNull, ExprDoneCond *isDone)
{ {
ExprState *clause = lfirst(notclause->args); ExprState *clause = linitial(notclause->args);
Datum expr_value; Datum expr_value;
if (isDone) if (isDone)
@ -1734,7 +1734,7 @@ ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
bool *isNull, ExprDoneCond *isDone) bool *isNull, ExprDoneCond *isDone)
{ {
List *clauses = orExpr->args; List *clauses = orExpr->args;
List *clause; ListCell *clause;
bool AnyNull; bool AnyNull;
if (isDone) if (isDone)
@ -1786,7 +1786,7 @@ ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
bool *isNull, ExprDoneCond *isDone) bool *isNull, ExprDoneCond *isDone)
{ {
List *clauses = andExpr->args; List *clauses = andExpr->args;
List *clause; ListCell *clause;
bool AnyNull; bool AnyNull;
if (isDone) if (isDone)
@ -1802,6 +1802,7 @@ ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
* when you interpret NULL as "don't know", using the same sort of * when you interpret NULL as "don't know", using the same sort of
* reasoning as for OR, above. * reasoning as for OR, above.
*/ */
foreach(clause, clauses) foreach(clause, clauses)
{ {
ExprState *clausestate = (ExprState *) lfirst(clause); ExprState *clausestate = (ExprState *) lfirst(clause);
@ -1838,7 +1839,7 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
bool *isNull, ExprDoneCond *isDone) bool *isNull, ExprDoneCond *isDone)
{ {
List *clauses = caseExpr->args; List *clauses = caseExpr->args;
List *clause; ListCell *clause;
Datum save_datum; Datum save_datum;
bool save_isNull; bool save_isNull;
@ -1938,7 +1939,7 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
{ {
ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr; ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
ArrayType *result; ArrayType *result;
List *element; ListCell *element;
Oid element_type = arrayExpr->element_typeid; Oid element_type = arrayExpr->element_typeid;
int ndims = 0; int ndims = 0;
int dims[MAXDIM]; int dims[MAXDIM];
@ -2118,7 +2119,7 @@ ExecEvalRow(RowExprState *rstate,
Datum *values; Datum *values;
char *nulls; char *nulls;
int nargs; int nargs;
List *arg; ListCell *arg;
int i; int i;
/* Set default values for result flags: non-null, not a set result */ /* Set default values for result flags: non-null, not a set result */
@ -2161,7 +2162,7 @@ static Datum
ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext, ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
bool *isNull, ExprDoneCond *isDone) bool *isNull, ExprDoneCond *isDone)
{ {
List *arg; ListCell *arg;
if (isDone) if (isDone)
*isDone = ExprSingleResult; *isDone = ExprSingleResult;
@ -2390,7 +2391,7 @@ ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
{ {
CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr; CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
Datum result; Datum result;
List *l; ListCell *l;
result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone); result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
@ -2826,14 +2827,14 @@ ExecInitExpr(Expr *node, PlanState *parent)
CaseExpr *caseexpr = (CaseExpr *) node; CaseExpr *caseexpr = (CaseExpr *) node;
CaseExprState *cstate = makeNode(CaseExprState); CaseExprState *cstate = makeNode(CaseExprState);
FastList outlist; FastList outlist;
List *inlist; ListCell *l;
cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase; cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase;
cstate->arg = ExecInitExpr(caseexpr->arg, parent); cstate->arg = ExecInitExpr(caseexpr->arg, parent);
FastListInit(&outlist); FastListInit(&outlist);
foreach(inlist, caseexpr->args) foreach(l, caseexpr->args)
{ {
CaseWhen *when = (CaseWhen *) lfirst(inlist); CaseWhen *when = (CaseWhen *) lfirst(l);
CaseWhenState *wstate = makeNode(CaseWhenState); CaseWhenState *wstate = makeNode(CaseWhenState);
Assert(IsA(when, CaseWhen)); Assert(IsA(when, CaseWhen));
@ -2853,13 +2854,13 @@ ExecInitExpr(Expr *node, PlanState *parent)
ArrayExpr *arrayexpr = (ArrayExpr *) node; ArrayExpr *arrayexpr = (ArrayExpr *) node;
ArrayExprState *astate = makeNode(ArrayExprState); ArrayExprState *astate = makeNode(ArrayExprState);
FastList outlist; FastList outlist;
List *inlist; ListCell *l;
astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray; astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray;
FastListInit(&outlist); FastListInit(&outlist);
foreach(inlist, arrayexpr->elements) foreach(l, arrayexpr->elements)
{ {
Expr *e = (Expr *) lfirst(inlist); Expr *e = (Expr *) lfirst(l);
ExprState *estate; ExprState *estate;
estate = ExecInitExpr(e, parent); estate = ExecInitExpr(e, parent);
@ -2879,13 +2880,13 @@ ExecInitExpr(Expr *node, PlanState *parent)
RowExpr *rowexpr = (RowExpr *) node; RowExpr *rowexpr = (RowExpr *) node;
RowExprState *rstate = makeNode(RowExprState); RowExprState *rstate = makeNode(RowExprState);
List *outlist; List *outlist;
List *inlist; ListCell *l;
rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow; rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow;
outlist = NIL; outlist = NIL;
foreach(inlist, rowexpr->args) foreach(l, rowexpr->args)
{ {
Expr *e = (Expr *) lfirst(inlist); Expr *e = (Expr *) lfirst(l);
ExprState *estate; ExprState *estate;
estate = ExecInitExpr(e, parent); estate = ExecInitExpr(e, parent);
@ -2912,13 +2913,13 @@ ExecInitExpr(Expr *node, PlanState *parent)
CoalesceExpr *coalesceexpr = (CoalesceExpr *) node; CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
CoalesceExprState *cstate = makeNode(CoalesceExprState); CoalesceExprState *cstate = makeNode(CoalesceExprState);
FastList outlist; FastList outlist;
List *inlist; ListCell *l;
cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce; cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce;
FastListInit(&outlist); FastListInit(&outlist);
foreach(inlist, coalesceexpr->args) foreach(l, coalesceexpr->args)
{ {
Expr *e = (Expr *) lfirst(inlist); Expr *e = (Expr *) lfirst(l);
ExprState *estate; ExprState *estate;
estate = ExecInitExpr(e, parent); estate = ExecInitExpr(e, parent);
@ -2984,13 +2985,13 @@ ExecInitExpr(Expr *node, PlanState *parent)
case T_List: case T_List:
{ {
FastList outlist; FastList outlist;
List *inlist; ListCell *l;
FastListInit(&outlist); FastListInit(&outlist);
foreach(inlist, (List *) node) foreach(l, (List *) node)
{ {
FastAppend(&outlist, FastAppend(&outlist,
ExecInitExpr((Expr *) lfirst(inlist), ExecInitExpr((Expr *) lfirst(l),
parent)); parent));
} }
/* Don't fall through to the "common" code below */ /* Don't fall through to the "common" code below */
@ -3101,7 +3102,7 @@ ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
{ {
bool result; bool result;
MemoryContext oldContext; MemoryContext oldContext;
List *qlist; ListCell *l;
/* /*
* debugging stuff * debugging stuff
@ -3131,9 +3132,9 @@ ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
*/ */
result = true; result = true;
foreach(qlist, qual) foreach(l, qual)
{ {
ExprState *clause = (ExprState *) lfirst(qlist); ExprState *clause = (ExprState *) lfirst(l);
Datum expr_value; Datum expr_value;
bool isNull; bool isNull;
@ -3179,7 +3180,7 @@ int
ExecCleanTargetListLength(List *targetlist) ExecCleanTargetListLength(List *targetlist)
{ {
int len = 0; int len = 0;
List *tl; ListCell *tl;
foreach(tl, targetlist) foreach(tl, targetlist)
{ {
@ -3219,7 +3220,7 @@ ExecTargetList(List *targetlist,
ExprDoneCond *isDone) ExprDoneCond *isDone)
{ {
MemoryContext oldContext; MemoryContext oldContext;
List *tl; ListCell *tl;
bool isNull; bool isNull;
bool haveDoneSets; bool haveDoneSets;

View File

@ -12,7 +12,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/execScan.c,v 1.30 2004/01/22 02:23:21 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execScan.c,v 1.31 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -195,6 +195,7 @@ tlist_matches_tupdesc(PlanState *ps, List *tlist, Index varno, TupleDesc tupdesc
int numattrs = tupdesc->natts; int numattrs = tupdesc->natts;
int attrno; int attrno;
bool hasoid; bool hasoid;
ListCell *tlist_item = list_head(tlist);
/* Check the tlist attributes */ /* Check the tlist attributes */
for (attrno = 1; attrno <= numattrs; attrno++) for (attrno = 1; attrno <= numattrs; attrno++)
@ -202,9 +203,9 @@ tlist_matches_tupdesc(PlanState *ps, List *tlist, Index varno, TupleDesc tupdesc
Form_pg_attribute att_tup = tupdesc->attrs[attrno - 1]; Form_pg_attribute att_tup = tupdesc->attrs[attrno - 1];
Var *var; Var *var;
if (tlist == NIL) if (tlist_item == NULL)
return false; /* tlist too short */ return false; /* tlist too short */
var = (Var *) ((TargetEntry *) lfirst(tlist))->expr; var = (Var *) ((TargetEntry *) lfirst(tlist_item))->expr;
if (!var || !IsA(var, Var)) if (!var || !IsA(var, Var))
return false; /* tlist item not a Var */ return false; /* tlist item not a Var */
Assert(var->varno == varno); Assert(var->varno == varno);
@ -216,10 +217,10 @@ tlist_matches_tupdesc(PlanState *ps, List *tlist, Index varno, TupleDesc tupdesc
Assert(var->vartype == att_tup->atttypid); Assert(var->vartype == att_tup->atttypid);
Assert(var->vartypmod == att_tup->atttypmod); Assert(var->vartypmod == att_tup->atttypmod);
tlist = lnext(tlist); tlist_item = lnext(tlist_item);
} }
if (tlist) if (tlist_item)
return false; /* tlist too long */ return false; /* tlist too long */
/* /*

View File

@ -15,7 +15,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/execTuples.c,v 1.77 2004/05/10 22:44:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execTuples.c,v 1.78 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -569,7 +569,7 @@ static TupleDesc
ExecTypeFromTLInternal(List *targetList, bool hasoid, bool skipjunk) ExecTypeFromTLInternal(List *targetList, bool hasoid, bool skipjunk)
{ {
TupleDesc typeInfo; TupleDesc typeInfo;
List *l; ListCell *l;
int len; int len;
int cur_resno = 1; int cur_resno = 1;
@ -606,7 +606,7 @@ TupleDesc
ExecTypeFromExprList(List *exprList) ExecTypeFromExprList(List *exprList)
{ {
TupleDesc typeInfo; TupleDesc typeInfo;
List *l; ListCell *l;
int cur_resno = 1; int cur_resno = 1;
char fldname[NAMEDATALEN]; char fldname[NAMEDATALEN];

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/execUtils.c,v 1.110 2004/03/17 20:48:42 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/execUtils.c,v 1.111 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -248,7 +248,10 @@ FreeExecutorState(EState *estate)
*/ */
while (estate->es_exprcontexts) while (estate->es_exprcontexts)
{ {
FreeExprContext((ExprContext *) lfirst(estate->es_exprcontexts)); /* XXX: seems there ought to be a faster way to implement this
* than repeated lremove(), no?
*/
FreeExprContext((ExprContext *) linitial(estate->es_exprcontexts));
/* FreeExprContext removed the list link for us */ /* FreeExprContext removed the list link for us */
} }
@ -636,8 +639,8 @@ void
ExecOpenIndices(ResultRelInfo *resultRelInfo) ExecOpenIndices(ResultRelInfo *resultRelInfo)
{ {
Relation resultRelation = resultRelInfo->ri_RelationDesc; Relation resultRelation = resultRelInfo->ri_RelationDesc;
List *indexoidlist, List *indexoidlist;
*indexoidscan; ListCell *l;
int len, int len,
i; i;
RelationPtr relationDescs; RelationPtr relationDescs;
@ -671,9 +674,9 @@ ExecOpenIndices(ResultRelInfo *resultRelInfo)
* For each index, open the index relation and save pg_index info. * For each index, open the index relation and save pg_index info.
*/ */
i = 0; i = 0;
foreach(indexoidscan, indexoidlist) foreach(l, indexoidlist)
{ {
Oid indexOid = lfirsto(indexoidscan); Oid indexOid = lfirsto(l);
Relation indexDesc; Relation indexDesc;
IndexInfo *ii; IndexInfo *ii;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/functions.c,v 1.80 2004/04/02 23:14:08 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/functions.c,v 1.81 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -92,7 +92,7 @@ init_execution_state(List *queryTree_list)
{ {
execution_state *firstes = NULL; execution_state *firstes = NULL;
execution_state *preves = NULL; execution_state *preves = NULL;
List *qtl_item; ListCell *qtl_item;
foreach(qtl_item, queryTree_list) foreach(qtl_item, queryTree_list)
{ {

View File

@ -45,7 +45,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeAgg.c,v 1.119 2004/03/13 00:54:10 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeAgg.c,v 1.120 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -1033,7 +1033,7 @@ ExecInitAgg(Agg *node, EState *estate)
ExprContext *econtext; ExprContext *econtext;
int numaggs, int numaggs,
aggno; aggno;
List *alist; ListCell *l;
/* /*
* create state structure * create state structure
@ -1187,9 +1187,9 @@ ExecInitAgg(Agg *node, EState *estate)
* result entry by giving them duplicate aggno values. * result entry by giving them duplicate aggno values.
*/ */
aggno = -1; aggno = -1;
foreach(alist, aggstate->aggs) foreach(l, aggstate->aggs)
{ {
AggrefExprState *aggrefstate = (AggrefExprState *) lfirst(alist); AggrefExprState *aggrefstate = (AggrefExprState *) lfirst(l);
Aggref *aggref = (Aggref *) aggrefstate->xprstate.expr; Aggref *aggref = (Aggref *) aggrefstate->xprstate.expr;
AggStatePerAgg peraggstate; AggStatePerAgg peraggstate;
Oid inputType; Oid inputType;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeAppend.c,v 1.56 2004/01/22 02:23:21 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeAppend.c,v 1.57 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -237,7 +237,7 @@ ExecInitAppend(Append *node, EState *estate)
int int
ExecCountSlotsAppend(Append *node) ExecCountSlotsAppend(Append *node)
{ {
List *plan; ListCell *plan;
int nSlots = 0; int nSlots = 0;
foreach(plan, node->appendplans) foreach(plan, node->appendplans)

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeFunctionscan.c,v 1.24 2004/04/01 21:28:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeFunctionscan.c,v 1.25 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -201,7 +201,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate)
else if (functyptype == 'b' || functyptype == 'd') else if (functyptype == 'b' || functyptype == 'd')
{ {
/* Must be a base data type, i.e. scalar */ /* Must be a base data type, i.e. scalar */
char *attname = strVal(lfirst(rte->eref->colnames)); char *attname = strVal(linitial(rte->eref->colnames));
tupdesc = CreateTemplateTupleDesc(1, false); tupdesc = CreateTemplateTupleDesc(1, false);
TupleDescInitEntry(tupdesc, TupleDescInitEntry(tupdesc,

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeHash.c,v 1.83 2004/03/17 01:02:23 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeHash.c,v 1.84 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -202,7 +202,7 @@ ExecHashTableCreate(Hash *node, List *hashOperators)
int nbatch; int nbatch;
int nkeys; int nkeys;
int i; int i;
List *ho; ListCell *ho;
MemoryContext oldcxt; MemoryContext oldcxt;
/* /*
@ -518,7 +518,7 @@ ExecHashGetBucket(HashJoinTable hashtable,
{ {
uint32 hashkey = 0; uint32 hashkey = 0;
int bucketno; int bucketno;
List *hk; ListCell *hk;
int i = 0; int i = 0;
MemoryContext oldContext; MemoryContext oldContext;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeHashjoin.c,v 1.60 2004/01/07 18:56:26 neilc Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeHashjoin.c,v 1.61 2004/05/26 04:41:15 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -311,7 +311,7 @@ ExecInitHashJoin(HashJoin *node, EState *estate)
List *lclauses; List *lclauses;
List *rclauses; List *rclauses;
List *hoperators; List *hoperators;
List *hcl; ListCell *l;
/* /*
* create state structure * create state structure
@ -419,15 +419,15 @@ ExecInitHashJoin(HashJoin *node, EState *estate)
lclauses = NIL; lclauses = NIL;
rclauses = NIL; rclauses = NIL;
hoperators = NIL; hoperators = NIL;
foreach(hcl, hjstate->hashclauses) foreach(l, hjstate->hashclauses)
{ {
FuncExprState *fstate = (FuncExprState *) lfirst(hcl); FuncExprState *fstate = (FuncExprState *) lfirst(l);
OpExpr *hclause; OpExpr *hclause;
Assert(IsA(fstate, FuncExprState)); Assert(IsA(fstate, FuncExprState));
hclause = (OpExpr *) fstate->xprstate.expr; hclause = (OpExpr *) fstate->xprstate.expr;
Assert(IsA(hclause, OpExpr)); Assert(IsA(hclause, OpExpr));
lclauses = lappend(lclauses, lfirst(fstate->args)); lclauses = lappend(lclauses, linitial(fstate->args));
rclauses = lappend(rclauses, lsecond(fstate->args)); rclauses = lappend(rclauses, lsecond(fstate->args));
hoperators = lappendo(hoperators, hclause->opno); hoperators = lappendo(hoperators, hclause->opno);
} }

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeIndexscan.c,v 1.93 2004/04/21 18:24:26 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeIndexscan.c,v 1.94 2004/05/26 04:41:16 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -146,7 +146,7 @@ IndexNext(IndexScanState *node)
if (estate->es_evTuple != NULL && if (estate->es_evTuple != NULL &&
estate->es_evTuple[scanrelid - 1] != NULL) estate->es_evTuple[scanrelid - 1] != NULL)
{ {
List *qual; ListCell *qual;
if (estate->es_evTupleNull[scanrelid - 1]) if (estate->es_evTupleNull[scanrelid - 1])
return slot; /* return empty slot */ return slot; /* return empty slot */
@ -164,7 +164,7 @@ IndexNext(IndexScanState *node)
if (ExecQual((List *) lfirst(qual), econtext, false)) if (ExecQual((List *) lfirst(qual), econtext, false))
break; break;
} }
if (qual == NIL) /* would not be returned by indices */ if (qual == NULL) /* would not be returned by indices */
slot->val = NULL; slot->val = NULL;
/* Flag for the next call that no more tuples */ /* Flag for the next call that no more tuples */
@ -283,11 +283,11 @@ IndexNext(IndexScanState *node)
{ {
bool prev_matches = false; bool prev_matches = false;
int prev_index; int prev_index;
List *qual; ListCell *qual;
econtext->ecxt_scantuple = slot; econtext->ecxt_scantuple = slot;
ResetExprContext(econtext); ResetExprContext(econtext);
qual = node->indxqualorig; qual = list_head(node->indxqualorig);
for (prev_index = 0; for (prev_index = 0;
prev_index < node->iss_IndexPtr; prev_index < node->iss_IndexPtr;
prev_index++) prev_index++)
@ -641,11 +641,11 @@ IndexScanState *
ExecInitIndexScan(IndexScan *node, EState *estate) ExecInitIndexScan(IndexScan *node, EState *estate)
{ {
IndexScanState *indexstate; IndexScanState *indexstate;
List *indxqual; ListCell *indxqual;
List *indxstrategy; ListCell *indxstrategy;
List *indxsubtype; ListCell *indxsubtype;
List *indxlossy; ListCell *indxlossy;
List *indxid; ListCell *indxid_item;
int i; int i;
int numIndices; int numIndices;
int indexPtr; int indexPtr;
@ -719,8 +719,8 @@ ExecInitIndexScan(IndexScan *node, EState *estate)
/* /*
* get the index node information * get the index node information
*/ */
indxid = node->indxid; indxid_item = list_head(node->indxid);
numIndices = length(indxid); numIndices = length(node->indxid);
indexPtr = -1; indexPtr = -1;
CXT1_printf("ExecInitIndexScan: context is %d\n", CurrentMemoryContext); CXT1_printf("ExecInitIndexScan: context is %d\n", CurrentMemoryContext);
@ -745,28 +745,32 @@ ExecInitIndexScan(IndexScan *node, EState *estate)
/* /*
* build the index scan keys from the index qualification * build the index scan keys from the index qualification
*/ */
indxqual = node->indxqual; indxqual = list_head(node->indxqual);
indxstrategy = node->indxstrategy; indxstrategy = list_head(node->indxstrategy);
indxsubtype = node->indxsubtype; indxsubtype = list_head(node->indxsubtype);
indxlossy = node->indxlossy; indxlossy = list_head(node->indxlossy);
for (i = 0; i < numIndices; i++) for (i = 0; i < numIndices; i++)
{ {
List *quals; List *quals;
List *strategies; List *strategies;
List *subtypes; List *subtypes;
List *lossyflags; List *lossyflags;
ListCell *qual_cell;
ListCell *strategy_cell;
ListCell *subtype_cell;
ListCell *lossyflag_cell;
int n_keys; int n_keys;
ScanKey scan_keys; ScanKey scan_keys;
ExprState **run_keys; ExprState **run_keys;
int j; int j;
quals = lfirst(indxqual); quals = (List *) lfirst(indxqual);
indxqual = lnext(indxqual); indxqual = lnext(indxqual);
strategies = lfirst(indxstrategy); strategies = (List *) lfirst(indxstrategy);
indxstrategy = lnext(indxstrategy); indxstrategy = lnext(indxstrategy);
subtypes = lfirst(indxsubtype); subtypes = (List *) lfirst(indxsubtype);
indxsubtype = lnext(indxsubtype); indxsubtype = lnext(indxsubtype);
lossyflags = lfirst(indxlossy); lossyflags = (List *) lfirst(indxlossy);
indxlossy = lnext(indxlossy); indxlossy = lnext(indxlossy);
n_keys = length(quals); n_keys = length(quals);
scan_keys = (n_keys <= 0) ? NULL : scan_keys = (n_keys <= 0) ? NULL :
@ -778,6 +782,10 @@ ExecInitIndexScan(IndexScan *node, EState *estate)
* for each opclause in the given qual, convert each qual's * for each opclause in the given qual, convert each qual's
* opclause into a single scan key * opclause into a single scan key
*/ */
qual_cell = list_head(quals);
strategy_cell = list_head(strategies);
subtype_cell = list_head(subtypes);
lossyflag_cell = list_head(lossyflags);
for (j = 0; j < n_keys; j++) for (j = 0; j < n_keys; j++)
{ {
OpExpr *clause; /* one clause of index qual */ OpExpr *clause; /* one clause of index qual */
@ -794,14 +802,14 @@ ExecInitIndexScan(IndexScan *node, EState *estate)
/* /*
* extract clause information from the qualification * extract clause information from the qualification
*/ */
clause = (OpExpr *) lfirst(quals); clause = (OpExpr *) lfirst(qual_cell);
quals = lnext(quals); qual_cell = lnext(qual_cell);
strategy = lfirsti(strategies); strategy = lfirsti(strategy_cell);
strategies = lnext(strategies); strategy_cell = lnext(strategy_cell);
subtype = lfirsto(subtypes); subtype = lfirsto(subtype_cell);
subtypes = lnext(subtypes); subtype_cell = lnext(subtype_cell);
lossy = lfirsti(lossyflags); lossy = lfirsti(lossyflag_cell);
lossyflags = lnext(lossyflags); lossyflag_cell = lnext(lossyflag_cell);
if (!IsA(clause, OpExpr)) if (!IsA(clause, OpExpr))
elog(ERROR, "indxqual is not an OpExpr"); elog(ERROR, "indxqual is not an OpExpr");
@ -972,7 +980,7 @@ ExecInitIndexScan(IndexScan *node, EState *estate)
*/ */
for (i = 0; i < numIndices; i++) for (i = 0; i < numIndices; i++)
{ {
Oid indexOid = lfirsto(indxid); Oid indexOid = lfirsto(indxid_item);
indexDescs[i] = index_open(indexOid); indexDescs[i] = index_open(indexOid);
scanDescs[i] = index_beginscan(currentRelation, scanDescs[i] = index_beginscan(currentRelation,
@ -980,7 +988,7 @@ ExecInitIndexScan(IndexScan *node, EState *estate)
estate->es_snapshot, estate->es_snapshot,
numScanKeys[i], numScanKeys[i],
scanKeys[i]); scanKeys[i]);
indxid = lnext(indxid); indxid_item = lnext(indxid_item);
} }
indexstate->iss_RelationDescs = indexDescs; indexstate->iss_RelationDescs = indexDescs;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeMergejoin.c,v 1.64 2004/03/17 01:02:23 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeMergejoin.c,v 1.65 2004/05/26 04:41:16 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -105,8 +105,8 @@ MJFormSkipQuals(List *qualList, List **ltQuals, List **gtQuals,
PlanState *parent) PlanState *parent)
{ {
List *ltexprs, List *ltexprs,
*gtexprs, *gtexprs;
*ltcdr, ListCell *ltcdr,
*gtcdr; *gtcdr;
/* /*
@ -119,8 +119,7 @@ MJFormSkipQuals(List *qualList, List **ltQuals, List **gtQuals,
* Scan both lists in parallel, so that we can update the operators * Scan both lists in parallel, so that we can update the operators
* with the minimum number of syscache searches. * with the minimum number of syscache searches.
*/ */
ltcdr = ltexprs; forboth(ltcdr, ltexprs, gtcdr, gtexprs)
foreach(gtcdr, gtexprs)
{ {
OpExpr *ltop = (OpExpr *) lfirst(ltcdr); OpExpr *ltop = (OpExpr *) lfirst(ltcdr);
OpExpr *gtop = (OpExpr *) lfirst(gtcdr); OpExpr *gtop = (OpExpr *) lfirst(gtcdr);
@ -140,8 +139,6 @@ MJFormSkipQuals(List *qualList, List **ltQuals, List **gtQuals,
&gtop->opno, &gtop->opno,
&ltop->opfuncid, &ltop->opfuncid,
&gtop->opfuncid); &gtop->opfuncid);
ltcdr = lnext(ltcdr);
} }
/* /*
@ -173,8 +170,8 @@ MergeCompare(List *eqQual, List *compareQual, ExprContext *econtext)
{ {
bool result; bool result;
MemoryContext oldContext; MemoryContext oldContext;
List *clause; ListCell *clause;
List *eqclause; ListCell *eqclause;
/* /*
* Do expression eval in short-lived context. * Do expression eval in short-lived context.
@ -188,8 +185,12 @@ MergeCompare(List *eqQual, List *compareQual, ExprContext *econtext)
*/ */
result = false; /* assume 'false' result */ result = false; /* assume 'false' result */
eqclause = eqQual; /*
foreach(clause, compareQual) * We can't run out of one list before the other
*/
Assert(length(compareQual) == length(eqQual));
forboth(clause, compareQual, eqclause, eqQual)
{ {
ExprState *clauseexpr = (ExprState *) lfirst(clause); ExprState *clauseexpr = (ExprState *) lfirst(clause);
ExprState *eqclauseexpr = (ExprState *) lfirst(eqclause); ExprState *eqclauseexpr = (ExprState *) lfirst(eqclause);
@ -220,8 +221,6 @@ MergeCompare(List *eqQual, List *compareQual, ExprContext *econtext)
if (!DatumGetBool(const_value) || isNull) if (!DatumGetBool(const_value) || isNull)
break; /* return false */ break; /* return false */
eqclause = lnext(eqclause);
} }
MemoryContextSwitchTo(oldContext); MemoryContextSwitchTo(oldContext);

View File

@ -7,7 +7,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeSubplan.c,v 1.61 2004/03/17 01:02:23 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeSubplan.c,v 1.62 2004/05/26 04:41:16 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -212,8 +212,8 @@ ExecScanSubPlan(SubPlanState *node,
TupleTableSlot *slot; TupleTableSlot *slot;
Datum result; Datum result;
bool found = false; /* TRUE if got at least one subplan tuple */ bool found = false; /* TRUE if got at least one subplan tuple */
List *pvar; ListCell *pvar;
List *lst; ListCell *l;
ArrayBuildState *astate = NULL; ArrayBuildState *astate = NULL;
/* /*
@ -228,21 +228,19 @@ ExecScanSubPlan(SubPlanState *node,
* calculation we have to do is done in the parent econtext, since the * calculation we have to do is done in the parent econtext, since the
* Param values don't need to have per-query lifetime.) * Param values don't need to have per-query lifetime.)
*/ */
pvar = node->args; Assert(length(subplan->parParam) == length(node->args));
foreach(lst, subplan->parParam)
forboth(l, subplan->parParam, pvar, node->args)
{ {
int paramid = lfirsti(lst); int paramid = lfirst_int(l);
ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
Assert(pvar != NIL);
prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar), prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
econtext, econtext,
&(prm->isnull), &(prm->isnull),
NULL); NULL);
pvar = lnext(pvar);
planstate->chgParam = bms_add_member(planstate->chgParam, paramid); planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
} }
Assert(pvar == NIL);
ExecReScan(planstate, NULL); ExecReScan(planstate, NULL);
@ -278,7 +276,7 @@ ExecScanSubPlan(SubPlanState *node,
Datum rowresult = BoolGetDatum(!useOr); Datum rowresult = BoolGetDatum(!useOr);
bool rownull = false; bool rownull = false;
int col = 1; int col = 1;
List *plst; ListCell *plst;
if (subLinkType == EXISTS_SUBLINK) if (subLinkType == EXISTS_SUBLINK)
{ {
@ -343,11 +341,12 @@ ExecScanSubPlan(SubPlanState *node,
* For ALL, ANY, and MULTIEXPR sublinks, iterate over combining * For ALL, ANY, and MULTIEXPR sublinks, iterate over combining
* operators for columns of tuple. * operators for columns of tuple.
*/ */
plst = subplan->paramIds; Assert(length(node->exprs) == length(subplan->paramIds));
foreach(lst, node->exprs)
forboth(l, node->exprs, plst, subplan->paramIds)
{ {
ExprState *exprstate = (ExprState *) lfirst(lst); ExprState *exprstate = (ExprState *) lfirst(l);
int paramid = lfirsti(plst); int paramid = lfirst_int(plst);
ParamExecData *prmdata; ParamExecData *prmdata;
Datum expresult; Datum expresult;
bool expnull; bool expnull;
@ -400,7 +399,6 @@ ExecScanSubPlan(SubPlanState *node,
} }
} }
plst = lnext(plst);
col++; col++;
} }
@ -559,7 +557,7 @@ buildSubPlanHash(SubPlanState *node)
HeapTuple tup = slot->val; HeapTuple tup = slot->val;
TupleDesc tdesc = slot->ttc_tupleDescriptor; TupleDesc tdesc = slot->ttc_tupleDescriptor;
int col = 1; int col = 1;
List *plst; ListCell *plst;
bool isnew; bool isnew;
/* /*
@ -737,7 +735,7 @@ ExecInitSubPlan(SubPlanState *node, EState *estate)
*/ */
if (subplan->setParam != NIL) if (subplan->setParam != NIL)
{ {
List *lst; ListCell *lst;
foreach(lst, subplan->setParam) foreach(lst, subplan->setParam)
{ {
@ -762,8 +760,8 @@ ExecInitSubPlan(SubPlanState *node, EState *estate)
List *lefttlist, List *lefttlist,
*righttlist, *righttlist,
*leftptlist, *leftptlist,
*rightptlist, *rightptlist;
*lexpr; ListCell *lexpr;
/* We need a memory context to hold the hash table(s) */ /* We need a memory context to hold the hash table(s) */
node->tablecxt = node->tablecxt =
@ -815,7 +813,7 @@ ExecInitSubPlan(SubPlanState *node, EState *estate)
Assert(length(fstate->args) == 2); Assert(length(fstate->args) == 2);
/* Process lefthand argument */ /* Process lefthand argument */
exstate = (ExprState *) lfirst(fstate->args); exstate = (ExprState *) linitial(fstate->args);
expr = exstate->expr; expr = exstate->expr;
tle = makeTargetEntry(makeResdom(i, tle = makeTargetEntry(makeResdom(i,
exprType((Node *) expr), exprType((Node *) expr),
@ -914,7 +912,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
SubLinkType subLinkType = subplan->subLinkType; SubLinkType subLinkType = subplan->subLinkType;
MemoryContext oldcontext; MemoryContext oldcontext;
TupleTableSlot *slot; TupleTableSlot *slot;
List *lst; ListCell *l;
bool found = false; bool found = false;
ArrayBuildState *astate = NULL; ArrayBuildState *astate = NULL;
@ -941,7 +939,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
if (subLinkType == EXISTS_SUBLINK) if (subLinkType == EXISTS_SUBLINK)
{ {
/* There can be only one param... */ /* There can be only one param... */
int paramid = lfirsti(subplan->setParam); int paramid = linitial_int(subplan->setParam);
ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
prm->execPlan = NULL; prm->execPlan = NULL;
@ -992,9 +990,9 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
/* /*
* Now set all the setParam params from the columns of the tuple * Now set all the setParam params from the columns of the tuple
*/ */
foreach(lst, subplan->setParam) foreach(l, subplan->setParam)
{ {
int paramid = lfirsti(lst); int paramid = lfirsti(l);
ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
prm->execPlan = NULL; prm->execPlan = NULL;
@ -1008,7 +1006,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
if (subLinkType == EXISTS_SUBLINK) if (subLinkType == EXISTS_SUBLINK)
{ {
/* There can be only one param... */ /* There can be only one param... */
int paramid = lfirsti(subplan->setParam); int paramid = linitial_int(subplan->setParam);
ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
prm->execPlan = NULL; prm->execPlan = NULL;
@ -1017,9 +1015,9 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
} }
else else
{ {
foreach(lst, subplan->setParam) foreach(l, subplan->setParam)
{ {
int paramid = lfirsti(lst); int paramid = lfirsti(l);
ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
prm->execPlan = NULL; prm->execPlan = NULL;
@ -1031,7 +1029,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
else if (subLinkType == ARRAY_SUBLINK) else if (subLinkType == ARRAY_SUBLINK)
{ {
/* There can be only one param... */ /* There can be only one param... */
int paramid = lfirsti(subplan->setParam); int paramid = linitial_int(subplan->setParam);
ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]); ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
Assert(astate != NULL); Assert(astate != NULL);
@ -1074,7 +1072,7 @@ ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent)
PlanState *planstate = node->planstate; PlanState *planstate = node->planstate;
SubPlan *subplan = (SubPlan *) node->xprstate.expr; SubPlan *subplan = (SubPlan *) node->xprstate.expr;
EState *estate = parent->state; EState *estate = parent->state;
List *lst; ListCell *l;
/* sanity checks */ /* sanity checks */
if (subplan->parParam != NIL) if (subplan->parParam != NIL)
@ -1091,9 +1089,9 @@ ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent)
/* /*
* Mark this subplan's output parameters as needing recalculation * Mark this subplan's output parameters as needing recalculation
*/ */
foreach(lst, subplan->setParam) foreach(l, subplan->setParam)
{ {
int paramid = lfirsti(lst); int paramid = lfirsti(l);
ParamExecData *prm = &(estate->es_param_exec_vals[paramid]); ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
prm->execPlan = node; prm->execPlan = node;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/nodeTidscan.c,v 1.37 2004/04/21 18:24:26 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/nodeTidscan.c,v 1.38 2004/05/26 04:41:16 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -45,18 +45,18 @@ TidListCreate(TidScanState *tidstate)
ExprContext *econtext = tidstate->ss.ps.ps_ExprContext; ExprContext *econtext = tidstate->ss.ps.ps_ExprContext;
ItemPointerData *tidList; ItemPointerData *tidList;
int numTids = 0; int numTids = 0;
List *lst; ListCell *l;
tidList = (ItemPointerData *) tidList = (ItemPointerData *)
palloc(length(tidstate->tss_tideval) * sizeof(ItemPointerData)); palloc(length(tidstate->tss_tideval) * sizeof(ItemPointerData));
foreach(lst, evalList) foreach(l, evalList)
{ {
ItemPointer itemptr; ItemPointer itemptr;
bool isNull; bool isNull;
itemptr = (ItemPointer) itemptr = (ItemPointer)
DatumGetPointer(ExecEvalExprSwitchContext(lfirst(lst), DatumGetPointer(ExecEvalExprSwitchContext(lfirst(l),
econtext, econtext,
&isNull, &isNull,
NULL)); NULL));

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/executor/spi.c,v 1.113 2004/04/01 21:28:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/executor/spi.c,v 1.114 2004/05/26 04:41:16 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -744,8 +744,8 @@ SPI_cursor_open(const char *name, void *plan, Datum *Values, const char *Nulls)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_CURSOR_DEFINITION), (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
errmsg("cannot open multi-query plan as cursor"))); errmsg("cannot open multi-query plan as cursor")));
queryTree = (Query *) lfirst((List *) lfirst(qtlist)); queryTree = (Query *) linitial((List *) linitial(qtlist));
planTree = (Plan *) lfirst(ptlist); planTree = (Plan *) linitial(ptlist);
if (queryTree->commandType != CMD_SELECT) if (queryTree->commandType != CMD_SELECT)
ereport(ERROR, ereport(ERROR,
@ -953,7 +953,7 @@ SPI_is_cursor_plan(void *plan)
qtlist = spiplan->qtlist; qtlist = spiplan->qtlist;
if (length(spiplan->ptlist) == 1 && length(qtlist) == 1) if (length(spiplan->ptlist) == 1 && length(qtlist) == 1)
{ {
Query *queryTree = (Query *) lfirst((List *) lfirst(qtlist)); Query *queryTree = (Query *) linitial((List *) linitial(qtlist));
if (queryTree->commandType == CMD_SELECT && queryTree->into == NULL) if (queryTree->commandType == CMD_SELECT && queryTree->into == NULL)
return true; return true;
@ -1062,7 +1062,7 @@ _SPI_execute(const char *src, int tcount, _SPI_plan *plan)
List *raw_parsetree_list; List *raw_parsetree_list;
List *query_list_list; List *query_list_list;
List *plan_list; List *plan_list;
List *list_item; ListCell *list_item;
ErrorContextCallback spierrcontext; ErrorContextCallback spierrcontext;
int nargs = 0; int nargs = 0;
Oid *argtypes = NULL; Oid *argtypes = NULL;
@ -1110,7 +1110,7 @@ _SPI_execute(const char *src, int tcount, _SPI_plan *plan)
{ {
Node *parsetree = (Node *) lfirst(list_item); Node *parsetree = (Node *) lfirst(list_item);
List *query_list; List *query_list;
List *query_list_item; ListCell *query_list_item;
query_list = pg_analyze_and_rewrite(parsetree, argtypes, nargs); query_list = pg_analyze_and_rewrite(parsetree, argtypes, nargs);
@ -1207,8 +1207,8 @@ _SPI_execute_plan(_SPI_plan *plan, Datum *Values, const char *Nulls,
bool useCurrentSnapshot, int tcount) bool useCurrentSnapshot, int tcount)
{ {
List *query_list_list = plan->qtlist; List *query_list_list = plan->qtlist;
List *plan_list = plan->ptlist; ListCell *plan_list_item = list_head(plan->ptlist);
List *query_list_list_item; ListCell *query_list_list_item;
ErrorContextCallback spierrcontext; ErrorContextCallback spierrcontext;
int nargs = plan->nargs; int nargs = plan->nargs;
int res = 0; int res = 0;
@ -1254,7 +1254,7 @@ _SPI_execute_plan(_SPI_plan *plan, Datum *Values, const char *Nulls,
foreach(query_list_list_item, query_list_list) foreach(query_list_list_item, query_list_list)
{ {
List *query_list = lfirst(query_list_list_item); List *query_list = lfirst(query_list_list_item);
List *query_list_item; ListCell *query_list_item;
/* Reset state for each original parsetree */ /* Reset state for each original parsetree */
/* (at most one of its querytrees will be marked canSetTag) */ /* (at most one of its querytrees will be marked canSetTag) */
@ -1270,8 +1270,8 @@ _SPI_execute_plan(_SPI_plan *plan, Datum *Values, const char *Nulls,
QueryDesc *qdesc; QueryDesc *qdesc;
DestReceiver *dest; DestReceiver *dest;
planTree = lfirst(plan_list); planTree = lfirst(plan_list_item);
plan_list = lnext(plan_list); plan_list_item = lnext(plan_list_item);
dest = CreateDestReceiver(queryTree->canSetTag ? SPI : None, NULL); dest = CreateDestReceiver(queryTree->canSetTag ? SPI : None, NULL);
if (queryTree->commandType == CMD_UTILITY) if (queryTree->commandType == CMD_UTILITY)

View File

@ -9,7 +9,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* $PostgreSQL: pgsql/src/backend/libpq/crypt.c,v 1.58 2003/11/29 19:51:49 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/libpq/crypt.c,v 1.59 2004/05/26 04:41:18 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -36,14 +36,14 @@ md5_crypt_verify(const Port *port, const char *user, char *client_pass)
*crypt_pwd; *crypt_pwd;
int retval = STATUS_ERROR; int retval = STATUS_ERROR;
List **line; List **line;
List *token; ListCell *token;
char *crypt_client_pass = client_pass; char *crypt_client_pass = client_pass;
if ((line = get_user_line(user)) == NULL) if ((line = get_user_line(user)) == NULL)
return STATUS_ERROR; return STATUS_ERROR;
/* Skip over line number and username */ /* Skip over username */
token = lnext(lnext(*line)); token = lnext(list_head(*line));
if (token) if (token)
{ {
shadow_pass = lfirst(token); shadow_pass = lfirst(token);

View File

@ -10,12 +10,14 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/libpq/hba.c,v 1.122 2004/05/25 19:11:14 tgl Exp $ * $PostgreSQL: pgsql/src/backend/libpq/hba.c,v 1.123 2004/05/26 04:41:18 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
#include "postgres.h" #include "postgres.h"
#define DISABLE_LIST_COMPAT
#include <errno.h> #include <errno.h>
#include <pwd.h> #include <pwd.h>
#include <fcntl.h> #include <fcntl.h>
@ -63,11 +65,19 @@
* one string per token on the line. Note there will always be at least * one string per token on the line. Note there will always be at least
* one token, since blank lines are not entered in the data structure. * one token, since blank lines are not entered in the data structure.
*/ */
static List *hba_lines = NIL; /* pre-parsed contents of hba file */
static List *ident_lines = NIL; /* pre-parsed contents of ident file */ /* pre-parsed content of CONF_FILE and corresponding line #s */
static List *group_lines = NIL; /* pre-parsed contents of group file */ static List *hba_lines = NIL;
static List *user_lines = NIL; /* pre-parsed contents of user password static List *hba_line_nums = NIL;
* file */ /* pre-parsed content of USERMAP_FILE and corresponding line #s */
static List *ident_lines = NIL;
static List *ident_line_nums = NIL;
/* pre-parsed content of group file and corresponding line #s */
static List *group_lines = NIL;
static List *group_line_nums = NIL;
/* pre-parsed content of user passwd file and corresponding line #s */
static List *user_lines = NIL;
static List *user_line_nums = NIL;
/* sorted entries so we can do binary search lookups */ /* sorted entries so we can do binary search lookups */
static List **user_sorted = NULL; /* sorted user list, for bsearch() */ static List **user_sorted = NULL; /* sorted user list, for bsearch() */
@ -76,7 +86,7 @@ static List **group_sorted = NULL; /* sorted group list, for
static int user_length; static int user_length;
static int group_length; static int group_length;
static List *tokenize_file(FILE *file); static void tokenize_file(FILE *file, List **lines, List **line_nums);
static char *tokenize_inc_file(const char *inc_filename); static char *tokenize_inc_file(const char *inc_filename);
/* /*
@ -250,28 +260,45 @@ next_token_expand(FILE *file)
* Free memory used by lines/tokens (i.e., structure built by tokenize_file) * Free memory used by lines/tokens (i.e., structure built by tokenize_file)
*/ */
static void static void
free_lines(List **lines) free_lines(List **lines, List **line_nums)
{ {
/*
* Either both must be non-NULL, or both must be NULL
*/
Assert((*lines != NIL && *line_nums != NIL) ||
(*lines == NIL && *line_nums == NIL));
if (*lines) if (*lines)
{ {
List *line, /*
*token; * "lines" is a list of lists; each of those sublists consists
* of palloc'ed tokens, so we want to free each pointed-to
* token in a sublist, followed by the sublist itself, and
* finally the whole list.
*/
ListCell *line;
foreach(line, *lines) foreach(line, *lines)
{ {
List *ln = lfirst(line); List *ln = lfirst(line);
ListCell *token;
/* free the pstrdup'd tokens (don't try it on the line number) */ foreach(token, ln)
foreach(token, lnext(ln))
pfree(lfirst(token)); pfree(lfirst(token));
/* free the sublist structure itself */ /* free the sublist structure itself */
freeList(ln); list_free(ln);
} }
/* free the list structure itself */ /* free the list structure itself */
freeList(*lines); list_free(*lines);
/* clear the static variable */ /* clear the static variable */
*lines = NIL; *lines = NIL;
} }
if (*line_nums)
{
list_free(*line_nums);
*line_nums = NIL;
}
} }
@ -281,7 +308,8 @@ tokenize_inc_file(const char *inc_filename)
char *inc_fullname; char *inc_fullname;
FILE *inc_file; FILE *inc_file;
List *inc_lines; List *inc_lines;
List *line; List *inc_line_nums;
ListCell *line;
char *comma_str = pstrdup(""); char *comma_str = pstrdup("");
inc_fullname = (char *) palloc(strlen(DataDir) + 1 + inc_fullname = (char *) palloc(strlen(DataDir) + 1 +
@ -305,17 +333,16 @@ tokenize_inc_file(const char *inc_filename)
pfree(inc_fullname); pfree(inc_fullname);
/* There is possible recursion here if the file contains @ */ /* There is possible recursion here if the file contains @ */
inc_lines = tokenize_file(inc_file); tokenize_file(inc_file, &inc_lines, &inc_line_nums);
FreeFile(inc_file); FreeFile(inc_file);
/* Create comma-separate string from List */ /* Create comma-separate string from List */
foreach(line, inc_lines) foreach(line, inc_lines)
{ {
List *ln = lfirst(line); List *token_list = (List *) lfirst(line);
List *token; ListCell *token;
/* First entry is line number */ foreach(token, token_list)
foreach(token, lnext(ln))
{ {
if (strlen(comma_str)) if (strlen(comma_str))
{ {
@ -328,24 +355,26 @@ tokenize_inc_file(const char *inc_filename)
} }
} }
free_lines(&inc_lines); free_lines(&inc_lines, &inc_line_nums);
return comma_str; return comma_str;
} }
/* /*
* Read the given file and create a list of line sublists. * Tokenize the given file, storing the resulting data into two lists:
* a list of sublists, each sublist containing the tokens in a line of
* the file, and a list of line numbers.
*/ */
static List * static void
tokenize_file(FILE *file) tokenize_file(FILE *file, List **lines, List **line_nums)
{ {
List *lines = NIL; List *current_line = NIL;
List *next_line = NIL;
int line_number = 1; int line_number = 1;
char *buf; char *buf;
*lines = *line_nums = NIL;
while (!feof(file)) while (!feof(file))
{ {
buf = next_token_expand(file); buf = next_token_expand(file);
@ -353,27 +382,27 @@ tokenize_file(FILE *file)
/* add token to list, unless we are at EOL or comment start */ /* add token to list, unless we are at EOL or comment start */
if (buf[0] != '\0') if (buf[0] != '\0')
{ {
if (next_line == NIL) if (current_line == NIL)
{ {
/* make a new line List */ /* make a new line List, record its line number */
next_line = makeListi1(line_number); current_line = lappend(current_line, buf);
lines = lappend(lines, next_line); *lines = lappend(*lines, current_line);
*line_nums = lappend_int(*line_nums, line_number);
} }
else
{
/* append token to current line's list */ /* append token to current line's list */
next_line = lappend(next_line, buf); current_line = lappend(current_line, buf);
}
} }
else else
{ {
/* we are at real or logical EOL, so force a new line List */ /* we are at real or logical EOL, so force a new line List */
next_line = NIL; current_line = NIL;
}
/* Advance line number whenever we reach EOL */ /* Advance line number whenever we reach EOL */
if (next_line == NIL)
line_number++; line_number++;
} }
}
return lines;
} }
@ -385,9 +414,8 @@ tokenize_file(FILE *file)
static int static int
user_group_qsort_cmp(const void *list1, const void *list2) user_group_qsort_cmp(const void *list1, const void *list2)
{ {
/* first node is line number */ char *user1 = linitial(*(List **) list1);
char *user1 = lfirst(lnext(*(List **) list1)); char *user2 = linitial(*(List **) list2);
char *user2 = lfirst(lnext(*(List **) list2));
return strcmp(user1, user2); return strcmp(user1, user2);
} }
@ -401,8 +429,7 @@ user_group_qsort_cmp(const void *list1, const void *list2)
static int static int
user_group_bsearch_cmp(const void *user, const void *list) user_group_bsearch_cmp(const void *user, const void *list)
{ {
/* first node is line number */ char *user2 = linitial(*(List **) list);
char *user2 = lfirst(lnext(*(List **) list));
return strcmp(user, user2); return strcmp(user, user2);
} }
@ -450,15 +477,19 @@ get_user_line(const char *user)
static bool static bool
check_group(char *group, char *user) check_group(char *group, char *user)
{ {
List **line, List **line;
*l;
if ((line = get_group_line(group)) != NULL) if ((line = get_group_line(group)) != NULL)
{ {
foreach(l, lnext(lnext(*line))) ListCell *line_item;
if (strcmp(lfirst(l), user) == 0)
/* skip over the group name */
for_each_cell(line_item, lnext(list_head(*line)))
{
if (strcmp(lfirst(line_item), user) == 0)
return true; return true;
} }
}
return false; return false;
} }
@ -518,24 +549,24 @@ check_db(char *dbname, char *user, char *param_str)
/* /*
* Scan the rest of a host record (after the mask field) * Scan the rest of a host record (after the mask field)
* and return the interpretation of it as *userauth_p, *auth_arg_p, and * and return the interpretation of it as *userauth_p, *auth_arg_p, and
* *error_p. *line points to the next token of the line, and is * *error_p. *line_item points to the next token of the line, and is
* advanced over successfully-read tokens. * advanced over successfully-read tokens.
*/ */
static void static void
parse_hba_auth(List **line, UserAuth *userauth_p, char **auth_arg_p, parse_hba_auth(ListCell **line_item, UserAuth *userauth_p,
bool *error_p) char **auth_arg_p, bool *error_p)
{ {
char *token; char *token;
*auth_arg_p = NULL; *auth_arg_p = NULL;
/* Get authentication type token. */ if (!*line_item)
if (!*line)
{ {
*error_p = true; *error_p = true;
return; return;
} }
token = lfirst(*line);
token = lfirst(*line_item);
if (strcmp(token, "trust") == 0) if (strcmp(token, "trust") == 0)
*userauth_p = uaTrust; *userauth_p = uaTrust;
else if (strcmp(token, "ident") == 0) else if (strcmp(token, "ident") == 0)
@ -561,16 +592,16 @@ parse_hba_auth(List **line, UserAuth *userauth_p, char **auth_arg_p,
*error_p = true; *error_p = true;
return; return;
} }
*line = lnext(*line); *line_item = lnext(*line_item);
/* Get the authentication argument token, if any */ /* Get the authentication argument token, if any */
if (*line) if (*line_item)
{ {
token = lfirst(*line); token = lfirst(*line_item);
*auth_arg_p = pstrdup(token); *auth_arg_p = pstrdup(token);
*line = lnext(*line); *line_item = lnext(*line_item);
/* If there is more on the line, it is an error */ /* If there is more on the line, it is an error */
if (*line) if (*line_item)
*error_p = true; *error_p = true;
} }
} }
@ -587,9 +618,9 @@ parse_hba_auth(List **line, UserAuth *userauth_p, char **auth_arg_p,
* leave *error_p as it was. * leave *error_p as it was.
*/ */
static void static void
parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p) parse_hba(List *line, int line_num, hbaPort *port,
bool *found_p, bool *error_p)
{ {
int line_number;
char *token; char *token;
char *db; char *db;
char *user; char *user;
@ -599,33 +630,32 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
struct sockaddr_storage addr; struct sockaddr_storage addr;
struct sockaddr_storage mask; struct sockaddr_storage mask;
char *cidr_slash; char *cidr_slash;
ListCell *line_item;
Assert(line != NIL); line_item = list_head(line);
line_number = lfirsti(line);
line = lnext(line);
Assert(line != NIL);
/* Check the record type. */ /* Check the record type. */
token = lfirst(line); token = lfirst(line_item);
if (strcmp(token, "local") == 0) if (strcmp(token, "local") == 0)
{ {
/* Get the database. */ /* Get the database. */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
db = lfirst(line); db = lfirst(line_item);
/* Get the user. */ /* Get the user. */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
user = lfirst(line); user = lfirst(line_item);
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
/* Read the rest of the line. */ /* Read the rest of the line. */
parse_hba_auth(&line, &port->auth_method, &port->auth_arg, error_p); parse_hba_auth(&line_item, &port->auth_method,
&port->auth_arg, error_p);
if (*error_p) if (*error_p)
goto hba_syntax; goto hba_syntax;
@ -669,22 +699,22 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
#endif #endif
/* Get the database. */ /* Get the database. */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
db = lfirst(line); db = lfirst(line_item);
/* Get the user. */ /* Get the user. */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
user = lfirst(line); user = lfirst(line_item);
/* Read the IP address field. (with or without CIDR netmask) */ /* Read the IP address field. (with or without CIDR netmask) */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
token = lfirst(line); token = lfirst(line_item);
/* Check if it has a CIDR suffix and if so isolate it */ /* Check if it has a CIDR suffix and if so isolate it */
cidr_slash = strchr(token, '/'); cidr_slash = strchr(token, '/');
@ -707,7 +737,7 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("invalid IP address \"%s\" in pg_hba.conf file line %d: %s", errmsg("invalid IP address \"%s\" in pg_hba.conf file line %d: %s",
token, line_number, gai_strerror(ret)))); token, line_num, gai_strerror(ret))));
if (cidr_slash) if (cidr_slash)
*cidr_slash = '/'; *cidr_slash = '/';
if (gai_result) if (gai_result)
@ -730,10 +760,10 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
else else
{ {
/* Read the mask field. */ /* Read the mask field. */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
token = lfirst(line); token = lfirst(line_item);
ret = getaddrinfo_all(token, NULL, &hints, &gai_result); ret = getaddrinfo_all(token, NULL, &hints, &gai_result);
if (ret || !gai_result) if (ret || !gai_result)
@ -741,7 +771,7 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("invalid IP mask \"%s\" in pg_hba.conf file line %d: %s", errmsg("invalid IP mask \"%s\" in pg_hba.conf file line %d: %s",
token, line_number, gai_strerror(ret)))); token, line_num, gai_strerror(ret))));
if (gai_result) if (gai_result)
freeaddrinfo_all(hints.ai_family, gai_result); freeaddrinfo_all(hints.ai_family, gai_result);
goto hba_other_error; goto hba_other_error;
@ -755,7 +785,7 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("IP address and mask do not match in pg_hba.conf file line %d", errmsg("IP address and mask do not match in pg_hba.conf file line %d",
line_number))); line_num)));
goto hba_other_error; goto hba_other_error;
} }
} }
@ -787,10 +817,11 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
return; return;
/* Read the rest of the line. */ /* Read the rest of the line. */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line_item)
goto hba_syntax; goto hba_syntax;
parse_hba_auth(&line, &port->auth_method, &port->auth_arg, error_p); parse_hba_auth(&line_item, &port->auth_method,
&port->auth_arg, error_p);
if (*error_p) if (*error_p)
goto hba_syntax; goto hba_syntax;
} }
@ -808,16 +839,16 @@ parse_hba(List *line, hbaPort *port, bool *found_p, bool *error_p)
return; return;
hba_syntax: hba_syntax:
if (line) if (line_item)
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("invalid entry in pg_hba.conf file at line %d, token \"%s\"", errmsg("invalid entry in pg_hba.conf file at line %d, token \"%s\"",
line_number, (const char *) lfirst(line)))); line_num, (char *) lfirst(line_item))));
else else
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("missing field in pg_hba.conf file at end of line %d", errmsg("missing field in pg_hba.conf file at end of line %d",
line_number))); line_num)));
/* Come here if suitable message already logged */ /* Come here if suitable message already logged */
hba_other_error: hba_other_error:
@ -834,11 +865,13 @@ check_hba(hbaPort *port)
{ {
bool found_entry = false; bool found_entry = false;
bool error = false; bool error = false;
List *line; ListCell *line;
ListCell *line_num;
foreach(line, hba_lines) forboth(line, hba_lines, line_num, hba_line_nums)
{ {
parse_hba(lfirst(line), port, &found_entry, &error); parse_hba(lfirst(line), lfirst_int(line_num),
port, &found_entry, &error);
if (found_entry || error) if (found_entry || error)
break; break;
} }
@ -911,11 +944,10 @@ void
load_group(void) load_group(void)
{ {
FILE *group_file; FILE *group_file;
List *line;
/* Discard any old data */ /* Discard any old data */
if (group_lines) if (group_lines || group_line_nums)
free_lines(&group_lines); free_lines(&group_lines, &group_line_nums);
if (group_sorted) if (group_sorted)
pfree(group_sorted); pfree(group_sorted);
group_sorted = NULL; group_sorted = NULL;
@ -924,14 +956,15 @@ load_group(void)
group_file = group_openfile(); group_file = group_openfile();
if (!group_file) if (!group_file)
return; return;
group_lines = tokenize_file(group_file); tokenize_file(group_file, &group_lines, &group_line_nums);
FreeFile(group_file); FreeFile(group_file);
/* create sorted lines for binary searching */ /* create sorted lines for binary searching */
group_length = length(group_lines); group_length = list_length(group_lines);
if (group_length) if (group_length)
{ {
int i = 0; int i = 0;
ListCell *line;
group_sorted = palloc(group_length * sizeof(List *)); group_sorted = palloc(group_length * sizeof(List *));
@ -953,11 +986,10 @@ void
load_user(void) load_user(void)
{ {
FILE *user_file; FILE *user_file;
List *line;
/* Discard any old data */ /* Discard any old data */
if (user_lines) if (user_lines || user_line_nums)
free_lines(&user_lines); free_lines(&user_lines, &user_line_nums);
if (user_sorted) if (user_sorted)
pfree(user_sorted); pfree(user_sorted);
user_sorted = NULL; user_sorted = NULL;
@ -966,14 +998,15 @@ load_user(void)
user_file = user_openfile(); user_file = user_openfile();
if (!user_file) if (!user_file)
return; return;
user_lines = tokenize_file(user_file); tokenize_file(user_file, &user_lines, &user_line_nums);
FreeFile(user_file); FreeFile(user_file);
/* create sorted lines for binary searching */ /* create sorted lines for binary searching */
user_length = length(user_lines); user_length = list_length(user_lines);
if (user_length) if (user_length)
{ {
int i = 0; int i = 0;
ListCell *line;
user_sorted = palloc(user_length * sizeof(List *)); user_sorted = palloc(user_length * sizeof(List *));
@ -1002,8 +1035,8 @@ load_hba(void)
FILE *file; /* The config file we have to read */ FILE *file; /* The config file we have to read */
char *conf_file; /* The name of the config file */ char *conf_file; /* The name of the config file */
if (hba_lines) if (hba_lines || hba_line_nums)
free_lines(&hba_lines); free_lines(&hba_lines, &hba_line_nums);
/* Put together the full pathname to the config file. */ /* Put together the full pathname to the config file. */
bufsize = (strlen(DataDir) + strlen(CONF_FILE) + 2) * sizeof(char); bufsize = (strlen(DataDir) + strlen(CONF_FILE) + 2) * sizeof(char);
@ -1017,7 +1050,7 @@ load_hba(void)
errmsg("could not open configuration file \"%s\": %m", errmsg("could not open configuration file \"%s\": %m",
conf_file))); conf_file)));
hba_lines = tokenize_file(file); tokenize_file(file, &hba_lines, &hba_line_nums);
FreeFile(file); FreeFile(file);
pfree(conf_file); pfree(conf_file);
} }
@ -1030,10 +1063,11 @@ load_hba(void)
* *found_p and *error_p are set according to our results. * *found_p and *error_p are set according to our results.
*/ */
static void static void
parse_ident_usermap(List *line, const char *usermap_name, const char *pg_user, parse_ident_usermap(List *line, int line_number, const char *usermap_name,
const char *ident_user, bool *found_p, bool *error_p) const char *pg_user, const char *ident_user,
bool *found_p, bool *error_p)
{ {
int line_number; ListCell *line_item;
char *token; char *token;
char *file_map; char *file_map;
char *file_pguser; char *file_pguser;
@ -1043,26 +1077,24 @@ parse_ident_usermap(List *line, const char *usermap_name, const char *pg_user,
*error_p = false; *error_p = false;
Assert(line != NIL); Assert(line != NIL);
line_number = lfirsti(line); line_item = list_head(line);
line = lnext(line);
Assert(line != NIL);
/* Get the map token (must exist) */ /* Get the map token (must exist) */
token = lfirst(line); token = lfirst(line_item);
file_map = token; file_map = token;
/* Get the ident user token (must be provided) */ /* Get the ident user token (must be provided) */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line)
goto ident_syntax; goto ident_syntax;
token = lfirst(line); token = lfirst(line_item);
file_ident_user = token; file_ident_user = token;
/* Get the PG username token */ /* Get the PG username token */
line = lnext(line); line_item = lnext(line_item);
if (!line) if (!line)
goto ident_syntax; goto ident_syntax;
token = lfirst(line); token = lfirst(line_item);
file_pguser = token; file_pguser = token;
/* Match? */ /* Match? */
@ -1073,11 +1105,11 @@ parse_ident_usermap(List *line, const char *usermap_name, const char *pg_user,
return; return;
ident_syntax: ident_syntax:
if (line) if (line_item)
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("invalid entry in pg_ident.conf file at line %d, token \"%s\"", errmsg("invalid entry in pg_ident.conf file at line %d, token \"%s\"",
line_number, (const char *) lfirst(line)))); line_number, (const char *) lfirst(line_item))));
else else
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR), (errcode(ERRCODE_CONFIG_FILE_ERROR),
@ -1105,7 +1137,6 @@ check_ident_usermap(const char *usermap_name,
const char *pg_user, const char *pg_user,
const char *ident_user) const char *ident_user)
{ {
List *line;
bool found_entry = false, bool found_entry = false,
error = false; error = false;
@ -1125,10 +1156,13 @@ check_ident_usermap(const char *usermap_name,
} }
else else
{ {
foreach(line, ident_lines) ListCell *line_cell, *num_cell;
forboth(line_cell, ident_lines, num_cell, ident_line_nums)
{ {
parse_ident_usermap(lfirst(line), usermap_name, pg_user, parse_ident_usermap(lfirst(line_cell), lfirst_int(num_cell),
ident_user, &found_entry, &error); usermap_name, pg_user, ident_user,
&found_entry, &error);
if (found_entry || error) if (found_entry || error)
break; break;
} }
@ -1148,8 +1182,8 @@ load_ident(void)
* read */ * read */
int bufsize; int bufsize;
if (ident_lines) if (ident_lines || ident_line_nums)
free_lines(&ident_lines); free_lines(&ident_lines, &ident_line_nums);
/* put together the full pathname to the map file */ /* put together the full pathname to the map file */
bufsize = (strlen(DataDir) + strlen(USERMAP_FILE) + 2) * sizeof(char); bufsize = (strlen(DataDir) + strlen(USERMAP_FILE) + 2) * sizeof(char);
@ -1166,7 +1200,7 @@ load_ident(void)
} }
else else
{ {
ident_lines = tokenize_file(file); tokenize_file(file, &ident_lines, &ident_line_nums);
FreeFile(file); FreeFile(file);
} }
pfree(map_file); pfree(map_file);

View File

@ -15,11 +15,13 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/copyfuncs.c,v 1.281 2004/05/10 22:44:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/nodes/copyfuncs.c,v 1.282 2004/05/26 04:41:18 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
#define DISABLE_LIST_COMPAT
#include "postgres.h" #include "postgres.h"
#include "nodes/parsenodes.h" #include "nodes/parsenodes.h"
@ -43,14 +45,6 @@
#define COPY_NODE_FIELD(fldname) \ #define COPY_NODE_FIELD(fldname) \
(newnode->fldname = copyObject(from->fldname)) (newnode->fldname = copyObject(from->fldname))
/* Copy a field that is a pointer to a list of integers */
#define COPY_INTLIST_FIELD(fldname) \
(newnode->fldname = listCopy(from->fldname))
/* Copy a field that is a pointer to a list of Oids */
#define COPY_OIDLIST_FIELD(fldname) \
(newnode->fldname = listCopy(from->fldname))
/* Copy a field that is a pointer to a Bitmapset */ /* Copy a field that is a pointer to a Bitmapset */
#define COPY_BITMAPSET_FIELD(fldname) \ #define COPY_BITMAPSET_FIELD(fldname) \
(newnode->fldname = bms_copy(from->fldname)) (newnode->fldname = bms_copy(from->fldname))
@ -68,46 +62,6 @@
} while (0) } while (0)
/*
* listCopy
* This copy function only copies the "cons-cells" of the list, not the
* pointed-to objects. (Use copyObject if you want a "deep" copy.)
*
* We also use this function for copying lists of integers and Oids,
* which is notationally a bit ugly, but perfectly safe.
*
* Note that copyObject will surely coredump if applied to a list
* of integers or Oids!
*/
List *
listCopy(List *list)
{
List *newlist,
*oldl,
*newcell,
*prev;
/* rather ugly coding for speed... */
if (list == NIL)
return NIL;
newcell = makeNode(List);
newcell->elem = list->elem;
newlist = prev = newcell;
foreach(oldl, lnext(list))
{
newcell = makeNode(List);
newcell->elem = oldl->elem;
prev->next = newcell;
prev = newcell;
}
prev->next = NIL;
return newlist;
}
/* **************************************************************** /* ****************************************************************
* plannodes.h copy functions * plannodes.h copy functions
* **************************************************************** * ****************************************************************
@ -259,42 +213,12 @@ _copyIndexScan(IndexScan *from)
/* /*
* copy remainder of node * copy remainder of node
*/ */
COPY_OIDLIST_FIELD(indxid); COPY_NODE_FIELD(indxid);
COPY_NODE_FIELD(indxqual); COPY_NODE_FIELD(indxqual);
COPY_NODE_FIELD(indxqualorig); COPY_NODE_FIELD(indxqualorig);
/* this can become COPY_NODE_FIELD when intlists are normal objects: */ COPY_NODE_FIELD(indxstrategy);
{ COPY_NODE_FIELD(indxsubtype);
List *newstrat = NIL; COPY_NODE_FIELD(indxlossy);
List *tmp;
foreach(tmp, from->indxstrategy)
{
newstrat = lappend(newstrat, listCopy(lfirst(tmp)));
}
newnode->indxstrategy = newstrat;
}
/* this can become COPY_NODE_FIELD when OID lists are normal objects: */
{
List *newsubtype = NIL;
List *tmp;
foreach(tmp, from->indxsubtype)
{
newsubtype = lappend(newsubtype, listCopy(lfirst(tmp)));
}
newnode->indxsubtype = newsubtype;
}
/* this can become COPY_NODE_FIELD when intlists are normal objects: */
{
List *newstrat = NIL;
List *tmp;
foreach(tmp, from->indxlossy)
{
newstrat = lappend(newstrat, listCopy(lfirst(tmp)));
}
newnode->indxlossy = newstrat;
}
COPY_SCALAR_FIELD(indxorderdir); COPY_SCALAR_FIELD(indxorderdir);
return newnode; return newnode;
@ -876,7 +800,7 @@ _copySubLink(SubLink *from)
COPY_SCALAR_FIELD(useOr); COPY_SCALAR_FIELD(useOr);
COPY_NODE_FIELD(lefthand); COPY_NODE_FIELD(lefthand);
COPY_NODE_FIELD(operName); COPY_NODE_FIELD(operName);
COPY_OIDLIST_FIELD(operOids); COPY_NODE_FIELD(operOids);
COPY_NODE_FIELD(subselect); COPY_NODE_FIELD(subselect);
return newnode; return newnode;
@ -893,14 +817,14 @@ _copySubPlan(SubPlan *from)
COPY_SCALAR_FIELD(subLinkType); COPY_SCALAR_FIELD(subLinkType);
COPY_SCALAR_FIELD(useOr); COPY_SCALAR_FIELD(useOr);
COPY_NODE_FIELD(exprs); COPY_NODE_FIELD(exprs);
COPY_INTLIST_FIELD(paramIds); COPY_NODE_FIELD(paramIds);
COPY_NODE_FIELD(plan); COPY_NODE_FIELD(plan);
COPY_SCALAR_FIELD(plan_id); COPY_SCALAR_FIELD(plan_id);
COPY_NODE_FIELD(rtable); COPY_NODE_FIELD(rtable);
COPY_SCALAR_FIELD(useHashTable); COPY_SCALAR_FIELD(useHashTable);
COPY_SCALAR_FIELD(unknownEqFalse); COPY_SCALAR_FIELD(unknownEqFalse);
COPY_INTLIST_FIELD(setParam); COPY_NODE_FIELD(setParam);
COPY_INTLIST_FIELD(parParam); COPY_NODE_FIELD(parParam);
COPY_NODE_FIELD(args); COPY_NODE_FIELD(args);
return newnode; return newnode;
@ -1582,7 +1506,7 @@ _copyQuery(Query *from)
COPY_SCALAR_FIELD(hasSubLinks); COPY_SCALAR_FIELD(hasSubLinks);
COPY_NODE_FIELD(rtable); COPY_NODE_FIELD(rtable);
COPY_NODE_FIELD(jointree); COPY_NODE_FIELD(jointree);
COPY_INTLIST_FIELD(rowMarks); COPY_NODE_FIELD(rowMarks);
COPY_NODE_FIELD(targetList); COPY_NODE_FIELD(targetList);
COPY_NODE_FIELD(groupClause); COPY_NODE_FIELD(groupClause);
COPY_NODE_FIELD(havingQual); COPY_NODE_FIELD(havingQual);
@ -1591,7 +1515,7 @@ _copyQuery(Query *from)
COPY_NODE_FIELD(limitOffset); COPY_NODE_FIELD(limitOffset);
COPY_NODE_FIELD(limitCount); COPY_NODE_FIELD(limitCount);
COPY_NODE_FIELD(setOperations); COPY_NODE_FIELD(setOperations);
COPY_INTLIST_FIELD(resultRelations); COPY_NODE_FIELD(resultRelations);
COPY_NODE_FIELD(in_info_list); COPY_NODE_FIELD(in_info_list);
COPY_SCALAR_FIELD(hasJoinRTEs); COPY_SCALAR_FIELD(hasJoinRTEs);
@ -1679,7 +1603,7 @@ _copySetOperationStmt(SetOperationStmt *from)
COPY_SCALAR_FIELD(all); COPY_SCALAR_FIELD(all);
COPY_NODE_FIELD(larg); COPY_NODE_FIELD(larg);
COPY_NODE_FIELD(rarg); COPY_NODE_FIELD(rarg);
COPY_OIDLIST_FIELD(colTypes); COPY_NODE_FIELD(colTypes);
return newnode; return newnode;
} }
@ -1731,7 +1655,7 @@ _copyGrantStmt(GrantStmt *from)
COPY_SCALAR_FIELD(is_grant); COPY_SCALAR_FIELD(is_grant);
COPY_SCALAR_FIELD(objtype); COPY_SCALAR_FIELD(objtype);
COPY_NODE_FIELD(objects); COPY_NODE_FIELD(objects);
COPY_INTLIST_FIELD(privileges); COPY_NODE_FIELD(privileges);
COPY_NODE_FIELD(grantees); COPY_NODE_FIELD(grantees);
COPY_SCALAR_FIELD(grant_option); COPY_SCALAR_FIELD(grant_option);
COPY_SCALAR_FIELD(behavior); COPY_SCALAR_FIELD(behavior);
@ -2477,7 +2401,7 @@ _copyPrepareStmt(PrepareStmt *from)
COPY_STRING_FIELD(name); COPY_STRING_FIELD(name);
COPY_NODE_FIELD(argtypes); COPY_NODE_FIELD(argtypes);
COPY_OIDLIST_FIELD(argtype_oids); COPY_NODE_FIELD(argtype_oids);
COPY_NODE_FIELD(query); COPY_NODE_FIELD(query);
return newnode; return newnode;
@ -2511,6 +2435,47 @@ _copyDeallocateStmt(DeallocateStmt *from)
* **************************************************************** * ****************************************************************
*/ */
/*
* Perform a deep copy of the specified list, using copyObject(). The
* list MUST be of type T_List; T_IntList and T_OidList nodes don't
* need deep copies, so they should be copied via list_copy()
*/
#define COPY_NODE_CELL(new, old) \
(new) = (ListCell *) palloc(sizeof(ListCell)); \
lfirst(new) = copyObject(lfirst(old));
static List *
_copyList(List *from)
{
List *new;
ListCell *curr_old;
ListCell *prev_new;
Assert(list_length(from) >= 1);
new = makeNode(List);
new->length = from->length;
COPY_NODE_CELL(new->head, from->head);
prev_new = new->head;
curr_old = lnext(from->head);
while (curr_old)
{
COPY_NODE_CELL(prev_new->next, curr_old);
prev_new = prev_new->next;
curr_old = curr_old->next;
}
prev_new->next = NULL;
new->tail = prev_new;
return new;
}
/* ****************************************************************
* value.h copy functions
* ****************************************************************
*/
static Value * static Value *
_copyValue(Value *from) _copyValue(Value *from)
{ {
@ -2752,30 +2717,21 @@ copyObject(void *from)
case T_Null: case T_Null:
retval = _copyValue(from); retval = _copyValue(from);
break; break;
/*
* LIST NODES
*/
case T_List: case T_List:
{ retval = _copyList(from);
List *list = from, break;
*oldl, /*
*newcell, * Lists of integers and OIDs don't need to be
*prev; * deep-copied, so we perform a shallow copy via
* list_copy()
/* rather ugly coding for speed... */ */
/* Note the input list cannot be NIL if we got here. */ case T_IntList:
newcell = makeNode(List); case T_OidList:
lfirst(newcell) = copyObject(lfirst(list)); retval = list_copy(from);
retval = (void *) newcell;
prev = newcell;
foreach(oldl, lnext(list))
{
newcell = makeNode(List);
lfirst(newcell) = copyObject(lfirst(oldl));
prev->next = newcell;
prev = newcell;
}
prev->next = NIL;
}
break; break;
/* /*

View File

@ -18,11 +18,13 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/equalfuncs.c,v 1.220 2004/05/10 22:44:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/nodes/equalfuncs.c,v 1.221 2004/05/26 04:41:19 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
#define DISABLE_LIST_COMPAT
#include "postgres.h" #include "postgres.h"
#include "nodes/params.h" #include "nodes/params.h"
@ -52,20 +54,6 @@
return false; \ return false; \
} while (0) } while (0)
/* Compare a field that is a pointer to a list of integers */
#define COMPARE_INTLIST_FIELD(fldname) \
do { \
if (!equali(a->fldname, b->fldname)) \
return false; \
} while (0)
/* Compare a field that is a pointer to a list of Oids */
#define COMPARE_OIDLIST_FIELD(fldname) \
do { \
if (!equalo(a->fldname, b->fldname)) \
return false; \
} while (0)
/* Compare a field that is a pointer to a Bitmapset */ /* Compare a field that is a pointer to a Bitmapset */
#define COMPARE_BITMAPSET_FIELD(fldname) \ #define COMPARE_BITMAPSET_FIELD(fldname) \
do { \ do { \
@ -328,7 +316,7 @@ _equalSubLink(SubLink *a, SubLink *b)
COMPARE_SCALAR_FIELD(useOr); COMPARE_SCALAR_FIELD(useOr);
COMPARE_NODE_FIELD(lefthand); COMPARE_NODE_FIELD(lefthand);
COMPARE_NODE_FIELD(operName); COMPARE_NODE_FIELD(operName);
COMPARE_OIDLIST_FIELD(operOids); COMPARE_NODE_FIELD(operOids);
COMPARE_NODE_FIELD(subselect); COMPARE_NODE_FIELD(subselect);
return true; return true;
@ -340,14 +328,14 @@ _equalSubPlan(SubPlan *a, SubPlan *b)
COMPARE_SCALAR_FIELD(subLinkType); COMPARE_SCALAR_FIELD(subLinkType);
COMPARE_SCALAR_FIELD(useOr); COMPARE_SCALAR_FIELD(useOr);
COMPARE_NODE_FIELD(exprs); COMPARE_NODE_FIELD(exprs);
COMPARE_INTLIST_FIELD(paramIds); COMPARE_NODE_FIELD(paramIds);
/* should compare plans, but have to settle for comparing plan IDs */ /* should compare plans, but have to settle for comparing plan IDs */
COMPARE_SCALAR_FIELD(plan_id); COMPARE_SCALAR_FIELD(plan_id);
COMPARE_NODE_FIELD(rtable); COMPARE_NODE_FIELD(rtable);
COMPARE_SCALAR_FIELD(useHashTable); COMPARE_SCALAR_FIELD(useHashTable);
COMPARE_SCALAR_FIELD(unknownEqFalse); COMPARE_SCALAR_FIELD(unknownEqFalse);
COMPARE_INTLIST_FIELD(setParam); COMPARE_NODE_FIELD(setParam);
COMPARE_INTLIST_FIELD(parParam); COMPARE_NODE_FIELD(parParam);
COMPARE_NODE_FIELD(args); COMPARE_NODE_FIELD(args);
return true; return true;
@ -636,7 +624,7 @@ _equalQuery(Query *a, Query *b)
COMPARE_SCALAR_FIELD(hasSubLinks); COMPARE_SCALAR_FIELD(hasSubLinks);
COMPARE_NODE_FIELD(rtable); COMPARE_NODE_FIELD(rtable);
COMPARE_NODE_FIELD(jointree); COMPARE_NODE_FIELD(jointree);
COMPARE_INTLIST_FIELD(rowMarks); COMPARE_NODE_FIELD(rowMarks);
COMPARE_NODE_FIELD(targetList); COMPARE_NODE_FIELD(targetList);
COMPARE_NODE_FIELD(groupClause); COMPARE_NODE_FIELD(groupClause);
COMPARE_NODE_FIELD(havingQual); COMPARE_NODE_FIELD(havingQual);
@ -645,7 +633,7 @@ _equalQuery(Query *a, Query *b)
COMPARE_NODE_FIELD(limitOffset); COMPARE_NODE_FIELD(limitOffset);
COMPARE_NODE_FIELD(limitCount); COMPARE_NODE_FIELD(limitCount);
COMPARE_NODE_FIELD(setOperations); COMPARE_NODE_FIELD(setOperations);
COMPARE_INTLIST_FIELD(resultRelations); COMPARE_NODE_FIELD(resultRelations);
COMPARE_NODE_FIELD(in_info_list); COMPARE_NODE_FIELD(in_info_list);
COMPARE_SCALAR_FIELD(hasJoinRTEs); COMPARE_SCALAR_FIELD(hasJoinRTEs);
@ -720,7 +708,7 @@ _equalSetOperationStmt(SetOperationStmt *a, SetOperationStmt *b)
COMPARE_SCALAR_FIELD(all); COMPARE_SCALAR_FIELD(all);
COMPARE_NODE_FIELD(larg); COMPARE_NODE_FIELD(larg);
COMPARE_NODE_FIELD(rarg); COMPARE_NODE_FIELD(rarg);
COMPARE_OIDLIST_FIELD(colTypes); COMPARE_NODE_FIELD(colTypes);
return true; return true;
} }
@ -764,7 +752,7 @@ _equalGrantStmt(GrantStmt *a, GrantStmt *b)
COMPARE_SCALAR_FIELD(is_grant); COMPARE_SCALAR_FIELD(is_grant);
COMPARE_SCALAR_FIELD(objtype); COMPARE_SCALAR_FIELD(objtype);
COMPARE_NODE_FIELD(objects); COMPARE_NODE_FIELD(objects);
COMPARE_INTLIST_FIELD(privileges); COMPARE_NODE_FIELD(privileges);
COMPARE_NODE_FIELD(grantees); COMPARE_NODE_FIELD(grantees);
COMPARE_SCALAR_FIELD(grant_option); COMPARE_SCALAR_FIELD(grant_option);
COMPARE_SCALAR_FIELD(behavior); COMPARE_SCALAR_FIELD(behavior);
@ -1389,7 +1377,7 @@ _equalPrepareStmt(PrepareStmt *a, PrepareStmt *b)
{ {
COMPARE_STRING_FIELD(name); COMPARE_STRING_FIELD(name);
COMPARE_NODE_FIELD(argtypes); COMPARE_NODE_FIELD(argtypes);
COMPARE_OIDLIST_FIELD(argtype_oids); COMPARE_NODE_FIELD(argtype_oids);
COMPARE_NODE_FIELD(query); COMPARE_NODE_FIELD(query);
return true; return true;
@ -1648,6 +1636,65 @@ _equalFkConstraint(FkConstraint *a, FkConstraint *b)
* Stuff from pg_list.h * Stuff from pg_list.h
*/ */
static bool
_equalList(List *a, List *b)
{
ListCell *item_a;
ListCell *item_b;
/*
* Try to reject by simple scalar checks before grovelling through
* all the list elements...
*/
COMPARE_SCALAR_FIELD(type);
COMPARE_SCALAR_FIELD(length);
/*
* We place the switch outside the loop for the sake of
* efficiency; this may not be worth doing...
*/
switch (a->type)
{
case T_List:
forboth(item_a, a, item_b, b)
{
if (!equal(lfirst(item_a), lfirst(item_b)))
return false;
}
break;
case T_IntList:
forboth(item_a, a, item_b, b)
{
if (lfirst_int(item_a) != lfirst_int(item_b))
return false;
}
break;
case T_OidList:
forboth(item_a, a, item_b, b)
{
if (lfirst_oid(item_a) != lfirst_oid(item_b))
return false;
}
break;
default:
elog(ERROR, "unrecognized list node type: %d",
(int) a->type);
return false; /* keep compiler quiet */
}
/*
* If we got here, we should have run out of elements of both lists
*/
Assert(item_a == NULL);
Assert(item_b == NULL);
return true;
}
/*
* Stuff from value.h
*/
static bool static bool
_equalValue(Value *a, Value *b) _equalValue(Value *a, Value *b)
{ {
@ -1818,30 +1865,10 @@ equal(void *a, void *b)
case T_InClauseInfo: case T_InClauseInfo:
retval = _equalInClauseInfo(a, b); retval = _equalInClauseInfo(a, b);
break; break;
/*
* LIST NODES
*/
case T_List: case T_List:
{ case T_IntList:
List *la = (List *) a; case T_OidList:
List *lb = (List *) b; retval = _equalList(a, b);
List *l;
/*
* Try to reject by length check before we grovel through
* all the elements...
*/
if (length(la) != length(lb))
return false;
foreach(l, la)
{
if (!equal(lfirst(l), lfirst(lb)))
return false;
lb = lnext(lb);
}
retval = true;
}
break; break;
case T_Integer: case T_Integer:

File diff suppressed because it is too large Load Diff

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/outfuncs.c,v 1.236 2004/05/10 22:44:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/nodes/outfuncs.c,v 1.237 2004/05/26 04:41:19 neilc Exp $
* *
* NOTES * NOTES
* Every node type that can appear in stored rules' parsetrees *must* * Every node type that can appear in stored rules' parsetrees *must*
@ -19,6 +19,8 @@
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
#define DISABLE_LIST_COMPAT
#include "postgres.h" #include "postgres.h"
#include <ctype.h> #include <ctype.h>
@ -85,16 +87,6 @@
(appendStringInfo(str, " :" CppAsString(fldname) " "), \ (appendStringInfo(str, " :" CppAsString(fldname) " "), \
_outNode(str, node->fldname)) _outNode(str, node->fldname))
/* Write an integer-list field */
#define WRITE_INTLIST_FIELD(fldname) \
(appendStringInfo(str, " :" CppAsString(fldname) " "), \
_outIntList(str, node->fldname))
/* Write an OID-list field */
#define WRITE_OIDLIST_FIELD(fldname) \
(appendStringInfo(str, " :" CppAsString(fldname) " "), \
_outOidList(str, node->fldname))
/* Write a bitmapset field */ /* Write a bitmapset field */
#define WRITE_BITMAPSET_FIELD(fldname) \ #define WRITE_BITMAPSET_FIELD(fldname) \
(appendStringInfo(str, " :" CppAsString(fldname) " "), \ (appendStringInfo(str, " :" CppAsString(fldname) " "), \
@ -145,35 +137,40 @@ _outToken(StringInfo str, char *s)
} }
} }
/*
* _outIntList -
* converts a List of integers
*/
static void static void
_outIntList(StringInfo str, List *list) _outList(StringInfo str, List *node)
{ {
List *l; ListCell *lc;
appendStringInfoChar(str, '('); appendStringInfoChar(str, '(');
if (IsA(node, IntList))
appendStringInfoChar(str, 'i'); appendStringInfoChar(str, 'i');
foreach(l, list) else if (IsA(node, OidList))
appendStringInfo(str, " %d", lfirsti(l));
appendStringInfoChar(str, ')');
}
/*
* _outOidList -
* converts a List of OIDs
*/
static void
_outOidList(StringInfo str, List *list)
{
List *l;
appendStringInfoChar(str, '(');
appendStringInfoChar(str, 'o'); appendStringInfoChar(str, 'o');
foreach(l, list)
appendStringInfo(str, " %u", lfirsto(l)); foreach (lc, node)
{
/*
* For the sake of backward compatibility, we emit a slightly
* different whitespace format for lists of nodes vs. other
* types of lists. XXX: is this necessary?
*/
if (IsA(node, List))
{
_outNode(str, lfirst(lc));
if (lnext(lc))
appendStringInfoChar(str, ' ');
}
else if (IsA(node, IntList))
appendStringInfo(str, " %d", lfirst_int(lc));
else if (IsA(node, OidList))
appendStringInfo(str, " %u", lfirst_oid(lc));
else
elog(ERROR, "unrecognized list node type: %d",
(int) node->type);
}
appendStringInfoChar(str, ')'); appendStringInfoChar(str, ')');
} }
@ -336,39 +333,12 @@ _outIndexScan(StringInfo str, IndexScan *node)
_outScanInfo(str, (Scan *) node); _outScanInfo(str, (Scan *) node);
WRITE_OIDLIST_FIELD(indxid); WRITE_NODE_FIELD(indxid);
WRITE_NODE_FIELD(indxqual); WRITE_NODE_FIELD(indxqual);
WRITE_NODE_FIELD(indxqualorig); WRITE_NODE_FIELD(indxqualorig);
/* this can become WRITE_NODE_FIELD when intlists are normal objects: */ WRITE_NODE_FIELD(indxstrategy);
{ WRITE_NODE_FIELD(indxsubtype);
List *tmp; WRITE_NODE_FIELD(indxlossy);
appendStringInfo(str, " :indxstrategy ");
foreach(tmp, node->indxstrategy)
{
_outIntList(str, lfirst(tmp));
}
}
/* this can become WRITE_NODE_FIELD when OID lists are normal objects: */
{
List *tmp;
appendStringInfo(str, " :indxsubtype ");
foreach(tmp, node->indxsubtype)
{
_outOidList(str, lfirst(tmp));
}
}
/* this can become WRITE_NODE_FIELD when intlists are normal objects: */
{
List *tmp;
appendStringInfo(str, " :indxlossy ");
foreach(tmp, node->indxlossy)
{
_outIntList(str, lfirst(tmp));
}
}
WRITE_ENUM_FIELD(indxorderdir, ScanDirection); WRITE_ENUM_FIELD(indxorderdir, ScanDirection);
} }
@ -743,7 +713,7 @@ _outSubLink(StringInfo str, SubLink *node)
WRITE_BOOL_FIELD(useOr); WRITE_BOOL_FIELD(useOr);
WRITE_NODE_FIELD(lefthand); WRITE_NODE_FIELD(lefthand);
WRITE_NODE_FIELD(operName); WRITE_NODE_FIELD(operName);
WRITE_OIDLIST_FIELD(operOids); WRITE_NODE_FIELD(operOids);
WRITE_NODE_FIELD(subselect); WRITE_NODE_FIELD(subselect);
} }
@ -755,14 +725,14 @@ _outSubPlan(StringInfo str, SubPlan *node)
WRITE_ENUM_FIELD(subLinkType, SubLinkType); WRITE_ENUM_FIELD(subLinkType, SubLinkType);
WRITE_BOOL_FIELD(useOr); WRITE_BOOL_FIELD(useOr);
WRITE_NODE_FIELD(exprs); WRITE_NODE_FIELD(exprs);
WRITE_INTLIST_FIELD(paramIds); WRITE_NODE_FIELD(paramIds);
WRITE_NODE_FIELD(plan); WRITE_NODE_FIELD(plan);
WRITE_INT_FIELD(plan_id); WRITE_INT_FIELD(plan_id);
WRITE_NODE_FIELD(rtable); WRITE_NODE_FIELD(rtable);
WRITE_BOOL_FIELD(useHashTable); WRITE_BOOL_FIELD(useHashTable);
WRITE_BOOL_FIELD(unknownEqFalse); WRITE_BOOL_FIELD(unknownEqFalse);
WRITE_INTLIST_FIELD(setParam); WRITE_NODE_FIELD(setParam);
WRITE_INTLIST_FIELD(parParam); WRITE_NODE_FIELD(parParam);
WRITE_NODE_FIELD(args); WRITE_NODE_FIELD(args);
} }
@ -1302,7 +1272,7 @@ _outQuery(StringInfo str, Query *node)
WRITE_BOOL_FIELD(hasSubLinks); WRITE_BOOL_FIELD(hasSubLinks);
WRITE_NODE_FIELD(rtable); WRITE_NODE_FIELD(rtable);
WRITE_NODE_FIELD(jointree); WRITE_NODE_FIELD(jointree);
WRITE_INTLIST_FIELD(rowMarks); WRITE_NODE_FIELD(rowMarks);
WRITE_NODE_FIELD(targetList); WRITE_NODE_FIELD(targetList);
WRITE_NODE_FIELD(groupClause); WRITE_NODE_FIELD(groupClause);
WRITE_NODE_FIELD(havingQual); WRITE_NODE_FIELD(havingQual);
@ -1311,7 +1281,7 @@ _outQuery(StringInfo str, Query *node)
WRITE_NODE_FIELD(limitOffset); WRITE_NODE_FIELD(limitOffset);
WRITE_NODE_FIELD(limitCount); WRITE_NODE_FIELD(limitCount);
WRITE_NODE_FIELD(setOperations); WRITE_NODE_FIELD(setOperations);
WRITE_INTLIST_FIELD(resultRelations); WRITE_NODE_FIELD(resultRelations);
/* planner-internal fields are not written out */ /* planner-internal fields are not written out */
} }
@ -1343,7 +1313,7 @@ _outSetOperationStmt(StringInfo str, SetOperationStmt *node)
WRITE_BOOL_FIELD(all); WRITE_BOOL_FIELD(all);
WRITE_NODE_FIELD(larg); WRITE_NODE_FIELD(larg);
WRITE_NODE_FIELD(rarg); WRITE_NODE_FIELD(rarg);
WRITE_OIDLIST_FIELD(colTypes); WRITE_NODE_FIELD(colTypes);
} }
static void static void
@ -1444,7 +1414,6 @@ _outValue(StringInfo str, Value *value)
appendStringInfo(str, "%ld", value->val.ival); appendStringInfo(str, "%ld", value->val.ival);
break; break;
case T_Float: case T_Float:
/* /*
* We assume the value is a valid numeric literal and so does * We assume the value is a valid numeric literal and so does
* not need quoting. * not need quoting.
@ -1572,24 +1541,9 @@ static void
_outNode(StringInfo str, void *obj) _outNode(StringInfo str, void *obj)
{ {
if (obj == NULL) if (obj == NULL)
{
appendStringInfo(str, "<>"); appendStringInfo(str, "<>");
return; else if (IsA(obj, List) || IsA(obj, IntList) || IsA(obj, OidList))
} _outList(str, obj);
if (IsA(obj, List))
{
List *l;
appendStringInfoChar(str, '(');
foreach(l, (List *) obj)
{
_outNode(str, lfirst(l));
if (lnext(l))
appendStringInfoChar(str, ' ');
}
appendStringInfoChar(str, ')');
}
else if (IsA(obj, Integer) || else if (IsA(obj, Integer) ||
IsA(obj, Float) || IsA(obj, Float) ||
IsA(obj, String) || IsA(obj, String) ||

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/print.c,v 1.66 2004/05/08 21:21:18 tgl Exp $ * $PostgreSQL: pgsql/src/backend/nodes/print.c,v 1.67 2004/05/26 04:41:19 neilc Exp $
* *
* HISTORY * HISTORY
* AUTHOR DATE MAJOR EVENT * AUTHOR DATE MAJOR EVENT
@ -255,7 +255,7 @@ pretty_format_node_dump(const char *dump)
void void
print_rt(List *rtable) print_rt(List *rtable)
{ {
List *l; ListCell *l;
int i = 1; int i = 1;
printf("resno\trefname \trelid\tinFromCl\n"); printf("resno\trefname \trelid\tinFromCl\n");
@ -395,7 +395,7 @@ print_expr(Node *expr, List *rtable)
{ {
FuncExpr *e = (FuncExpr *) expr; FuncExpr *e = (FuncExpr *) expr;
char *funcname; char *funcname;
List *l; ListCell *l;
funcname = get_func_name(e->funcid); funcname = get_func_name(e->funcid);
printf("%s(", ((funcname != NULL) ? funcname : "(invalid function)")); printf("%s(", ((funcname != NULL) ? funcname : "(invalid function)"));
@ -418,18 +418,18 @@ print_expr(Node *expr, List *rtable)
void void
print_pathkeys(List *pathkeys, List *rtable) print_pathkeys(List *pathkeys, List *rtable)
{ {
List *i, ListCell *i;
*k;
printf("("); printf("(");
foreach(i, pathkeys) foreach(i, pathkeys)
{ {
List *pathkey = lfirst(i); List *pathkey = (List *) lfirst(i);
ListCell *k;
printf("("); printf("(");
foreach(k, pathkey) foreach(k, pathkey)
{ {
PathKeyItem *item = lfirst(k); PathKeyItem *item = (PathKeyItem *) lfirst(k);
print_expr(item->key, rtable); print_expr(item->key, rtable);
if (lnext(k)) if (lnext(k))
@ -449,12 +449,12 @@ print_pathkeys(List *pathkeys, List *rtable)
void void
print_tl(List *tlist, List *rtable) print_tl(List *tlist, List *rtable)
{ {
List *tl; ListCell *tl;
printf("(\n"); printf("(\n");
foreach(tl, tlist) foreach(tl, tlist)
{ {
TargetEntry *tle = lfirst(tl); TargetEntry *tle = (TargetEntry *) lfirst(tl);
printf("\t%d %s\t", tle->resdom->resno, printf("\t%d %s\t", tle->resdom->resno,
tle->resdom->resname ? tle->resdom->resname : "<null>"); tle->resdom->resname ? tle->resdom->resname : "<null>");
@ -590,13 +590,13 @@ print_plan_recursive(Plan *p, Query *parsetree, int indentLevel, char *label)
if (IsA(p, Append)) if (IsA(p, Append))
{ {
List *lst; ListCell *l;
int whichplan = 0; int whichplan = 0;
Append *appendplan = (Append *) p; Append *appendplan = (Append *) p;
foreach(lst, appendplan->appendplans) foreach(l, appendplan->appendplans)
{ {
Plan *subnode = (Plan *) lfirst(lst); Plan *subnode = (Plan *) lfirst(l);
/* /*
* I don't think we need to fiddle with the range table here, * I don't think we need to fiddle with the range table here,

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/read.c,v 1.41 2004/05/08 21:21:18 tgl Exp $ * $PostgreSQL: pgsql/src/backend/nodes/read.c,v 1.42 2004/05/26 04:41:19 neilc Exp $
* *
* HISTORY * HISTORY
* AUTHOR DATE MAJOR EVENT * AUTHOR DATE MAJOR EVENT
@ -384,7 +384,6 @@ nodeRead(char *token, int tok_len)
} }
break; break;
case T_Integer: case T_Integer:
/* /*
* we know that the token terminates on a char atol will stop * we know that the token terminates on a char atol will stop
* at * at

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/readfuncs.c,v 1.169 2004/05/10 22:44:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/nodes/readfuncs.c,v 1.170 2004/05/26 04:41:19 neilc Exp $
* *
* NOTES * NOTES
* Path and Plan nodes do not have any readfuncs support, because we * Path and Plan nodes do not have any readfuncs support, because we
@ -18,6 +18,8 @@
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
#define DISABLE_LIST_COMPAT
#include "postgres.h" #include "postgres.h"
#include <math.h> #include <math.h>
@ -33,11 +35,7 @@
* routine. * routine.
*/ */
/* Declare appropriate local variables */ /* Macros for declaring appropriate local variables */
#define READ_LOCALS(nodeTypeName) \
nodeTypeName *local_node = makeNode(nodeTypeName); \
char *token; \
int length
/* A few guys need only local_node */ /* A few guys need only local_node */
#define READ_LOCALS_NO_FIELDS(nodeTypeName) \ #define READ_LOCALS_NO_FIELDS(nodeTypeName) \
@ -48,6 +46,11 @@
char *token; \ char *token; \
int length int length
/* ... but most need both */
#define READ_LOCALS(nodeTypeName) \
READ_LOCALS_NO_FIELDS(nodeTypeName); \
READ_TEMP_LOCALS()
/* Read an integer field (anything written as ":fldname %d") */ /* Read an integer field (anything written as ":fldname %d") */
#define READ_INT_FIELD(fldname) \ #define READ_INT_FIELD(fldname) \
token = pg_strtok(&length); /* skip :fldname */ \ token = pg_strtok(&length); /* skip :fldname */ \
@ -101,16 +104,6 @@
token = pg_strtok(&length); /* skip :fldname */ \ token = pg_strtok(&length); /* skip :fldname */ \
local_node->fldname = nodeRead(NULL, 0) local_node->fldname = nodeRead(NULL, 0)
/* Read an integer-list field (XXX combine me with READ_NODE_FIELD) */
#define READ_INTLIST_FIELD(fldname) \
token = pg_strtok(&length); /* skip :fldname */ \
local_node->fldname = nodeRead(NULL, 0)
/* Read an OID-list field (XXX combine me with READ_NODE_FIELD) */
#define READ_OIDLIST_FIELD(fldname) \
token = pg_strtok(&length); /* skip :fldname */ \
local_node->fldname = nodeRead(NULL, 0)
/* Routine exit */ /* Routine exit */
#define READ_DONE() \ #define READ_DONE() \
return local_node return local_node
@ -153,7 +146,7 @@ _readQuery(void)
READ_BOOL_FIELD(hasSubLinks); READ_BOOL_FIELD(hasSubLinks);
READ_NODE_FIELD(rtable); READ_NODE_FIELD(rtable);
READ_NODE_FIELD(jointree); READ_NODE_FIELD(jointree);
READ_INTLIST_FIELD(rowMarks); READ_NODE_FIELD(rowMarks);
READ_NODE_FIELD(targetList); READ_NODE_FIELD(targetList);
READ_NODE_FIELD(groupClause); READ_NODE_FIELD(groupClause);
READ_NODE_FIELD(havingQual); READ_NODE_FIELD(havingQual);
@ -162,7 +155,7 @@ _readQuery(void)
READ_NODE_FIELD(limitOffset); READ_NODE_FIELD(limitOffset);
READ_NODE_FIELD(limitCount); READ_NODE_FIELD(limitCount);
READ_NODE_FIELD(setOperations); READ_NODE_FIELD(setOperations);
READ_INTLIST_FIELD(resultRelations); READ_NODE_FIELD(resultRelations);
/* planner-internal fields are left zero */ /* planner-internal fields are left zero */
@ -237,7 +230,7 @@ _readSetOperationStmt(void)
READ_BOOL_FIELD(all); READ_BOOL_FIELD(all);
READ_NODE_FIELD(larg); READ_NODE_FIELD(larg);
READ_NODE_FIELD(rarg); READ_NODE_FIELD(rarg);
READ_OIDLIST_FIELD(colTypes); READ_NODE_FIELD(colTypes);
READ_DONE(); READ_DONE();
} }
@ -526,7 +519,7 @@ _readSubLink(void)
READ_BOOL_FIELD(useOr); READ_BOOL_FIELD(useOr);
READ_NODE_FIELD(lefthand); READ_NODE_FIELD(lefthand);
READ_NODE_FIELD(operName); READ_NODE_FIELD(operName);
READ_OIDLIST_FIELD(operOids); READ_NODE_FIELD(operOids);
READ_NODE_FIELD(subselect); READ_NODE_FIELD(subselect);
READ_DONE(); READ_DONE();

View File

@ -6,7 +6,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* $PostgreSQL: pgsql/src/backend/optimizer/geqo/geqo_eval.c,v 1.67 2004/01/23 23:54:21 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/geqo/geqo_eval.c,v 1.68 2004/05/26 04:41:20 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -238,14 +238,14 @@ static bool
desirable_join(Query *root, desirable_join(Query *root,
RelOptInfo *outer_rel, RelOptInfo *inner_rel) RelOptInfo *outer_rel, RelOptInfo *inner_rel)
{ {
List *i; ListCell *l;
/* /*
* Join if there is an applicable join clause. * Join if there is an applicable join clause.
*/ */
foreach(i, outer_rel->joininfo) foreach(l, outer_rel->joininfo)
{ {
JoinInfo *joininfo = (JoinInfo *) lfirst(i); JoinInfo *joininfo = (JoinInfo *) lfirst(l);
if (bms_is_subset(joininfo->unjoined_relids, inner_rel->relids)) if (bms_is_subset(joininfo->unjoined_relids, inner_rel->relids))
return true; return true;
@ -256,9 +256,9 @@ desirable_join(Query *root,
* needed to improve the odds that we will find a valid solution in * needed to improve the odds that we will find a valid solution in
* a case where an IN sub-select has a clauseless join. * a case where an IN sub-select has a clauseless join.
*/ */
foreach(i, root->in_info_list) foreach(l, root->in_info_list)
{ {
InClauseInfo *ininfo = (InClauseInfo *) lfirst(i); InClauseInfo *ininfo = (InClauseInfo *) lfirst(l);
if (bms_is_subset(outer_rel->relids, ininfo->righthand) && if (bms_is_subset(outer_rel->relids, ininfo->righthand) &&
bms_is_subset(inner_rel->relids, ininfo->righthand)) bms_is_subset(inner_rel->relids, ininfo->righthand))

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/allpaths.c,v 1.114 2004/05/10 22:44:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/allpaths.c,v 1.115 2004/05/26 04:41:21 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -102,11 +102,11 @@ make_one_rel(Query *root)
static void static void
set_base_rel_pathlists(Query *root) set_base_rel_pathlists(Query *root)
{ {
List *rellist; ListCell *l;
foreach(rellist, root->base_rel_list) foreach(l, root->base_rel_list)
{ {
RelOptInfo *rel = (RelOptInfo *) lfirst(rellist); RelOptInfo *rel = (RelOptInfo *) lfirst(l);
Index rti = rel->relid; Index rti = rel->relid;
RangeTblEntry *rte; RangeTblEntry *rte;
List *inheritlist; List *inheritlist;
@ -212,7 +212,7 @@ set_inherited_rel_pathlist(Query *root, RelOptInfo *rel,
int parentRTindex = rti; int parentRTindex = rti;
Oid parentOID = rte->relid; Oid parentOID = rte->relid;
List *subpaths = NIL; List *subpaths = NIL;
List *il; ListCell *il;
/* /*
* XXX for now, can't handle inherited expansion of FOR UPDATE; can we * XXX for now, can't handle inherited expansion of FOR UPDATE; can we
@ -247,8 +247,8 @@ set_inherited_rel_pathlist(Query *root, RelOptInfo *rel,
Oid childOID; Oid childOID;
RelOptInfo *childrel; RelOptInfo *childrel;
List *reltlist; List *reltlist;
List *parentvars; ListCell *parentvars;
List *childvars; ListCell *childvars;
childrte = rt_fetch(childRTindex, root->rtable); childrte = rt_fetch(childRTindex, root->rtable);
childOID = childrte->relid; childOID = childrte->relid;
@ -300,7 +300,7 @@ set_inherited_rel_pathlist(Query *root, RelOptInfo *rel,
if (childrel->width > rel->width) if (childrel->width > rel->width)
rel->width = childrel->width; rel->width = childrel->width;
childvars = FastListValue(&childrel->reltargetlist); childvars = list_head(FastListValue(&childrel->reltargetlist));
foreach(parentvars, FastListValue(&rel->reltargetlist)) foreach(parentvars, FastListValue(&rel->reltargetlist))
{ {
Var *parentvar = (Var *) lfirst(parentvars); Var *parentvar = (Var *) lfirst(parentvars);
@ -366,11 +366,11 @@ set_subquery_pathlist(Query *root, RelOptInfo *rel,
{ {
/* OK to consider pushing down individual quals */ /* OK to consider pushing down individual quals */
List *upperrestrictlist = NIL; List *upperrestrictlist = NIL;
List *lst; ListCell *l;
foreach(lst, rel->baserestrictinfo) foreach(l, rel->baserestrictinfo)
{ {
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lst); RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
Node *clause = (Node *) rinfo->clause; Node *clause = (Node *) rinfo->clause;
if (qual_is_pushdown_safe(subquery, rti, clause, differentTypes)) if (qual_is_pushdown_safe(subquery, rti, clause, differentTypes))
@ -434,7 +434,7 @@ make_fromexpr_rel(Query *root, FromExpr *from)
{ {
int levels_needed; int levels_needed;
List *initial_rels = NIL; List *initial_rels = NIL;
List *jt; ListCell *jt;
/* /*
* Count the number of child jointree nodes. This is the depth of the * Count the number of child jointree nodes. This is the depth of the
@ -464,7 +464,7 @@ make_fromexpr_rel(Query *root, FromExpr *from)
/* /*
* Single jointree node, so we're done. * Single jointree node, so we're done.
*/ */
return (RelOptInfo *) lfirst(initial_rels); return (RelOptInfo *) linitial(initial_rels);
} }
else else
{ {
@ -516,7 +516,7 @@ make_one_rel_by_joins(Query *root, int levels_needed, List *initial_rels)
for (lev = 2; lev <= levels_needed; lev++) for (lev = 2; lev <= levels_needed; lev++)
{ {
List *x; ListCell *x;
/* /*
* Determine all possible pairs of relations to be joined at this * Determine all possible pairs of relations to be joined at this
@ -548,7 +548,7 @@ make_one_rel_by_joins(Query *root, int levels_needed, List *initial_rels)
elog(ERROR, "failed to build any %d-way joins", levels_needed); elog(ERROR, "failed to build any %d-way joins", levels_needed);
Assert(length(joinitems[levels_needed]) == 1); Assert(length(joinitems[levels_needed]) == 1);
rel = (RelOptInfo *) lfirst(joinitems[levels_needed]); rel = (RelOptInfo *) linitial(joinitems[levels_needed]);
return rel; return rel;
} }
@ -660,21 +660,22 @@ static void
compare_tlist_datatypes(List *tlist, List *colTypes, compare_tlist_datatypes(List *tlist, List *colTypes,
bool *differentTypes) bool *differentTypes)
{ {
List *i; ListCell *l;
ListCell *colType = list_head(colTypes);
foreach(i, tlist) foreach(l, tlist)
{ {
TargetEntry *tle = (TargetEntry *) lfirst(i); TargetEntry *tle = (TargetEntry *) lfirst(l);
if (tle->resdom->resjunk) if (tle->resdom->resjunk)
continue; /* ignore resjunk columns */ continue; /* ignore resjunk columns */
if (colTypes == NIL) if (colType == NULL)
elog(ERROR, "wrong number of tlist entries"); elog(ERROR, "wrong number of tlist entries");
if (tle->resdom->restype != lfirsto(colTypes)) if (tle->resdom->restype != lfirst_oid(colType))
differentTypes[tle->resdom->resno] = true; differentTypes[tle->resdom->resno] = true;
colTypes = lnext(colTypes); colType = lnext(colType);
} }
if (colTypes != NIL) if (colType != NULL)
elog(ERROR, "wrong number of tlist entries"); elog(ERROR, "wrong number of tlist entries");
} }
@ -712,7 +713,7 @@ qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
{ {
bool safe = true; bool safe = true;
List *vars; List *vars;
List *vl; ListCell *vl;
Bitmapset *tested = NULL; Bitmapset *tested = NULL;
/* Refuse subselects (point 1) */ /* Refuse subselects (point 1) */
@ -869,7 +870,7 @@ print_relids(Relids relids)
static void static void
print_restrictclauses(Query *root, List *clauses) print_restrictclauses(Query *root, List *clauses)
{ {
List *l; ListCell *l;
foreach(l, clauses) foreach(l, clauses)
{ {
@ -987,7 +988,7 @@ print_path(Query *root, Path *path, int indent)
void void
debug_print_rel(Query *root, RelOptInfo *rel) debug_print_rel(Query *root, RelOptInfo *rel)
{ {
List *l; ListCell *l;
printf("RELOPTINFO ("); printf("RELOPTINFO (");
print_relids(rel->relids); print_relids(rel->relids);

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/clausesel.c,v 1.65 2004/05/10 22:44:45 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/clausesel.c,v 1.66 2004/05/26 04:41:21 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -98,16 +98,16 @@ clauselist_selectivity(Query *root,
{ {
Selectivity s1 = 1.0; Selectivity s1 = 1.0;
RangeQueryClause *rqlist = NULL; RangeQueryClause *rqlist = NULL;
List *clist; ListCell *l;
/* /*
* Initial scan over clauses. Anything that doesn't look like a * Initial scan over clauses. Anything that doesn't look like a
* potential rangequery clause gets multiplied into s1 and forgotten. * potential rangequery clause gets multiplied into s1 and forgotten.
* Anything that does gets inserted into an rqlist entry. * Anything that does gets inserted into an rqlist entry.
*/ */
foreach(clist, clauses) foreach(l, clauses)
{ {
Node *clause = (Node *) lfirst(clist); Node *clause = (Node *) lfirst(l);
RestrictInfo *rinfo; RestrictInfo *rinfo;
Selectivity s2; Selectivity s2;
@ -143,7 +143,7 @@ clauselist_selectivity(Query *root,
(is_pseudo_constant_clause_relids(lsecond(expr->args), (is_pseudo_constant_clause_relids(lsecond(expr->args),
rinfo->right_relids) || rinfo->right_relids) ||
(varonleft = false, (varonleft = false,
is_pseudo_constant_clause_relids(lfirst(expr->args), is_pseudo_constant_clause_relids(linitial(expr->args),
rinfo->left_relids))); rinfo->left_relids)));
} }
else else
@ -151,7 +151,7 @@ clauselist_selectivity(Query *root,
ok = (NumRelids(clause) == 1) && ok = (NumRelids(clause) == 1) &&
(is_pseudo_constant_clause(lsecond(expr->args)) || (is_pseudo_constant_clause(lsecond(expr->args)) ||
(varonleft = false, (varonleft = false,
is_pseudo_constant_clause(lfirst(expr->args)))); is_pseudo_constant_clause(linitial(expr->args))));
} }
if (ok) if (ok)
@ -521,7 +521,7 @@ clause_selectivity(Query *root,
* *
* XXX is this too conservative? * XXX is this too conservative?
*/ */
List *arg; ListCell *arg;
s1 = 0.0; s1 = 0.0;
foreach(arg, ((BoolExpr *) clause)->args) foreach(arg, ((BoolExpr *) clause)->args)

View File

@ -49,7 +49,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/costsize.c,v 1.126 2004/04/06 18:46:03 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/costsize.c,v 1.127 2004/05/26 04:41:21 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -920,7 +920,7 @@ cost_mergejoin(MergePath *path, Query *root)
*/ */
if (mergeclauses) if (mergeclauses)
{ {
firstclause = (RestrictInfo *) lfirst(mergeclauses); firstclause = (RestrictInfo *) linitial(mergeclauses);
if (firstclause->left_mergescansel < 0) /* not computed yet? */ if (firstclause->left_mergescansel < 0) /* not computed yet? */
mergejoinscansel(root, (Node *) firstclause->clause, mergejoinscansel(root, (Node *) firstclause->clause,
&firstclause->left_mergescansel, &firstclause->left_mergescansel,
@ -1069,7 +1069,7 @@ cost_hashjoin(HashPath *path, Query *root)
int numbatches; int numbatches;
Selectivity innerbucketsize; Selectivity innerbucketsize;
Selectivity joininfactor; Selectivity joininfactor;
List *hcl; ListCell *hcl;
if (!enable_hashjoin) if (!enable_hashjoin)
startup_cost += disable_cost; startup_cost += disable_cost;
@ -1267,7 +1267,7 @@ cost_hashjoin(HashPath *path, Query *root)
void void
cost_qual_eval(QualCost *cost, List *quals) cost_qual_eval(QualCost *cost, List *quals)
{ {
List *l; ListCell *l;
cost->startup = 0; cost->startup = 0;
cost->per_tuple = 0; cost->per_tuple = 0;
@ -1444,7 +1444,7 @@ static Selectivity
approx_selectivity(Query *root, List *quals, JoinType jointype) approx_selectivity(Query *root, List *quals, JoinType jointype)
{ {
Selectivity total = 1.0; Selectivity total = 1.0;
List *l; ListCell *l;
foreach(l, quals) foreach(l, quals)
{ {
@ -1699,7 +1699,7 @@ static void
set_rel_width(Query *root, RelOptInfo *rel) set_rel_width(Query *root, RelOptInfo *rel)
{ {
int32 tuple_width = 0; int32 tuple_width = 0;
List *tllist; ListCell *tllist;
foreach(tllist, FastListValue(&rel->reltargetlist)) foreach(tllist, FastListValue(&rel->reltargetlist))
{ {

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/indxpath.c,v 1.158 2004/03/27 00:24:28 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/indxpath.c,v 1.159 2004/05/26 04:41:21 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -121,7 +121,7 @@ void
create_index_paths(Query *root, RelOptInfo *rel) create_index_paths(Query *root, RelOptInfo *rel)
{ {
Relids all_join_outerrelids = NULL; Relids all_join_outerrelids = NULL;
List *ilist; ListCell *ilist;
foreach(ilist, rel->indexlist) foreach(ilist, rel->indexlist)
{ {
@ -250,12 +250,12 @@ group_clauses_by_indexkey(RelOptInfo *rel, IndexOptInfo *index)
{ {
Oid curClass = classes[0]; Oid curClass = classes[0];
FastList clausegroup; FastList clausegroup;
List *i; ListCell *l;
FastListInit(&clausegroup); FastListInit(&clausegroup);
foreach(i, restrictinfo_list) foreach(l, restrictinfo_list)
{ {
RestrictInfo *rinfo = (RestrictInfo *) lfirst(i); RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
if (match_clause_to_indexcol(rel, if (match_clause_to_indexcol(rel,
index, index,
@ -312,7 +312,7 @@ group_clauses_by_indexkey_for_join(Query *root,
Oid curClass = classes[0]; Oid curClass = classes[0];
FastList clausegroup; FastList clausegroup;
int numsources; int numsources;
List *i; ListCell *l;
FastListInit(&clausegroup); FastListInit(&clausegroup);
@ -324,9 +324,9 @@ group_clauses_by_indexkey_for_join(Query *root,
* of a non-join clause if it appears after a join clause it is * of a non-join clause if it appears after a join clause it is
* redundant with. * redundant with.
*/ */
foreach(i, rel->baserestrictinfo) foreach(l, rel->baserestrictinfo)
{ {
RestrictInfo *rinfo = (RestrictInfo *) lfirst(i); RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
/* Can't use pushed-down clauses in outer join */ /* Can't use pushed-down clauses in outer join */
if (isouterjoin && rinfo->is_pushed_down) if (isouterjoin && rinfo->is_pushed_down)
@ -344,11 +344,11 @@ group_clauses_by_indexkey_for_join(Query *root,
numsources = (FastListValue(&clausegroup) != NIL) ? 1 : 0; numsources = (FastListValue(&clausegroup) != NIL) ? 1 : 0;
/* Look for joinclauses that are usable with given outer_relids */ /* Look for joinclauses that are usable with given outer_relids */
foreach(i, rel->joininfo) foreach(l, rel->joininfo)
{ {
JoinInfo *joininfo = (JoinInfo *) lfirst(i); JoinInfo *joininfo = (JoinInfo *) lfirst(l);
bool jfoundhere = false; bool jfoundhere = false;
List *j; ListCell *j;
if (!bms_is_subset(joininfo->unjoined_relids, outer_relids)) if (!bms_is_subset(joininfo->unjoined_relids, outer_relids))
continue; continue;
@ -448,7 +448,7 @@ group_clauses_by_indexkey_for_or(RelOptInfo *rel,
{ {
Oid curClass = classes[0]; Oid curClass = classes[0];
FastList clausegroup; FastList clausegroup;
List *item; ListCell *item;
FastListInit(&clausegroup); FastListInit(&clausegroup);
@ -511,7 +511,6 @@ group_clauses_by_indexkey_for_or(RelOptInfo *rel,
indexcol++; indexcol++;
classes++; classes++;
} while (!DoneMatchingIndexKeys(classes)); } while (!DoneMatchingIndexKeys(classes));
/* if OR clause was not used then forget it, per comments above */ /* if OR clause was not used then forget it, per comments above */
@ -738,7 +737,7 @@ void
check_partial_indexes(Query *root, RelOptInfo *rel) check_partial_indexes(Query *root, RelOptInfo *rel)
{ {
List *restrictinfo_list = rel->baserestrictinfo; List *restrictinfo_list = rel->baserestrictinfo;
List *ilist; ListCell *ilist;
foreach(ilist, rel->indexlist) foreach(ilist, rel->indexlist)
{ {
@ -772,7 +771,7 @@ check_partial_indexes(Query *root, RelOptInfo *rel)
static bool static bool
pred_test(List *predicate_list, List *restrictinfo_list) pred_test(List *predicate_list, List *restrictinfo_list)
{ {
List *pred; ListCell *pred;
/* /*
* Note: if Postgres tried to optimize queries by forming equivalence * Note: if Postgres tried to optimize queries by forming equivalence
@ -815,7 +814,7 @@ pred_test(List *predicate_list, List *restrictinfo_list)
static bool static bool
pred_test_restrict_list(Expr *predicate, List *restrictinfo_list) pred_test_restrict_list(Expr *predicate, List *restrictinfo_list)
{ {
List *item; ListCell *item;
foreach(item, restrictinfo_list) foreach(item, restrictinfo_list)
{ {
@ -839,8 +838,8 @@ pred_test_restrict_list(Expr *predicate, List *restrictinfo_list)
static bool static bool
pred_test_recurse_clause(Expr *predicate, Node *clause) pred_test_recurse_clause(Expr *predicate, Node *clause)
{ {
List *items, List *items;
*item; ListCell *item;
Assert(clause != NULL); Assert(clause != NULL);
if (or_clause(clause)) if (or_clause(clause))
@ -883,8 +882,8 @@ pred_test_recurse_clause(Expr *predicate, Node *clause)
static bool static bool
pred_test_recurse_pred(Expr *predicate, Node *clause) pred_test_recurse_pred(Expr *predicate, Node *clause)
{ {
List *items, List *items;
*item; ListCell *item;
Assert(predicate != NULL); Assert(predicate != NULL);
if (or_clause((Node *) predicate)) if (or_clause((Node *) predicate))
@ -1360,13 +1359,13 @@ static Relids
indexable_outerrelids(RelOptInfo *rel, IndexOptInfo *index) indexable_outerrelids(RelOptInfo *rel, IndexOptInfo *index)
{ {
Relids outer_relids = NULL; Relids outer_relids = NULL;
List *i; ListCell *l;
foreach(i, rel->joininfo) foreach(l, rel->joininfo)
{ {
JoinInfo *joininfo = (JoinInfo *) lfirst(i); JoinInfo *joininfo = (JoinInfo *) lfirst(l);
bool match_found = false; bool match_found = false;
List *j; ListCell *j;
/* /*
* Examine each joinclause in the JoinInfo node's list to see if * Examine each joinclause in the JoinInfo node's list to see if
@ -1433,8 +1432,8 @@ best_inner_indexscan(Query *root, RelOptInfo *rel,
{ {
Path *cheapest = NULL; Path *cheapest = NULL;
bool isouterjoin; bool isouterjoin;
List *ilist; ListCell *ilist;
List *jlist; ListCell *jlist;
InnerIndexscanInfo *info; InnerIndexscanInfo *info;
MemoryContext oldcontext; MemoryContext oldcontext;
@ -1538,7 +1537,7 @@ best_inner_indexscan(Query *root, RelOptInfo *rel,
} }
} }
if (jlist == NIL) /* failed to find a match? */ if (jlist == NULL) /* failed to find a match? */
{ {
List *clausegroups; List *clausegroups;
@ -1676,7 +1675,7 @@ List *
flatten_clausegroups_list(List *clausegroups) flatten_clausegroups_list(List *clausegroups)
{ {
List *allclauses = NIL; List *allclauses = NIL;
List *l; ListCell *l;
foreach(l, clausegroups) foreach(l, clausegroups)
{ {
@ -1697,7 +1696,7 @@ Expr *
make_expr_from_indexclauses(List *indexclauses) make_expr_from_indexclauses(List *indexclauses)
{ {
List *orclauses = NIL; List *orclauses = NIL;
List *orlist; ListCell *orlist;
/* There's no such thing as an indexpath with zero scans */ /* There's no such thing as an indexpath with zero scans */
Assert(indexclauses != NIL); Assert(indexclauses != NIL);
@ -1715,7 +1714,7 @@ make_expr_from_indexclauses(List *indexclauses)
if (length(orclauses) > 1) if (length(orclauses) > 1)
return make_orclause(orclauses); return make_orclause(orclauses);
else else
return (Expr *) lfirst(orclauses); return (Expr *) linitial(orclauses);
} }
@ -1768,23 +1767,23 @@ match_index_to_operand(Node *operand,
* could be avoided, at the cost of complicating all the callers * could be avoided, at the cost of complicating all the callers
* of this routine; doesn't seem worth it.) * of this routine; doesn't seem worth it.)
*/ */
List *indexprs; ListCell *indexpr_item;
int i; int i;
Node *indexkey; Node *indexkey;
indexprs = index->indexprs; indexpr_item = list_head(index->indexprs);
for (i = 0; i < indexcol; i++) for (i = 0; i < indexcol; i++)
{ {
if (index->indexkeys[i] == 0) if (index->indexkeys[i] == 0)
{ {
if (indexprs == NIL) if (indexpr_item == NULL)
elog(ERROR, "wrong number of index expressions"); elog(ERROR, "wrong number of index expressions");
indexprs = lnext(indexprs); indexpr_item = lnext(indexpr_item);
} }
} }
if (indexprs == NIL) if (indexpr_item == NULL)
elog(ERROR, "wrong number of index expressions"); elog(ERROR, "wrong number of index expressions");
indexkey = (Node *) lfirst(indexprs); indexkey = (Node *) lfirst(indexpr_item);
/* /*
* Does it match the operand? Again, strip any relabeling. * Does it match the operand? Again, strip any relabeling.
@ -2013,32 +2012,32 @@ List *
expand_indexqual_conditions(IndexOptInfo *index, List *clausegroups) expand_indexqual_conditions(IndexOptInfo *index, List *clausegroups)
{ {
FastList resultquals; FastList resultquals;
ListCell *clausegroup_item;
Oid *classes = index->classlist; Oid *classes = index->classlist;
if (clausegroups == NIL) if (clausegroups == NIL)
return NIL; return NIL;
FastListInit(&resultquals); FastListInit(&resultquals);
clausegroup_item = list_head(clausegroups);
do do
{ {
Oid curClass = classes[0]; Oid curClass = classes[0];
List *i; ListCell *l;
foreach(i, (List *) lfirst(clausegroups)) foreach(l, (List *) lfirst(clausegroup_item))
{ {
RestrictInfo *rinfo = (RestrictInfo *) lfirst(i); RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
FastConc(&resultquals, FastConc(&resultquals,
expand_indexqual_condition(rinfo, curClass)); expand_indexqual_condition(rinfo, curClass));
} }
clausegroups = lnext(clausegroups); clausegroup_item = lnext(clausegroup_item);
classes++; classes++;
} while (clausegroup_item != NULL && !DoneMatchingIndexKeys(classes));
} while (clausegroups != NIL && !DoneMatchingIndexKeys(classes)); Assert(clausegroup_item == NULL); /* else more groups than indexkeys... */
Assert(clausegroups == NIL); /* else more groups than indexkeys... */
return FastListValue(&resultquals); return FastListValue(&resultquals);
} }

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/joinpath.c,v 1.86 2004/04/06 18:46:03 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/joinpath.c,v 1.87 2004/05/26 04:41:22 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -145,7 +145,7 @@ sort_inner_and_outer(Query *root,
Path *outer_path; Path *outer_path;
Path *inner_path; Path *inner_path;
List *all_pathkeys; List *all_pathkeys;
List *i; ListCell *l;
/* /*
* If we are doing a right or full join, we must use *all* the * If we are doing a right or full join, we must use *all* the
@ -224,9 +224,9 @@ sort_inner_and_outer(Query *root,
mergeclause_list, mergeclause_list,
outerrel); outerrel);
foreach(i, all_pathkeys) foreach(l, all_pathkeys)
{ {
List *front_pathkey = lfirst(i); List *front_pathkey = (List *) lfirst(l);
List *cur_pathkeys; List *cur_pathkeys;
List *cur_mergeclauses; List *cur_mergeclauses;
List *outerkeys; List *outerkeys;
@ -234,7 +234,7 @@ sort_inner_and_outer(Query *root,
List *merge_pathkeys; List *merge_pathkeys;
/* Make a pathkey list with this guy first. */ /* Make a pathkey list with this guy first. */
if (i != all_pathkeys) if (l != list_head(all_pathkeys))
cur_pathkeys = lcons(front_pathkey, cur_pathkeys = lcons(front_pathkey,
lremove(front_pathkey, lremove(front_pathkey,
listCopy(all_pathkeys))); listCopy(all_pathkeys)));
@ -338,7 +338,7 @@ match_unsorted_outer(Query *root,
Path *inner_cheapest_total = innerrel->cheapest_total_path; Path *inner_cheapest_total = innerrel->cheapest_total_path;
Path *matpath = NULL; Path *matpath = NULL;
Path *bestinnerjoin = NULL; Path *bestinnerjoin = NULL;
List *i; ListCell *l;
/* /*
* Nestloop only supports inner, left, and IN joins. Also, if we are * Nestloop only supports inner, left, and IN joins. Also, if we are
@ -402,9 +402,9 @@ match_unsorted_outer(Query *root,
outerrel->relids, jointype); outerrel->relids, jointype);
} }
foreach(i, outerrel->pathlist) foreach(l, outerrel->pathlist)
{ {
Path *outerpath = (Path *) lfirst(i); Path *outerpath = (Path *) lfirst(l);
List *merge_pathkeys; List *merge_pathkeys;
List *mergeclauses; List *mergeclauses;
List *innersortkeys; List *innersortkeys;
@ -676,7 +676,7 @@ hash_inner_and_outer(Query *root,
{ {
bool isouterjoin; bool isouterjoin;
List *hashclauses; List *hashclauses;
List *i; ListCell *l;
/* /*
* Hashjoin only supports inner, left, and IN joins. * Hashjoin only supports inner, left, and IN joins.
@ -704,9 +704,9 @@ hash_inner_and_outer(Query *root,
* are usable with this pair of sub-relations. * are usable with this pair of sub-relations.
*/ */
hashclauses = NIL; hashclauses = NIL;
foreach(i, restrictlist) foreach(l, restrictlist)
{ {
RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i); RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
if (!restrictinfo->can_join || if (!restrictinfo->can_join ||
restrictinfo->hashjoinoperator == InvalidOid) restrictinfo->hashjoinoperator == InvalidOid)
@ -803,11 +803,11 @@ select_mergejoin_clauses(RelOptInfo *joinrel,
{ {
List *result_list = NIL; List *result_list = NIL;
bool isouterjoin = IS_OUTER_JOIN(jointype); bool isouterjoin = IS_OUTER_JOIN(jointype);
List *i; ListCell *l;
foreach(i, restrictlist) foreach(l, restrictlist)
{ {
RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i); RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
/* /*
* If processing an outer join, only use its own join clauses in * If processing an outer join, only use its own join clauses in

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/joinrels.c,v 1.67 2004/03/08 17:20:17 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/joinrels.c,v 1.68 2004/05/26 04:41:22 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -20,10 +20,10 @@
static List *make_rels_by_clause_joins(Query *root, static List *make_rels_by_clause_joins(Query *root,
RelOptInfo *old_rel, RelOptInfo *old_rel,
List *other_rels); ListCell *other_rels);
static List *make_rels_by_clauseless_joins(Query *root, static List *make_rels_by_clauseless_joins(Query *root,
RelOptInfo *old_rel, RelOptInfo *old_rel,
List *other_rels); ListCell *other_rels);
static bool is_inside_IN(Query *root, RelOptInfo *rel); static bool is_inside_IN(Query *root, RelOptInfo *rel);
@ -43,8 +43,8 @@ make_rels_by_joins(Query *root, int level, List **joinrels)
{ {
List *result_rels = NIL; List *result_rels = NIL;
List *new_rels; List *new_rels;
List *nr; ListCell *nr;
List *r; ListCell *r;
int k; int k;
/* /*
@ -64,13 +64,13 @@ make_rels_by_joins(Query *root, int level, List **joinrels)
foreach(r, joinrels[level - 1]) foreach(r, joinrels[level - 1])
{ {
RelOptInfo *old_rel = (RelOptInfo *) lfirst(r); RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
List *other_rels; ListCell *other_rels;
if (level == 2) if (level == 2)
other_rels = lnext(r); /* only consider remaining initial other_rels = lnext(r); /* only consider remaining initial
* rels */ * rels */
else else
other_rels = joinrels[1]; /* consider all initial rels */ other_rels = list_head(joinrels[1]); /* consider all initial rels */
if (old_rel->joininfo != NIL) if (old_rel->joininfo != NIL)
{ {
@ -149,8 +149,8 @@ make_rels_by_joins(Query *root, int level, List **joinrels)
foreach(r, joinrels[k]) foreach(r, joinrels[k])
{ {
RelOptInfo *old_rel = (RelOptInfo *) lfirst(r); RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
List *other_rels; ListCell *other_rels;
List *r2; ListCell *r2;
if (old_rel->joininfo == NIL) if (old_rel->joininfo == NIL)
continue; /* we ignore clauseless joins here */ continue; /* we ignore clauseless joins here */
@ -158,15 +158,15 @@ make_rels_by_joins(Query *root, int level, List **joinrels)
if (k == other_level) if (k == other_level)
other_rels = lnext(r); /* only consider remaining rels */ other_rels = lnext(r); /* only consider remaining rels */
else else
other_rels = joinrels[other_level]; other_rels = list_head(joinrels[other_level]);
foreach(r2, other_rels) for_each_cell(r2, other_rels)
{ {
RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2); RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2);
if (!bms_overlap(old_rel->relids, new_rel->relids)) if (!bms_overlap(old_rel->relids, new_rel->relids))
{ {
List *i; ListCell *i;
/* /*
* OK, we can build a rel of the right level from this * OK, we can build a rel of the right level from this
@ -217,13 +217,13 @@ make_rels_by_joins(Query *root, int level, List **joinrels)
foreach(r, joinrels[level - 1]) foreach(r, joinrels[level - 1])
{ {
RelOptInfo *old_rel = (RelOptInfo *) lfirst(r); RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
List *other_rels; ListCell *other_rels;
if (level == 2) if (level == 2)
other_rels = lnext(r); /* only consider remaining initial other_rels = lnext(r); /* only consider remaining initial
* rels */ * rels */
else else
other_rels = joinrels[1]; /* consider all initial other_rels = list_head(joinrels[1]); /* consider all initial
* rels */ * rels */
new_rels = make_rels_by_clauseless_joins(root, new_rels = make_rels_by_clauseless_joins(root,
@ -271,7 +271,8 @@ make_rels_by_joins(Query *root, int level, List **joinrels)
* The join rel nodes are returned in a list. * The join rel nodes are returned in a list.
* *
* 'old_rel' is the relation entry for the relation to be joined * 'old_rel' is the relation entry for the relation to be joined
* 'other_rels': other rels to be considered for joining * 'other_rels': the first cell in a linked list containing the other
* rels to be considered for joining
* *
* Currently, this is only used with initial rels in other_rels, but it * Currently, this is only used with initial rels in other_rels, but it
* will work for joining to joinrels too, if the caller ensures there is no * will work for joining to joinrels too, if the caller ensures there is no
@ -282,10 +283,10 @@ make_rels_by_joins(Query *root, int level, List **joinrels)
static List * static List *
make_rels_by_clause_joins(Query *root, make_rels_by_clause_joins(Query *root,
RelOptInfo *old_rel, RelOptInfo *old_rel,
List *other_rels) ListCell *other_rels)
{ {
List *result = NIL; List *result = NIL;
List *i, ListCell *i,
*j; *j;
foreach(i, old_rel->joininfo) foreach(i, old_rel->joininfo)
@ -293,7 +294,7 @@ make_rels_by_clause_joins(Query *root,
JoinInfo *joininfo = (JoinInfo *) lfirst(i); JoinInfo *joininfo = (JoinInfo *) lfirst(i);
Relids unjoined_relids = joininfo->unjoined_relids; Relids unjoined_relids = joininfo->unjoined_relids;
foreach(j, other_rels) for_each_cell(j, other_rels)
{ {
RelOptInfo *other_rel = (RelOptInfo *) lfirst(j); RelOptInfo *other_rel = (RelOptInfo *) lfirst(j);
@ -324,7 +325,8 @@ make_rels_by_clause_joins(Query *root,
* The join rel nodes are returned in a list. * The join rel nodes are returned in a list.
* *
* 'old_rel' is the relation entry for the relation to be joined * 'old_rel' is the relation entry for the relation to be joined
* 'other_rels': other rels to be considered for joining * 'other_rels': the first cell of a linked list containing the
* other rels to be considered for joining
* *
* Currently, this is only used with initial rels in other_rels, but it would * Currently, this is only used with initial rels in other_rels, but it would
* work for joining to joinrels too. * work for joining to joinrels too.
@ -332,12 +334,12 @@ make_rels_by_clause_joins(Query *root,
static List * static List *
make_rels_by_clauseless_joins(Query *root, make_rels_by_clauseless_joins(Query *root,
RelOptInfo *old_rel, RelOptInfo *old_rel,
List *other_rels) ListCell *other_rels)
{ {
List *result = NIL; List *result = NIL;
List *i; ListCell *i;
foreach(i, other_rels) for_each_cell(i, other_rels)
{ {
RelOptInfo *other_rel = (RelOptInfo *) lfirst(i); RelOptInfo *other_rel = (RelOptInfo *) lfirst(i);
@ -370,11 +372,11 @@ make_rels_by_clauseless_joins(Query *root,
static bool static bool
is_inside_IN(Query *root, RelOptInfo *rel) is_inside_IN(Query *root, RelOptInfo *rel)
{ {
List *i; ListCell *l;
foreach(i, root->in_info_list) foreach(l, root->in_info_list)
{ {
InClauseInfo *ininfo = (InClauseInfo *) lfirst(i); InClauseInfo *ininfo = (InClauseInfo *) lfirst(l);
if (bms_is_subset(rel->relids, ininfo->righthand)) if (bms_is_subset(rel->relids, ininfo->righthand))
return true; return true;
@ -476,7 +478,7 @@ make_join_rel(Query *root, RelOptInfo *rel1, RelOptInfo *rel2,
*/ */
if (jointype == JOIN_INNER) if (jointype == JOIN_INNER)
{ {
List *l; ListCell *l;
foreach(l, root->in_info_list) foreach(l, root->in_info_list)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/orindxpath.c,v 1.57 2004/01/05 23:39:54 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/orindxpath.c,v 1.58 2004/05/26 04:41:22 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -100,7 +100,7 @@ create_or_index_quals(Query *root, RelOptInfo *rel)
RestrictInfo *or_rinfo; RestrictInfo *or_rinfo;
Selectivity or_selec, Selectivity or_selec,
orig_selec; orig_selec;
List *i; ListCell *i;
/* /*
* We use the best_or_subclause_indexes() machinery to locate the * We use the best_or_subclause_indexes() machinery to locate the
@ -111,7 +111,7 @@ create_or_index_quals(Query *root, RelOptInfo *rel)
foreach(i, rel->joininfo) foreach(i, rel->joininfo)
{ {
JoinInfo *joininfo = (JoinInfo *) lfirst(i); JoinInfo *joininfo = (JoinInfo *) lfirst(i);
List *j; ListCell *j;
foreach(j, joininfo->jinfo_restrictinfo) foreach(j, joininfo->jinfo_restrictinfo)
{ {
@ -150,7 +150,7 @@ create_or_index_quals(Query *root, RelOptInfo *rel)
newrinfos = make_restrictinfo_from_indexclauses(bestpath->indexclauses, newrinfos = make_restrictinfo_from_indexclauses(bestpath->indexclauses,
true, true); true, true);
Assert(length(newrinfos) == 1); Assert(length(newrinfos) == 1);
or_rinfo = (RestrictInfo *) lfirst(newrinfos); or_rinfo = (RestrictInfo *) linitial(newrinfos);
rel->baserestrictinfo = nconc(rel->baserestrictinfo, newrinfos); rel->baserestrictinfo = nconc(rel->baserestrictinfo, newrinfos);
/* /*
@ -190,15 +190,15 @@ create_or_index_quals(Query *root, RelOptInfo *rel)
void void
create_or_index_paths(Query *root, RelOptInfo *rel) create_or_index_paths(Query *root, RelOptInfo *rel)
{ {
List *i; ListCell *l;
/* /*
* Check each restriction clause to see if it is an OR clause, and if so, * Check each restriction clause to see if it is an OR clause, and if so,
* try to make a path using it. * try to make a path using it.
*/ */
foreach(i, rel->baserestrictinfo) foreach(l, rel->baserestrictinfo)
{ {
RestrictInfo *rinfo = (RestrictInfo *) lfirst(i); RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
if (restriction_is_or_clause(rinfo)) if (restriction_is_or_clause(rinfo))
{ {
@ -248,7 +248,7 @@ best_or_subclause_indexes(Query *root,
FastList quals; FastList quals;
Cost path_startup_cost; Cost path_startup_cost;
Cost path_total_cost; Cost path_total_cost;
List *slist; ListCell *slist;
IndexPath *pathnode; IndexPath *pathnode;
FastListInit(&infos); FastListInit(&infos);
@ -283,7 +283,7 @@ best_or_subclause_indexes(Query *root,
* *
* Total cost is sum of the per-scan costs. * Total cost is sum of the per-scan costs.
*/ */
if (slist == subclauses) /* first scan? */ if (slist == list_head(subclauses)) /* first scan? */
path_startup_cost = best_startup_cost; path_startup_cost = best_startup_cost;
path_total_cost += best_total_cost; path_total_cost += best_total_cost;
} }
@ -351,7 +351,7 @@ best_or_subclause_index(Query *root,
Cost *retTotalCost) /* return value */ Cost *retTotalCost) /* return value */
{ {
bool found = false; bool found = false;
List *ilist; ListCell *ilist;
foreach(ilist, rel->indexlist) foreach(ilist, rel->indexlist)
{ {

View File

@ -11,7 +11,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/pathkeys.c,v 1.56 2004/04/07 17:42:28 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/pathkeys.c,v 1.57 2004/05/26 04:41:22 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -95,8 +95,8 @@ add_equijoined_keys(Query *root, RestrictInfo *restrictinfo)
PathKeyItem *item2 = makePathKeyItem(get_rightop(clause), PathKeyItem *item2 = makePathKeyItem(get_rightop(clause),
restrictinfo->right_sortop, restrictinfo->right_sortop,
false); false);
List *newset, List *newset;
*cursetlink; ListCell *cursetlink;
/* We might see a clause X=X; don't make a single-element list from it */ /* We might see a clause X=X; don't make a single-element list from it */
if (equal(item1, item2)) if (equal(item1, item2))
@ -122,10 +122,10 @@ add_equijoined_keys(Query *root, RestrictInfo *restrictinfo)
newset = NIL; newset = NIL;
/* cannot use foreach here because of possible lremove */ /* cannot use foreach here because of possible lremove */
cursetlink = root->equi_key_list; cursetlink = list_head(root->equi_key_list);
while (cursetlink) while (cursetlink)
{ {
List *curset = lfirst(cursetlink); List *curset = (List *) lfirst(cursetlink);
bool item1here = member(item1, curset); bool item1here = member(item1, curset);
bool item2here = member(item2, curset); bool item2here = member(item2, curset);
@ -199,15 +199,15 @@ add_equijoined_keys(Query *root, RestrictInfo *restrictinfo)
void void
generate_implied_equalities(Query *root) generate_implied_equalities(Query *root)
{ {
List *cursetlink; ListCell *cursetlink;
foreach(cursetlink, root->equi_key_list) foreach(cursetlink, root->equi_key_list)
{ {
List *curset = lfirst(cursetlink); List *curset = (List *) lfirst(cursetlink);
int nitems = length(curset); int nitems = length(curset);
Relids *relids; Relids *relids;
bool have_consts; bool have_consts;
List *ptr1; ListCell *ptr1;
int i1; int i1;
/* /*
@ -245,10 +245,10 @@ generate_implied_equalities(Query *root)
{ {
PathKeyItem *item1 = (PathKeyItem *) lfirst(ptr1); PathKeyItem *item1 = (PathKeyItem *) lfirst(ptr1);
bool i1_is_variable = !bms_is_empty(relids[i1]); bool i1_is_variable = !bms_is_empty(relids[i1]);
List *ptr2; ListCell *ptr2;
int i2 = i1 + 1; int i2 = i1 + 1;
foreach(ptr2, lnext(ptr1)) for_each_cell(ptr2, lnext(ptr1))
{ {
PathKeyItem *item2 = (PathKeyItem *) lfirst(ptr2); PathKeyItem *item2 = (PathKeyItem *) lfirst(ptr2);
bool i2_is_variable = !bms_is_empty(relids[i2]); bool i2_is_variable = !bms_is_empty(relids[i2]);
@ -294,14 +294,14 @@ generate_implied_equalities(Query *root)
bool bool
exprs_known_equal(Query *root, Node *item1, Node *item2) exprs_known_equal(Query *root, Node *item1, Node *item2)
{ {
List *cursetlink; ListCell *cursetlink;
foreach(cursetlink, root->equi_key_list) foreach(cursetlink, root->equi_key_list)
{ {
List *curset = lfirst(cursetlink); List *curset = (List *) lfirst(cursetlink);
bool item1member = false; bool item1member = false;
bool item2member = false; bool item2member = false;
List *ptr; ListCell *ptr;
foreach(ptr, curset) foreach(ptr, curset)
{ {
@ -334,12 +334,12 @@ exprs_known_equal(Query *root, Node *item1, Node *item2)
static List * static List *
make_canonical_pathkey(Query *root, PathKeyItem *item) make_canonical_pathkey(Query *root, PathKeyItem *item)
{ {
List *cursetlink;
List *newset; List *newset;
ListCell *cursetlink;
foreach(cursetlink, root->equi_key_list) foreach(cursetlink, root->equi_key_list)
{ {
List *curset = lfirst(cursetlink); List *curset = (List *) lfirst(cursetlink);
if (member(item, curset)) if (member(item, curset))
return curset; return curset;
@ -360,11 +360,11 @@ List *
canonicalize_pathkeys(Query *root, List *pathkeys) canonicalize_pathkeys(Query *root, List *pathkeys)
{ {
List *new_pathkeys = NIL; List *new_pathkeys = NIL;
List *i; ListCell *l;
foreach(i, pathkeys) foreach(l, pathkeys)
{ {
List *pathkey = (List *) lfirst(i); List *pathkey = (List *) lfirst(l);
PathKeyItem *item; PathKeyItem *item;
List *cpathkey; List *cpathkey;
@ -374,7 +374,7 @@ canonicalize_pathkeys(Query *root, List *pathkeys)
* set by definition. * set by definition.
*/ */
Assert(pathkey != NIL); Assert(pathkey != NIL);
item = (PathKeyItem *) lfirst(pathkey); item = (PathKeyItem *) linitial(pathkey);
cpathkey = make_canonical_pathkey(root, item); cpathkey = make_canonical_pathkey(root, item);
/* /*
@ -402,11 +402,11 @@ canonicalize_pathkeys(Query *root, List *pathkeys)
static int static int
count_canonical_peers(Query *root, PathKeyItem *item) count_canonical_peers(Query *root, PathKeyItem *item)
{ {
List *cursetlink; ListCell *cursetlink;
foreach(cursetlink, root->equi_key_list) foreach(cursetlink, root->equi_key_list)
{ {
List *curset = lfirst(cursetlink); List *curset = (List *) lfirst(cursetlink);
if (member(item, curset)) if (member(item, curset))
return length(curset) - 1; return length(curset) - 1;
@ -430,15 +430,13 @@ count_canonical_peers(Query *root, PathKeyItem *item)
PathKeysComparison PathKeysComparison
compare_pathkeys(List *keys1, List *keys2) compare_pathkeys(List *keys1, List *keys2)
{ {
List *key1, ListCell *key1,
*key2; *key2;
for (key1 = keys1, key2 = keys2; forboth(key1, keys1, key2, keys2)
key1 != NIL && key2 != NIL;
key1 = lnext(key1), key2 = lnext(key2))
{ {
List *subkey1 = lfirst(key1); List *subkey1 = (List *) lfirst(key1);
List *subkey2 = lfirst(key2); List *subkey2 = (List *) lfirst(key2);
/* /*
* XXX would like to check that we've been given canonicalized * XXX would like to check that we've been given canonicalized
@ -465,9 +463,9 @@ compare_pathkeys(List *keys1, List *keys2)
* the other list are not NIL --- no pathkey list should ever have a * the other list are not NIL --- no pathkey list should ever have a
* NIL sublist.) * NIL sublist.)
*/ */
if (key1 == NIL && key2 == NIL) if (key1 == NULL && key2 == NULL)
return PATHKEYS_EQUAL; return PATHKEYS_EQUAL;
if (key1 != NIL) if (key1 != NULL)
return PATHKEYS_BETTER1; /* key1 is longer */ return PATHKEYS_BETTER1; /* key1 is longer */
return PATHKEYS_BETTER2; /* key2 is longer */ return PATHKEYS_BETTER2; /* key2 is longer */
} }
@ -493,15 +491,13 @@ compare_pathkeys(List *keys1, List *keys2)
PathKeysComparison PathKeysComparison
compare_noncanonical_pathkeys(List *keys1, List *keys2) compare_noncanonical_pathkeys(List *keys1, List *keys2)
{ {
List *key1, ListCell *key1,
*key2; *key2;
for (key1 = keys1, key2 = keys2; forboth(key1, keys1, key2, keys2)
key1 != NIL && key2 != NIL;
key1 = lnext(key1), key2 = lnext(key2))
{ {
List *subkey1 = lfirst(key1); List *subkey1 = (List *) lfirst(key1);
List *subkey2 = lfirst(key2); List *subkey2 = (List *) lfirst(key2);
Assert(length(subkey1) == 1); Assert(length(subkey1) == 1);
Assert(length(subkey2) == 1); Assert(length(subkey2) == 1);
@ -515,9 +511,9 @@ compare_noncanonical_pathkeys(List *keys1, List *keys2)
* the other list are not NIL --- no pathkey list should ever have a * the other list are not NIL --- no pathkey list should ever have a
* NIL sublist.) * NIL sublist.)
*/ */
if (key1 == NIL && key2 == NIL) if (key1 == NULL && key2 == NULL)
return PATHKEYS_EQUAL; return PATHKEYS_EQUAL;
if (key1 != NIL) if (key1 != NULL)
return PATHKEYS_BETTER1; /* key1 is longer */ return PATHKEYS_BETTER1; /* key1 is longer */
return PATHKEYS_BETTER2; /* key2 is longer */ return PATHKEYS_BETTER2; /* key2 is longer */
} }
@ -573,11 +569,11 @@ get_cheapest_path_for_pathkeys(List *paths, List *pathkeys,
CostSelector cost_criterion) CostSelector cost_criterion)
{ {
Path *matched_path = NULL; Path *matched_path = NULL;
List *i; ListCell *l;
foreach(i, paths) foreach(l, paths)
{ {
Path *path = (Path *) lfirst(i); Path *path = (Path *) lfirst(l);
/* /*
* Since cost comparison is a lot cheaper than pathkey comparison, * Since cost comparison is a lot cheaper than pathkey comparison,
@ -612,11 +608,11 @@ get_cheapest_fractional_path_for_pathkeys(List *paths,
double fraction) double fraction)
{ {
Path *matched_path = NULL; Path *matched_path = NULL;
List *i; ListCell *l;
foreach(i, paths) foreach(l, paths)
{ {
Path *path = (Path *) lfirst(i); Path *path = (Path *) lfirst(l);
/* /*
* Since cost comparison is a lot cheaper than pathkey comparison, * Since cost comparison is a lot cheaper than pathkey comparison,
@ -658,7 +654,7 @@ build_index_pathkeys(Query *root,
List *retval = NIL; List *retval = NIL;
int *indexkeys = index->indexkeys; int *indexkeys = index->indexkeys;
Oid *ordering = index->ordering; Oid *ordering = index->ordering;
List *indexprs = index->indexprs; ListCell *indexprs_item = list_head(index->indexprs);
while (*ordering != InvalidOid) while (*ordering != InvalidOid)
{ {
@ -683,10 +679,10 @@ build_index_pathkeys(Query *root,
else else
{ {
/* expression --- assume we need not copy it */ /* expression --- assume we need not copy it */
if (indexprs == NIL) if (indexprs_item == NULL)
elog(ERROR, "wrong number of index expressions"); elog(ERROR, "wrong number of index expressions");
indexkey = (Node *) lfirst(indexprs); indexkey = (Node *) lfirst(indexprs_item);
indexprs = lnext(indexprs); indexprs_item = lnext(indexprs_item);
} }
/* OK, make a sublist for this sort key */ /* OK, make a sublist for this sort key */
@ -719,7 +715,7 @@ build_index_pathkeys(Query *root,
static Var * static Var *
find_indexkey_var(Query *root, RelOptInfo *rel, AttrNumber varattno) find_indexkey_var(Query *root, RelOptInfo *rel, AttrNumber varattno)
{ {
List *temp; ListCell *temp;
Index relid; Index relid;
Oid reloid, Oid reloid,
vartypeid; vartypeid;
@ -758,12 +754,12 @@ build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery)
int retvallen = 0; int retvallen = 0;
int outer_query_keys = length(root->query_pathkeys); int outer_query_keys = length(root->query_pathkeys);
List *sub_tlist = rel->subplan->targetlist; List *sub_tlist = rel->subplan->targetlist;
List *l; ListCell *i;
foreach(l, subquery->query_pathkeys) foreach(i, subquery->query_pathkeys)
{ {
List *sub_pathkey = (List *) lfirst(l); List *sub_pathkey = (List *) lfirst(i);
List *j; ListCell *j;
PathKeyItem *best_item = NULL; PathKeyItem *best_item = NULL;
int best_score = 0; int best_score = 0;
List *cpathkey; List *cpathkey;
@ -788,7 +784,7 @@ build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery)
{ {
PathKeyItem *sub_item = (PathKeyItem *) lfirst(j); PathKeyItem *sub_item = (PathKeyItem *) lfirst(j);
Node *sub_key = sub_item->key; Node *sub_key = sub_item->key;
List *k; ListCell *k;
foreach(k, sub_tlist) foreach(k, sub_tlist)
{ {
@ -908,11 +904,11 @@ make_pathkeys_for_sortclauses(List *sortclauses,
List *tlist) List *tlist)
{ {
List *pathkeys = NIL; List *pathkeys = NIL;
List *i; ListCell *l;
foreach(i, sortclauses) foreach(l, sortclauses)
{ {
SortClause *sortcl = (SortClause *) lfirst(i); SortClause *sortcl = (SortClause *) lfirst(l);
Node *sortkey; Node *sortkey;
PathKeyItem *pathkey; PathKeyItem *pathkey;
@ -1000,21 +996,21 @@ find_mergeclauses_for_pathkeys(Query *root,
List *restrictinfos) List *restrictinfos)
{ {
List *mergeclauses = NIL; List *mergeclauses = NIL;
List *i; ListCell *i;
/* make sure we have pathkeys cached in the clauses */ /* make sure we have pathkeys cached in the clauses */
foreach(i, restrictinfos) foreach(i, restrictinfos)
{ {
RestrictInfo *restrictinfo = lfirst(i); RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i);
cache_mergeclause_pathkeys(root, restrictinfo); cache_mergeclause_pathkeys(root, restrictinfo);
} }
foreach(i, pathkeys) foreach(i, pathkeys)
{ {
List *pathkey = lfirst(i); List *pathkey = (List *) lfirst(i);
List *matched_restrictinfos = NIL; List *matched_restrictinfos = NIL;
List *j; ListCell *j;
/* /*
* We can match a pathkey against either left or right side of any * We can match a pathkey against either left or right side of any
@ -1037,7 +1033,7 @@ find_mergeclauses_for_pathkeys(Query *root,
*/ */
foreach(j, restrictinfos) foreach(j, restrictinfos)
{ {
RestrictInfo *restrictinfo = lfirst(j); RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(j);
/* /*
* We can compare canonical pathkey sublists by simple pointer * We can compare canonical pathkey sublists by simple pointer
@ -1093,11 +1089,11 @@ make_pathkeys_for_mergeclauses(Query *root,
RelOptInfo *rel) RelOptInfo *rel)
{ {
List *pathkeys = NIL; List *pathkeys = NIL;
List *i; ListCell *l;
foreach(i, mergeclauses) foreach(l, mergeclauses)
{ {
RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i); RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
List *pathkey; List *pathkey;
cache_mergeclause_pathkeys(root, restrictinfo); cache_mergeclause_pathkeys(root, restrictinfo);
@ -1160,18 +1156,18 @@ int
pathkeys_useful_for_merging(Query *root, RelOptInfo *rel, List *pathkeys) pathkeys_useful_for_merging(Query *root, RelOptInfo *rel, List *pathkeys)
{ {
int useful = 0; int useful = 0;
List *i; ListCell *i;
foreach(i, pathkeys) foreach(i, pathkeys)
{ {
List *pathkey = lfirst(i); List *pathkey = (List *) lfirst(i);
bool matched = false; bool matched = false;
List *j; ListCell *j;
foreach(j, rel->joininfo) foreach(j, rel->joininfo)
{ {
JoinInfo *joininfo = (JoinInfo *) lfirst(j); JoinInfo *joininfo = (JoinInfo *) lfirst(j);
List *k; ListCell *k;
foreach(k, joininfo->jinfo_restrictinfo) foreach(k, joininfo->jinfo_restrictinfo)
{ {

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/path/tidpath.c,v 1.18 2003/11/29 19:51:50 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/path/tidpath.c,v 1.19 2004/05/26 04:41:22 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -33,7 +33,7 @@ static List *TidqualFromExpr(int varno, Expr *expr);
static bool static bool
isEvaluable(int varno, Node *node) isEvaluable(int varno, Node *node)
{ {
List *lst; ListCell *l;
FuncExpr *expr; FuncExpr *expr;
if (IsA(node, Const)) if (IsA(node, Const))
@ -51,9 +51,9 @@ isEvaluable(int varno, Node *node)
if (!is_funcclause(node)) if (!is_funcclause(node))
return false; return false;
expr = (FuncExpr *) node; expr = (FuncExpr *) node;
foreach(lst, expr->args) foreach(l, expr->args)
{ {
if (!isEvaluable(varno, lfirst(lst))) if (!isEvaluable(varno, lfirst(l)))
return false; return false;
} }
@ -81,7 +81,7 @@ TidequalClause(int varno, OpExpr *node)
return rnode; return rnode;
if (length(node->args) != 2) if (length(node->args) != 2)
return rnode; return rnode;
arg1 = lfirst(node->args); arg1 = linitial(node->args);
arg2 = lsecond(node->args); arg2 = lsecond(node->args);
arg = NULL; arg = NULL;
@ -156,8 +156,8 @@ static List *
TidqualFromExpr(int varno, Expr *expr) TidqualFromExpr(int varno, Expr *expr)
{ {
List *rlst = NIL, List *rlst = NIL,
*lst,
*frtn; *frtn;
ListCell *l;
Node *node = (Node *) expr, Node *node = (Node *) expr,
*rnode; *rnode;
@ -169,9 +169,9 @@ TidqualFromExpr(int varno, Expr *expr)
} }
else if (and_clause(node)) else if (and_clause(node))
{ {
foreach(lst, ((BoolExpr *) expr)->args) foreach(l, ((BoolExpr *) expr)->args)
{ {
node = lfirst(lst); node = (Node *) lfirst(l);
rlst = TidqualFromExpr(varno, (Expr *) node); rlst = TidqualFromExpr(varno, (Expr *) node);
if (rlst) if (rlst)
break; break;
@ -179,9 +179,9 @@ TidqualFromExpr(int varno, Expr *expr)
} }
else if (or_clause(node)) else if (or_clause(node))
{ {
foreach(lst, ((BoolExpr *) expr)->args) foreach(l, ((BoolExpr *) expr)->args)
{ {
node = lfirst(lst); node = (Node *) lfirst(l);
frtn = TidqualFromExpr(varno, (Expr *) node); frtn = TidqualFromExpr(varno, (Expr *) node);
if (frtn) if (frtn)
rlst = nconc(rlst, frtn); rlst = nconc(rlst, frtn);
@ -200,8 +200,8 @@ TidqualFromExpr(int varno, Expr *expr)
static List * static List *
TidqualFromRestrictinfo(Relids relids, List *restrictinfo) TidqualFromRestrictinfo(Relids relids, List *restrictinfo)
{ {
List *lst, ListCell *l;
*rlst = NIL; List *rlst = NIL;
int varno; int varno;
Node *node; Node *node;
Expr *expr; Expr *expr;
@ -209,9 +209,9 @@ TidqualFromRestrictinfo(Relids relids, List *restrictinfo)
if (bms_membership(relids) != BMS_SINGLETON) if (bms_membership(relids) != BMS_SINGLETON)
return NIL; return NIL;
varno = bms_singleton_member(relids); varno = bms_singleton_member(relids);
foreach(lst, restrictinfo) foreach(l, restrictinfo)
{ {
node = lfirst(lst); node = (Node *) lfirst(l);
if (!IsA(node, RestrictInfo)) if (!IsA(node, RestrictInfo))
continue; continue;
expr = ((RestrictInfo *) node)->clause; expr = ((RestrictInfo *) node)->clause;

View File

@ -10,7 +10,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/plan/createplan.c,v 1.169 2004/04/25 18:23:56 neilc Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/plan/createplan.c,v 1.170 2004/05/26 04:41:24 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -263,7 +263,7 @@ build_relation_tlist(RelOptInfo *rel)
{ {
FastList tlist; FastList tlist;
int resdomno = 1; int resdomno = 1;
List *v; ListCell *v;
FastListInit(&tlist); FastListInit(&tlist);
foreach(v, FastListValue(&rel->reltargetlist)) foreach(v, FastListValue(&rel->reltargetlist))
@ -415,7 +415,7 @@ create_append_plan(Query *root, AppendPath *best_path)
Append *plan; Append *plan;
List *tlist = build_relation_tlist(best_path->path.parent); List *tlist = build_relation_tlist(best_path->path.parent);
List *subplans = NIL; List *subplans = NIL;
List *subpaths; ListCell *subpaths;
foreach(subpaths, best_path->subpaths) foreach(subpaths, best_path->subpaths)
{ {
@ -505,7 +505,7 @@ create_unique_plan(Query *root, UniquePath *best_path)
List *newtlist; List *newtlist;
int nextresno; int nextresno;
bool newitems; bool newitems;
List *l; ListCell *l;
subplan = create_plan(root, best_path->subpath); subplan = create_plan(root, best_path->subpath);
@ -544,7 +544,7 @@ create_unique_plan(Query *root, UniquePath *best_path)
break; break;
} }
} }
if (l == NIL) /* fell out of loop? */ if (l == NULL) /* fell out of loop? */
elog(ERROR, "could not find UniquePath in in_info_list"); elog(ERROR, "could not find UniquePath in in_info_list");
/* set up to record positions of unique columns */ /* set up to record positions of unique columns */
@ -702,7 +702,7 @@ create_indexscan_plan(Query *root,
List *indxsubtype; List *indxsubtype;
List *indxlossy; List *indxlossy;
FastList indexids; FastList indexids;
List *i; ListCell *l;
IndexScan *scan_plan; IndexScan *scan_plan;
/* it should be a base rel... */ /* it should be a base rel... */
@ -727,7 +727,7 @@ create_indexscan_plan(Query *root,
*/ */
Assert(length(best_path->indexclauses) == 1); Assert(length(best_path->indexclauses) == 1);
scan_clauses = set_ptrUnion(scan_clauses, scan_clauses = set_ptrUnion(scan_clauses,
(List *) lfirst(best_path->indexclauses)); (List *) linitial(best_path->indexclauses));
} }
/* Reduce RestrictInfo list to bare expressions */ /* Reduce RestrictInfo list to bare expressions */
@ -738,9 +738,9 @@ create_indexscan_plan(Query *root,
/* Build list of index OIDs */ /* Build list of index OIDs */
FastListInit(&indexids); FastListInit(&indexids);
foreach(i, best_path->indexinfo) foreach(l, best_path->indexinfo)
{ {
IndexOptInfo *index = (IndexOptInfo *) lfirst(i); IndexOptInfo *index = (IndexOptInfo *) lfirst(l);
FastAppendo(&indexids, index->indexoid); FastAppendo(&indexids, index->indexoid);
} }
@ -750,9 +750,9 @@ create_indexscan_plan(Query *root,
* executor as indxqualorig * executor as indxqualorig
*/ */
stripped_indxquals = NIL; stripped_indxquals = NIL;
foreach(i, indxquals) foreach(l, indxquals)
{ {
List *andlist = (List *) lfirst(i); List *andlist = (List *) lfirst(l);
stripped_indxquals = lappend(stripped_indxquals, stripped_indxquals = lappend(stripped_indxquals,
get_actual_clauses(andlist)); get_actual_clauses(andlist));
@ -785,7 +785,7 @@ create_indexscan_plan(Query *root,
* behavior. * behavior.
*/ */
Assert(stripped_indxquals != NIL); Assert(stripped_indxquals != NIL);
qpqual = set_difference(scan_clauses, lfirst(stripped_indxquals)); qpqual = set_difference(scan_clauses, linitial(stripped_indxquals));
} }
/* /*
@ -955,7 +955,7 @@ create_nestloop_plan(Query *root,
joinrestrictclauses = joinrestrictclauses =
select_nonredundant_join_clauses(root, select_nonredundant_join_clauses(root,
joinrestrictclauses, joinrestrictclauses,
lfirst(indexclauses), linitial(indexclauses),
best_path->jointype); best_path->jointype);
} }
} }
@ -1182,17 +1182,17 @@ fix_indxqual_references(List *indexquals, IndexPath *index_path,
{ {
Relids baserelids = index_path->path.parent->relids; Relids baserelids = index_path->path.parent->relids;
int baserelid = index_path->path.parent->relid; int baserelid = index_path->path.parent->relid;
List *ixinfo = index_path->indexinfo; List *index_info = index_path->indexinfo;
List *i; ListCell *iq, *ii;
*fixed_indexquals = NIL; *fixed_indexquals = NIL;
*indxstrategy = NIL; *indxstrategy = NIL;
*indxsubtype = NIL; *indxsubtype = NIL;
*indxlossy = NIL; *indxlossy = NIL;
foreach(i, indexquals) forboth(iq, indexquals, ii, index_info)
{ {
List *indexqual = lfirst(i); List *indexqual = (List *) lfirst(iq);
IndexOptInfo *index = (IndexOptInfo *) lfirst(ixinfo); IndexOptInfo *index = (IndexOptInfo *) lfirst(ii);
List *fixed_qual; List *fixed_qual;
List *strategy; List *strategy;
List *subtype; List *subtype;
@ -1204,8 +1204,6 @@ fix_indxqual_references(List *indexquals, IndexPath *index_path,
*indxstrategy = lappend(*indxstrategy, strategy); *indxstrategy = lappend(*indxstrategy, strategy);
*indxsubtype = lappend(*indxsubtype, subtype); *indxsubtype = lappend(*indxsubtype, subtype);
*indxlossy = lappend(*indxlossy, lossy); *indxlossy = lappend(*indxlossy, lossy);
ixinfo = lnext(ixinfo);
} }
} }
@ -1232,15 +1230,15 @@ fix_indxqual_sublist(List *indexqual,
List **subtype, List **subtype,
List **lossy) List **lossy)
{ {
List *i; ListCell *l;
*fixed_quals = NIL; *fixed_quals = NIL;
*strategy = NIL; *strategy = NIL;
*subtype = NIL; *subtype = NIL;
*lossy = NIL; *lossy = NIL;
foreach(i, indexqual) foreach(l, indexqual)
{ {
RestrictInfo *rinfo = (RestrictInfo *) lfirst(i); RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
OpExpr *clause; OpExpr *clause;
OpExpr *newclause; OpExpr *newclause;
Oid opclass; Oid opclass;
@ -1250,8 +1248,7 @@ fix_indxqual_sublist(List *indexqual,
Assert(IsA(rinfo, RestrictInfo)); Assert(IsA(rinfo, RestrictInfo));
clause = (OpExpr *) rinfo->clause; clause = (OpExpr *) rinfo->clause;
if (!IsA(clause, OpExpr) || if (!IsA(clause, OpExpr) || length(clause->args) != 2)
length(clause->args) != 2)
elog(ERROR, "indexqual clause is not binary opclause"); elog(ERROR, "indexqual clause is not binary opclause");
/* /*
@ -1275,7 +1272,7 @@ fix_indxqual_sublist(List *indexqual,
* Now, determine which index attribute this is, change the * Now, determine which index attribute this is, change the
* indexkey operand as needed, and get the index opclass. * indexkey operand as needed, and get the index opclass.
*/ */
lfirst(newclause->args) = fix_indxqual_operand(lfirst(newclause->args), linitial(newclause->args) = fix_indxqual_operand(linitial(newclause->args),
baserelid, baserelid,
index, index,
&opclass); &opclass);
@ -1309,7 +1306,7 @@ fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index,
*/ */
Var *result; Var *result;
int pos; int pos;
List *indexprs; ListCell *indexpr_item;
/* /*
* Remove any binary-compatible relabeling of the indexkey * Remove any binary-compatible relabeling of the indexkey
@ -1340,29 +1337,29 @@ fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index,
} }
/* Try to match against index expressions */ /* Try to match against index expressions */
indexprs = index->indexprs; indexpr_item = list_head(index->indexprs);
for (pos = 0; pos < index->ncolumns; pos++) for (pos = 0; pos < index->ncolumns; pos++)
{ {
if (index->indexkeys[pos] == 0) if (index->indexkeys[pos] == 0)
{ {
Node *indexkey; Node *indexkey;
if (indexprs == NIL) if (indexpr_item == NULL)
elog(ERROR, "too few entries in indexprs list"); elog(ERROR, "too few entries in indexprs list");
indexkey = (Node *) lfirst(indexprs); indexkey = (Node *) lfirst(indexpr_item);
if (indexkey && IsA(indexkey, RelabelType)) if (indexkey && IsA(indexkey, RelabelType))
indexkey = (Node *) ((RelabelType *) indexkey)->arg; indexkey = (Node *) ((RelabelType *) indexkey)->arg;
if (equal(node, indexkey)) if (equal(node, indexkey))
{ {
/* Found a match */ /* Found a match */
result = makeVar(baserelid, pos + 1, result = makeVar(baserelid, pos + 1,
exprType(lfirst(indexprs)), -1, exprType(lfirst(indexpr_item)), -1,
0); 0);
/* return the correct opclass, too */ /* return the correct opclass, too */
*opclass = index->classlist[pos]; *opclass = index->classlist[pos];
return (Node *) result; return (Node *) result;
} }
indexprs = lnext(indexprs); indexpr_item = lnext(indexpr_item);
} }
} }
@ -1383,11 +1380,11 @@ static List *
get_switched_clauses(List *clauses, Relids outerrelids) get_switched_clauses(List *clauses, Relids outerrelids)
{ {
List *t_list = NIL; List *t_list = NIL;
List *i; ListCell *l;
foreach(i, clauses) foreach(l, clauses)
{ {
RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i); RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
OpExpr *clause = (OpExpr *) restrictinfo->clause; OpExpr *clause = (OpExpr *) restrictinfo->clause;
Assert(is_opclause(clause)); Assert(is_opclause(clause));
@ -1432,7 +1429,7 @@ order_qual_clauses(Query *root, List *clauses)
{ {
FastList nosubplans; FastList nosubplans;
FastList withsubplans; FastList withsubplans;
List *l; ListCell *l;
/* No need to work hard if the query is subselect-free */ /* No need to work hard if the query is subselect-free */
if (!root->hasSubLinks) if (!root->hasSubLinks)
@ -1442,7 +1439,7 @@ order_qual_clauses(Query *root, List *clauses)
FastListInit(&withsubplans); FastListInit(&withsubplans);
foreach(l, clauses) foreach(l, clauses)
{ {
Node *clause = lfirst(l); Node *clause = (Node *) lfirst(l);
if (contain_subplans(clause)) if (contain_subplans(clause))
FastAppend(&withsubplans, clause); FastAppend(&withsubplans, clause);
@ -1632,7 +1629,7 @@ make_append(List *appendplans, bool isTarget, List *tlist)
{ {
Append *node = makeNode(Append); Append *node = makeNode(Append);
Plan *plan = &node->plan; Plan *plan = &node->plan;
List *subnode; ListCell *subnode;
/* /*
* Compute cost as sum of subplan costs. We charge nothing extra for * Compute cost as sum of subplan costs. We charge nothing extra for
@ -1647,7 +1644,7 @@ make_append(List *appendplans, bool isTarget, List *tlist)
{ {
Plan *subplan = (Plan *) lfirst(subnode); Plan *subplan = (Plan *) lfirst(subnode);
if (subnode == appendplans) /* first node? */ if (subnode == list_head(appendplans)) /* first node? */
plan->startup_cost = subplan->startup_cost; plan->startup_cost = subplan->startup_cost;
plan->total_cost += subplan->total_cost; plan->total_cost += subplan->total_cost;
plan->plan_rows += subplan->plan_rows; plan->plan_rows += subplan->plan_rows;
@ -1837,7 +1834,7 @@ static Sort *
make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys) make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
{ {
List *tlist = lefttree->targetlist; List *tlist = lefttree->targetlist;
List *i; ListCell *i;
int numsortkeys; int numsortkeys;
AttrNumber *sortColIdx; AttrNumber *sortColIdx;
Oid *sortOperators; Oid *sortOperators;
@ -1854,7 +1851,7 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
List *keysublist = (List *) lfirst(i); List *keysublist = (List *) lfirst(i);
PathKeyItem *pathkey = NULL; PathKeyItem *pathkey = NULL;
Resdom *resdom = NULL; Resdom *resdom = NULL;
List *j; ListCell *j;
/* /*
* We can sort by any one of the sort key items listed in this * We can sort by any one of the sort key items listed in this
@ -1870,7 +1867,7 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
*/ */
foreach(j, keysublist) foreach(j, keysublist)
{ {
pathkey = lfirst(j); pathkey = (PathKeyItem *) lfirst(j);
Assert(IsA(pathkey, PathKeyItem)); Assert(IsA(pathkey, PathKeyItem));
resdom = tlist_member(pathkey->key, tlist); resdom = tlist_member(pathkey->key, tlist);
if (resdom) if (resdom)
@ -1882,9 +1879,9 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
foreach(j, keysublist) foreach(j, keysublist)
{ {
List *exprvars; List *exprvars;
List *k; ListCell *k;
pathkey = lfirst(j); pathkey = (PathKeyItem *) lfirst(j);
exprvars = pull_var_clause(pathkey->key, false); exprvars = pull_var_clause(pathkey->key, false);
foreach(k, exprvars) foreach(k, exprvars)
{ {
@ -1948,7 +1945,7 @@ Sort *
make_sort_from_sortclauses(Query *root, List *sortcls, Plan *lefttree) make_sort_from_sortclauses(Query *root, List *sortcls, Plan *lefttree)
{ {
List *sub_tlist = lefttree->targetlist; List *sub_tlist = lefttree->targetlist;
List *i; ListCell *l;
int numsortkeys; int numsortkeys;
AttrNumber *sortColIdx; AttrNumber *sortColIdx;
Oid *sortOperators; Oid *sortOperators;
@ -1960,9 +1957,9 @@ make_sort_from_sortclauses(Query *root, List *sortcls, Plan *lefttree)
numsortkeys = 0; numsortkeys = 0;
foreach(i, sortcls) foreach(l, sortcls)
{ {
SortClause *sortcl = (SortClause *) lfirst(i); SortClause *sortcl = (SortClause *) lfirst(l);
TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist); TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
/* /*
@ -2001,7 +1998,7 @@ make_sort_from_groupcols(Query *root,
{ {
List *sub_tlist = lefttree->targetlist; List *sub_tlist = lefttree->targetlist;
int grpno = 0; int grpno = 0;
List *i; ListCell *l;
int numsortkeys; int numsortkeys;
AttrNumber *sortColIdx; AttrNumber *sortColIdx;
Oid *sortOperators; Oid *sortOperators;
@ -2013,9 +2010,9 @@ make_sort_from_groupcols(Query *root,
numsortkeys = 0; numsortkeys = 0;
foreach(i, groupcls) foreach(l, groupcls)
{ {
GroupClause *grpcl = (GroupClause *) lfirst(i); GroupClause *grpcl = (GroupClause *) lfirst(l);
TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[grpno]); TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[grpno]);
/* /*
@ -2213,7 +2210,7 @@ make_unique(Plan *lefttree, List *distinctList)
int numCols = length(distinctList); int numCols = length(distinctList);
int keyno = 0; int keyno = 0;
AttrNumber *uniqColIdx; AttrNumber *uniqColIdx;
List *slitem; ListCell *slitem;
copy_plan_costsize(plan, lefttree); copy_plan_costsize(plan, lefttree);
@ -2270,7 +2267,7 @@ make_setop(SetOpCmd cmd, Plan *lefttree,
int numCols = length(distinctList); int numCols = length(distinctList);
int keyno = 0; int keyno = 0;
AttrNumber *dupColIdx; AttrNumber *dupColIdx;
List *slitem; ListCell *slitem;
copy_plan_costsize(plan, lefttree); copy_plan_costsize(plan, lefttree);

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/plan/initsplan.c,v 1.98 2004/02/27 21:42:00 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/plan/initsplan.c,v 1.99 2004/05/26 04:41:24 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -81,7 +81,7 @@ add_base_rels_to_query(Query *root, Node *jtnode)
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
add_base_rels_to_query(root, lfirst(l)); add_base_rels_to_query(root, lfirst(l));
@ -135,7 +135,7 @@ build_base_rel_tlists(Query *root, List *final_tlist)
static void static void
add_vars_to_targetlist(Query *root, List *vars, Relids where_needed) add_vars_to_targetlist(Query *root, List *vars, Relids where_needed)
{ {
List *temp; ListCell *temp;
Assert(!bms_is_empty(where_needed)); Assert(!bms_is_empty(where_needed));
@ -205,8 +205,7 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
List *qual;
/* /*
* First, recurse to handle child joins. * First, recurse to handle child joins.
@ -222,8 +221,8 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
* Now process the top-level quals. These are always marked as * Now process the top-level quals. These are always marked as
* "pushed down", since they clearly didn't come from a JOIN expr. * "pushed down", since they clearly didn't come from a JOIN expr.
*/ */
foreach(qual, (List *) f->quals) foreach(l, (List *) f->quals)
distribute_qual_to_rels(root, (Node *) lfirst(qual), distribute_qual_to_rels(root, (Node *) lfirst(l),
true, false, NULL, result); true, false, NULL, result);
} }
else if (IsA(jtnode, JoinExpr)) else if (IsA(jtnode, JoinExpr))
@ -233,7 +232,7 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
rightids, rightids,
nonnullable_rels, nonnullable_rels,
nullable_rels; nullable_rels;
List *qual; ListCell *qual;
/* /*
* Order of operations here is subtle and critical. First we * Order of operations here is subtle and critical. First we
@ -636,7 +635,7 @@ process_implied_equality(Query *root,
BMS_Membership membership; BMS_Membership membership;
RelOptInfo *rel1; RelOptInfo *rel1;
List *restrictlist; List *restrictlist;
List *itm; ListCell *itm;
Oid ltype, Oid ltype,
rtype; rtype;
Operator eq_operator; Operator eq_operator;
@ -803,7 +802,7 @@ qual_is_redundant(Query *root,
Node *newleft; Node *newleft;
Node *newright; Node *newright;
List *oldquals; List *oldquals;
List *olditem; ListCell *olditem;
List *equalexprs; List *equalexprs;
bool someadded; bool someadded;
@ -860,7 +859,7 @@ qual_is_redundant(Query *root,
{ {
someadded = false; someadded = false;
/* cannot use foreach here because of possible lremove */ /* cannot use foreach here because of possible lremove */
olditem = oldquals; olditem = list_head(oldquals);
while (olditem) while (olditem)
{ {
RestrictInfo *oldrinfo = (RestrictInfo *) lfirst(olditem); RestrictInfo *oldrinfo = (RestrictInfo *) lfirst(olditem);

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.169 2004/05/11 02:21:37 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.170 2004/05/26 04:41:24 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -174,6 +174,7 @@ subquery_planner(Query *parse, double tuple_fraction)
Plan *plan; Plan *plan;
List *newHaving; List *newHaving;
List *lst; List *lst;
ListCell *l;
/* Set up for a new level of subquery */ /* Set up for a new level of subquery */
PlannerQueryLevel++; PlannerQueryLevel++;
@ -206,9 +207,9 @@ subquery_planner(Query *parse, double tuple_fraction)
*/ */
parse->hasJoinRTEs = false; parse->hasJoinRTEs = false;
hasOuterJoins = false; hasOuterJoins = false;
foreach(lst, parse->rtable) foreach(l, parse->rtable)
{ {
RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst); RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
if (rte->rtekind == RTE_JOIN) if (rte->rtekind == RTE_JOIN)
{ {
@ -244,9 +245,9 @@ subquery_planner(Query *parse, double tuple_fraction)
EXPRKIND_ININFO); EXPRKIND_ININFO);
/* Also need to preprocess expressions for function RTEs */ /* Also need to preprocess expressions for function RTEs */
foreach(lst, parse->rtable) foreach(l, parse->rtable)
{ {
RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst); RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
if (rte->rtekind == RTE_FUNCTION) if (rte->rtekind == RTE_FUNCTION)
rte->funcexpr = preprocess_expression(parse, rte->funcexpr, rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
@ -271,9 +272,9 @@ subquery_planner(Query *parse, double tuple_fraction)
* declared as Node *. * declared as Node *.
*/ */
newHaving = NIL; newHaving = NIL;
foreach(lst, (List *) parse->havingQual) foreach(l, (List *) parse->havingQual)
{ {
Node *havingclause = (Node *) lfirst(lst); Node *havingclause = (Node *) lfirst(l);
if (contain_agg_clause(havingclause)) if (contain_agg_clause(havingclause))
newHaving = lappend(newHaving, havingclause); newHaving = lappend(newHaving, havingclause);
@ -337,9 +338,9 @@ subquery_planner(Query *parse, double tuple_fraction)
*/ */
plan->initPlan = PlannerInitPlan; plan->initPlan = PlannerInitPlan;
foreach(lst, plan->initPlan) foreach(l, plan->initPlan)
{ {
SubPlan *initplan = (SubPlan *) lfirst(lst); SubPlan *initplan = (SubPlan *) lfirst(l);
plan->extParam = bms_add_members(plan->extParam, plan->extParam = bms_add_members(plan->extParam,
initplan->plan->extParam); initplan->plan->extParam);
@ -445,7 +446,7 @@ preprocess_qual_conditions(Query *parse, Node *jtnode)
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
preprocess_qual_conditions(parse, lfirst(l)); preprocess_qual_conditions(parse, lfirst(l));
@ -495,7 +496,7 @@ inheritance_planner(Query *parse, List *inheritlist)
int mainrtlength = length(parse->rtable); int mainrtlength = length(parse->rtable);
List *subplans = NIL; List *subplans = NIL;
List *tlist = NIL; List *tlist = NIL;
List *l; ListCell *l;
foreach(l, inheritlist) foreach(l, inheritlist)
{ {
@ -524,10 +525,9 @@ inheritance_planner(Query *parse, List *inheritlist)
subrtlength = length(subquery->rtable); subrtlength = length(subquery->rtable);
if (subrtlength > mainrtlength) if (subrtlength > mainrtlength)
{ {
List *subrt = subquery->rtable; List *subrt;
while (mainrtlength-- > 0) /* wish we had nthcdr() */ subrt = list_copy_tail(subquery->rtable, mainrtlength);
subrt = lnext(subrt);
parse->rtable = nconc(parse->rtable, subrt); parse->rtable = nconc(parse->rtable, subrt);
mainrtlength = subrtlength; mainrtlength = subrtlength;
} }
@ -650,7 +650,7 @@ grouping_planner(Query *parse, double tuple_fraction)
*/ */
if (parse->rowMarks) if (parse->rowMarks)
{ {
List *l; ListCell *l;
/* /*
* We've got trouble if the FOR UPDATE appears inside * We've got trouble if the FOR UPDATE appears inside
@ -1328,7 +1328,7 @@ grouping_planner(Query *parse, double tuple_fraction)
static bool static bool
hash_safe_grouping(Query *parse) hash_safe_grouping(Query *parse)
{ {
List *gl; ListCell *gl;
foreach(gl, parse->groupClause) foreach(gl, parse->groupClause)
{ {
@ -1435,7 +1435,7 @@ make_subplanTargetList(Query *parse,
{ {
int keyno = 0; int keyno = 0;
AttrNumber *grpColIdx; AttrNumber *grpColIdx;
List *gl; ListCell *gl;
grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols); grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
*groupColIdx = grpColIdx; *groupColIdx = grpColIdx;
@ -1445,7 +1445,7 @@ make_subplanTargetList(Query *parse,
GroupClause *grpcl = (GroupClause *) lfirst(gl); GroupClause *grpcl = (GroupClause *) lfirst(gl);
Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist); Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
TargetEntry *te = NULL; TargetEntry *te = NULL;
List *sl; ListCell *sl;
/* Find or make a matching sub_tlist entry */ /* Find or make a matching sub_tlist entry */
foreach(sl, sub_tlist) foreach(sl, sub_tlist)
@ -1489,7 +1489,7 @@ locate_grouping_columns(Query *parse,
AttrNumber *groupColIdx) AttrNumber *groupColIdx)
{ {
int keyno = 0; int keyno = 0;
List *gl; ListCell *gl;
/* /*
* No work unless grouping. * No work unless grouping.
@ -1506,7 +1506,7 @@ locate_grouping_columns(Query *parse,
GroupClause *grpcl = (GroupClause *) lfirst(gl); GroupClause *grpcl = (GroupClause *) lfirst(gl);
Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist); Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
TargetEntry *te = NULL; TargetEntry *te = NULL;
List *sl; ListCell *sl;
foreach(sl, sub_tlist) foreach(sl, sub_tlist)
{ {
@ -1534,7 +1534,8 @@ locate_grouping_columns(Query *parse,
static List * static List *
postprocess_setop_tlist(List *new_tlist, List *orig_tlist) postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
{ {
List *l; ListCell *l;
ListCell *orig_tlist_item = list_head(orig_tlist);
foreach(l, new_tlist) foreach(l, new_tlist)
{ {
@ -1545,16 +1546,16 @@ postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
if (new_tle->resdom->resjunk) if (new_tle->resdom->resjunk)
continue; continue;
Assert(orig_tlist != NIL); Assert(orig_tlist_item != NULL);
orig_tle = (TargetEntry *) lfirst(orig_tlist); orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
orig_tlist = lnext(orig_tlist); orig_tlist_item = lnext(orig_tlist_item);
if (orig_tle->resdom->resjunk) /* should not happen */ if (orig_tle->resdom->resjunk) /* should not happen */
elog(ERROR, "resjunk output columns are not implemented"); elog(ERROR, "resjunk output columns are not implemented");
Assert(new_tle->resdom->resno == orig_tle->resdom->resno); Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
Assert(new_tle->resdom->restype == orig_tle->resdom->restype); Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref; new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
} }
if (orig_tlist != NIL) if (orig_tlist_item != NULL)
elog(ERROR, "resjunk output columns are not implemented"); elog(ERROR, "resjunk output columns are not implemented");
return new_tlist; return new_tlist;
} }

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/plan/setrefs.c,v 1.101 2004/05/11 13:15:15 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/plan/setrefs.c,v 1.102 2004/05/26 04:41:24 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -84,7 +84,7 @@ static void set_sa_opfuncid(ScalarArrayOpExpr *opexpr);
void void
set_plan_references(Plan *plan, List *rtable) set_plan_references(Plan *plan, List *rtable)
{ {
List *pl; ListCell *l;
if (plan == NULL) if (plan == NULL)
return; return;
@ -213,15 +213,14 @@ set_plan_references(Plan *plan, List *rtable)
fix_expr_references(plan, ((Result *) plan)->resconstantqual); fix_expr_references(plan, ((Result *) plan)->resconstantqual);
break; break;
case T_Append: case T_Append:
/* /*
* Append, like Sort et al, doesn't actually evaluate its * Append, like Sort et al, doesn't actually evaluate its
* targetlist or quals, and we haven't bothered to give it its * targetlist or quals, and we haven't bothered to give it
* own tlist copy. So, don't fix targetlist/qual. But do * its own tlist copy. So, don't fix targetlist/qual. But
* recurse into child plans. * do recurse into child plans.
*/ */
foreach(pl, ((Append *) plan)->appendplans) foreach(l, ((Append *) plan)->appendplans)
set_plan_references((Plan *) lfirst(pl), rtable); set_plan_references((Plan *) lfirst(l), rtable);
break; break;
default: default:
elog(ERROR, "unrecognized node type: %d", elog(ERROR, "unrecognized node type: %d",
@ -242,9 +241,9 @@ set_plan_references(Plan *plan, List *rtable)
set_plan_references(plan->lefttree, rtable); set_plan_references(plan->lefttree, rtable);
set_plan_references(plan->righttree, rtable); set_plan_references(plan->righttree, rtable);
foreach(pl, plan->initPlan) foreach(l, plan->initPlan)
{ {
SubPlan *sp = (SubPlan *) lfirst(pl); SubPlan *sp = (SubPlan *) lfirst(l);
Assert(IsA(sp, SubPlan)); Assert(IsA(sp, SubPlan));
set_plan_references(sp->plan, sp->rtable); set_plan_references(sp->plan, sp->rtable);
@ -440,8 +439,8 @@ set_uppernode_references(Plan *plan, Index subvarno)
{ {
Plan *subplan = plan->lefttree; Plan *subplan = plan->lefttree;
List *subplan_targetlist, List *subplan_targetlist,
*output_targetlist, *output_targetlist;
*l; ListCell *l;
bool tlist_has_non_vars; bool tlist_has_non_vars;
if (subplan != NULL) if (subplan != NULL)
@ -483,7 +482,7 @@ set_uppernode_references(Plan *plan, Index subvarno)
static bool static bool
targetlist_has_non_vars(List *tlist) targetlist_has_non_vars(List *tlist)
{ {
List *l; ListCell *l;
foreach(l, tlist) foreach(l, tlist)
{ {

View File

@ -7,7 +7,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/plan/subselect.c,v 1.89 2004/05/11 13:15:15 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/plan/subselect.c,v 1.90 2004/05/26 04:41:24 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -101,7 +101,7 @@ static Param *
replace_outer_var(Var *var) replace_outer_var(Var *var)
{ {
Param *retval; Param *retval;
List *ppl; ListCell *ppl;
PlannerParamItem *pitem; PlannerParamItem *pitem;
Index abslevel; Index abslevel;
int i; int i;
@ -250,7 +250,6 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual)
Plan *plan; Plan *plan;
Bitmapset *tmpset; Bitmapset *tmpset;
int paramid; int paramid;
List *lst;
Node *result; Node *result;
/* /*
@ -348,7 +347,7 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual)
} }
else if (node->parParam == NIL && slink->subLinkType == EXPR_SUBLINK) else if (node->parParam == NIL && slink->subLinkType == EXPR_SUBLINK)
{ {
TargetEntry *te = lfirst(plan->targetlist); TargetEntry *te = linitial(plan->targetlist);
Param *prm; Param *prm;
Assert(!te->resdom->resjunk); Assert(!te->resdom->resjunk);
@ -359,7 +358,7 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual)
} }
else if (node->parParam == NIL && slink->subLinkType == ARRAY_SUBLINK) else if (node->parParam == NIL && slink->subLinkType == ARRAY_SUBLINK)
{ {
TargetEntry *te = lfirst(plan->targetlist); TargetEntry *te = linitial(plan->targetlist);
Oid arraytype; Oid arraytype;
Param *prm; Param *prm;
@ -395,11 +394,12 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual)
result = (Node *) (node->useOr ? make_orclause(exprs) : result = (Node *) (node->useOr ? make_orclause(exprs) :
make_andclause(exprs)); make_andclause(exprs));
else else
result = (Node *) lfirst(exprs); result = (Node *) linitial(exprs);
} }
else else
{ {
List *args; List *args;
ListCell *l;
/* /*
* We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types
@ -471,9 +471,9 @@ make_subplan(SubLink *slink, List *lefthand, bool isTopQual)
* Make node->args from parParam. * Make node->args from parParam.
*/ */
args = NIL; args = NIL;
foreach(lst, node->parParam) foreach(l, node->parParam)
{ {
PlannerParamItem *pitem = nth(lfirsti(lst), PlannerParamList); PlannerParamItem *pitem = nth(lfirsti(l), PlannerParamList);
/* /*
* The Var or Aggref has already been adjusted to have the * The Var or Aggref has already been adjusted to have the
@ -509,15 +509,17 @@ convert_sublink_opers(List *lefthand, List *operOids,
List **righthandIds) List **righthandIds)
{ {
List *result = NIL; List *result = NIL;
List *lst; ListCell *l, *lefthand_item, *tlist_item;
*righthandIds = NIL; *righthandIds = NIL;
lefthand_item = list_head(lefthand);
tlist_item = list_head(targetlist);
foreach(lst, operOids) foreach(l, operOids)
{ {
Oid opid = lfirsto(lst); Oid opid = lfirsto(l);
Node *leftop = lfirst(lefthand); Node *leftop = (Node *) lfirst(lefthand_item);
TargetEntry *te = lfirst(targetlist); TargetEntry *te = (TargetEntry *) lfirst(tlist_item);
Node *rightop; Node *rightop;
Operator tup; Operator tup;
@ -574,8 +576,8 @@ convert_sublink_opers(List *lefthand, List *operOids,
ReleaseSysCache(tup); ReleaseSysCache(tup);
lefthand = lnext(lefthand); lefthand_item = lnext(lefthand_item);
targetlist = lnext(targetlist); tlist_item = lnext(tlist_item);
} }
return result; return result;
@ -591,7 +593,7 @@ static bool
subplan_is_hashable(SubLink *slink, SubPlan *node) subplan_is_hashable(SubLink *slink, SubPlan *node)
{ {
double subquery_size; double subquery_size;
List *opids; ListCell *l;
/* /*
* The sublink type must be "= ANY" --- that is, an IN operator. (We * The sublink type must be "= ANY" --- that is, an IN operator. (We
@ -602,7 +604,7 @@ subplan_is_hashable(SubLink *slink, SubPlan *node)
if (slink->subLinkType != ANY_SUBLINK) if (slink->subLinkType != ANY_SUBLINK)
return false; return false;
if (length(slink->operName) != 1 || if (length(slink->operName) != 1 ||
strcmp(strVal(lfirst(slink->operName)), "=") != 0) strcmp(strVal(linitial(slink->operName)), "=") != 0)
return false; return false;
/* /*
@ -636,9 +638,9 @@ subplan_is_hashable(SubLink *slink, SubPlan *node)
* different sets of operators with the hash table, but there is no * different sets of operators with the hash table, but there is no
* obvious usefulness to that at present.) * obvious usefulness to that at present.)
*/ */
foreach(opids, slink->operOids) foreach(l, slink->operOids)
{ {
Oid opid = lfirsto(opids); Oid opid = lfirsto(l);
HeapTuple tup; HeapTuple tup;
Form_pg_operator optup; Form_pg_operator optup;
@ -690,7 +692,7 @@ convert_IN_to_join(Query *parse, SubLink *sublink)
if (sublink->subLinkType != ANY_SUBLINK) if (sublink->subLinkType != ANY_SUBLINK)
return NULL; return NULL;
if (length(sublink->operName) != 1 || if (length(sublink->operName) != 1 ||
strcmp(strVal(lfirst(sublink->operName)), "=") != 0) strcmp(strVal(linitial(sublink->operName)), "=") != 0)
return NULL; return NULL;
/* /*
@ -860,7 +862,7 @@ process_sublinks_mutator(Node *node, bool *isTopQual)
if (and_clause(node)) if (and_clause(node))
{ {
List *newargs = NIL; List *newargs = NIL;
List *l; ListCell *l;
/* Still at qual top-level */ /* Still at qual top-level */
locTopQual = *isTopQual; locTopQual = *isTopQual;
@ -885,7 +887,7 @@ process_sublinks_mutator(Node *node, bool *isTopQual)
if (or_clause(node)) if (or_clause(node))
{ {
List *newargs = NIL; List *newargs = NIL;
List *l; ListCell *l;
foreach(l, ((BoolExpr *) node)->args) foreach(l, ((BoolExpr *) node)->args)
{ {
@ -918,7 +920,7 @@ SS_finalize_plan(Plan *plan, List *rtable)
Bitmapset *outer_params = NULL; Bitmapset *outer_params = NULL;
Bitmapset *valid_params = NULL; Bitmapset *valid_params = NULL;
int paramid; int paramid;
List *lst; ListCell *l;
/* /*
* First, scan the param list to discover the sets of params that are * First, scan the param list to discover the sets of params that are
@ -926,9 +928,9 @@ SS_finalize_plan(Plan *plan, List *rtable)
* this once to save time in the per-plan recursion steps. * this once to save time in the per-plan recursion steps.
*/ */
paramid = 0; paramid = 0;
foreach(lst, PlannerParamList) foreach(l, PlannerParamList)
{ {
PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lst); PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
if (pitem->abslevel < PlannerQueryLevel) if (pitem->abslevel < PlannerQueryLevel)
{ {
@ -966,7 +968,6 @@ finalize_plan(Plan *plan, List *rtable,
Bitmapset *outer_params, Bitmapset *valid_params) Bitmapset *outer_params, Bitmapset *valid_params)
{ {
finalize_primnode_context context; finalize_primnode_context context;
List *lst;
if (plan == NULL) if (plan == NULL)
return NULL; return NULL;
@ -1033,15 +1034,19 @@ finalize_plan(Plan *plan, List *rtable,
break; break;
case T_Append: case T_Append:
foreach(lst, ((Append *) plan)->appendplans) {
ListCell *l;
foreach(l, ((Append *) plan)->appendplans)
{ {
context.paramids = context.paramids =
bms_add_members(context.paramids, bms_add_members(context.paramids,
finalize_plan((Plan *) lfirst(lst), finalize_plan((Plan *) lfirst(l),
rtable, rtable,
outer_params, outer_params,
valid_params)); valid_params));
} }
}
break; break;
case T_NestLoop: case T_NestLoop:

View File

@ -16,7 +16,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.17 2004/05/10 22:44:45 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.18 2004/05/26 04:41:26 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -97,11 +97,11 @@ pull_up_IN_clauses(Query *parse, Node *node)
if (and_clause(node)) if (and_clause(node))
{ {
List *newclauses = NIL; List *newclauses = NIL;
List *oldclauses; ListCell *l;
foreach(oldclauses, ((BoolExpr *) node)->args) foreach(l, ((BoolExpr *) node)->args)
{ {
Node *oldclause = lfirst(oldclauses); Node *oldclause = (Node *) lfirst(l);
newclauses = lappend(newclauses, newclauses = lappend(newclauses,
pull_up_IN_clauses(parse, pull_up_IN_clauses(parse,
@ -162,7 +162,7 @@ pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join)
{ {
int rtoffset; int rtoffset;
List *subtlist; List *subtlist;
List *rt; ListCell *rt;
/* /*
* Need a modifiable copy of the subquery to hack on. Even if * Need a modifiable copy of the subquery to hack on. Even if
@ -314,7 +314,7 @@ pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join)
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
lfirst(l) = pull_up_subqueries(parse, lfirst(l), lfirst(l) = pull_up_subqueries(parse, lfirst(l),
@ -447,7 +447,7 @@ is_simple_subquery(Query *subquery)
static bool static bool
has_nullable_targetlist(Query *subquery) has_nullable_targetlist(Query *subquery)
{ {
List *l; ListCell *l;
foreach(l, subquery->targetList) foreach(l, subquery->targetList)
{ {
@ -488,7 +488,7 @@ resolvenew_in_jointree(Node *jtnode, int varno,
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
resolvenew_in_jointree(lfirst(l), varno, rte, subtlist); resolvenew_in_jointree(lfirst(l), varno, rte, subtlist);
@ -588,7 +588,7 @@ reduce_outer_joins_pass1(Node *jtnode)
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
{ {
@ -653,8 +653,8 @@ reduce_outer_joins_pass2(Node *jtnode,
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
List *s; ListCell *s;
Relids pass_nonnullable; Relids pass_nonnullable;
/* Scan quals to see if we can add any nonnullability constraints */ /* Scan quals to see if we can add any nonnullability constraints */
@ -662,15 +662,14 @@ reduce_outer_joins_pass2(Node *jtnode,
pass_nonnullable = bms_add_members(pass_nonnullable, pass_nonnullable = bms_add_members(pass_nonnullable,
nonnullable_rels); nonnullable_rels);
/* And recurse --- but only into interesting subtrees */ /* And recurse --- but only into interesting subtrees */
s = state->sub_states; Assert(length(f->fromlist) == length(state->sub_states));
foreach(l, f->fromlist) forboth(l, f->fromlist, s, state->sub_states)
{ {
reduce_outer_joins_state *sub_state = lfirst(s); reduce_outer_joins_state *sub_state = lfirst(s);
if (sub_state->contains_outer) if (sub_state->contains_outer)
reduce_outer_joins_pass2(lfirst(l), sub_state, parse, reduce_outer_joins_pass2(lfirst(l), sub_state, parse,
pass_nonnullable); pass_nonnullable);
s = lnext(s);
} }
bms_free(pass_nonnullable); bms_free(pass_nonnullable);
} }
@ -679,7 +678,7 @@ reduce_outer_joins_pass2(Node *jtnode,
JoinExpr *j = (JoinExpr *) jtnode; JoinExpr *j = (JoinExpr *) jtnode;
int rtindex = j->rtindex; int rtindex = j->rtindex;
JoinType jointype = j->jointype; JoinType jointype = j->jointype;
reduce_outer_joins_state *left_state = lfirst(state->sub_states); reduce_outer_joins_state *left_state = linitial(state->sub_states);
reduce_outer_joins_state *right_state = lsecond(state->sub_states); reduce_outer_joins_state *right_state = lsecond(state->sub_states);
/* Can we simplify this join? */ /* Can we simplify this join? */
@ -798,7 +797,7 @@ find_nonnullable_rels(Node *node, bool top_level)
} }
else if (IsA(node, List)) else if (IsA(node, List))
{ {
List *l; ListCell *l;
foreach(l, (List *) node) foreach(l, (List *) node)
{ {
@ -898,7 +897,7 @@ simplify_jointree(Query *parse, Node *jtnode)
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *newlist = NIL; List *newlist = NIL;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
{ {
@ -918,7 +917,16 @@ simplify_jointree(Query *parse, Node *jtnode)
*/ */
FromExpr *subf = (FromExpr *) child; FromExpr *subf = (FromExpr *) child;
int childlen = length(subf->fromlist); int childlen = length(subf->fromlist);
int myothers = length(newlist) + length(lnext(l)); int myothers;
ListCell *l2;
/*
* XXX: This is a quick hack, not sure of the proper
* fix.
*/
myothers = length(newlist);
for_each_cell(l2, lnext(l))
myothers++;
if (childlen <= 1 || if (childlen <= 1 ||
(childlen + myothers) <= from_collapse_limit) (childlen + myothers) <= from_collapse_limit)
@ -1022,7 +1030,7 @@ simplify_jointree(Query *parse, Node *jtnode)
static void static void
fix_in_clause_relids(List *in_info_list, int varno, Relids subrelids) fix_in_clause_relids(List *in_info_list, int varno, Relids subrelids)
{ {
List *l; ListCell *l;
foreach(l, in_info_list) foreach(l, in_info_list)
{ {
@ -1060,7 +1068,7 @@ get_relids_in_jointree(Node *jtnode)
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
{ {
@ -1119,7 +1127,7 @@ find_jointree_node_for_rel(Node *jtnode, int relid)
else if (IsA(jtnode, FromExpr)) else if (IsA(jtnode, FromExpr))
{ {
FromExpr *f = (FromExpr *) jtnode; FromExpr *f = (FromExpr *) jtnode;
List *l; ListCell *l;
foreach(l, f->fromlist) foreach(l, f->fromlist)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/prep/prepqual.c,v 1.41 2003/12/30 21:49:19 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/prep/prepqual.c,v 1.42 2004/05/26 04:41:26 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -144,7 +144,7 @@ flatten_andors_mutator(Node *node, void *context)
static void static void
flatten_andors_and_walker(FastList *out_list, List *andlist) flatten_andors_and_walker(FastList *out_list, List *andlist)
{ {
List *arg; ListCell *arg;
foreach(arg, andlist) foreach(arg, andlist)
{ {
@ -160,7 +160,7 @@ flatten_andors_and_walker(FastList *out_list, List *andlist)
static void static void
flatten_andors_or_walker(FastList *out_list, List *orlist) flatten_andors_or_walker(FastList *out_list, List *orlist)
{ {
List *arg; ListCell *arg;
foreach(arg, orlist) foreach(arg, orlist)
{ {
@ -193,7 +193,7 @@ pull_ands(List *andlist)
static void static void
pull_ands_walker(FastList *out_list, List *andlist) pull_ands_walker(FastList *out_list, List *andlist)
{ {
List *arg; ListCell *arg;
foreach(arg, andlist) foreach(arg, andlist)
{ {
@ -226,7 +226,7 @@ pull_ors(List *orlist)
static void static void
pull_ors_walker(FastList *out_list, List *orlist) pull_ors_walker(FastList *out_list, List *orlist)
{ {
List *arg; ListCell *arg;
foreach(arg, orlist) foreach(arg, orlist)
{ {
@ -258,7 +258,7 @@ find_nots(Expr *qual)
if (and_clause((Node *) qual)) if (and_clause((Node *) qual))
{ {
FastList t_list; FastList t_list;
List *temp; ListCell *temp;
FastListInit(&t_list); FastListInit(&t_list);
foreach(temp, ((BoolExpr *) qual)->args) foreach(temp, ((BoolExpr *) qual)->args)
@ -268,7 +268,7 @@ find_nots(Expr *qual)
else if (or_clause((Node *) qual)) else if (or_clause((Node *) qual))
{ {
FastList t_list; FastList t_list;
List *temp; ListCell *temp;
FastListInit(&t_list); FastListInit(&t_list);
foreach(temp, ((BoolExpr *) qual)->args) foreach(temp, ((BoolExpr *) qual)->args)
@ -324,7 +324,7 @@ push_nots(Expr *qual)
*-------------------- *--------------------
*/ */
FastList t_list; FastList t_list;
List *temp; ListCell *temp;
FastListInit(&t_list); FastListInit(&t_list);
foreach(temp, ((BoolExpr *) qual)->args) foreach(temp, ((BoolExpr *) qual)->args)
@ -334,7 +334,7 @@ push_nots(Expr *qual)
else if (or_clause((Node *) qual)) else if (or_clause((Node *) qual))
{ {
FastList t_list; FastList t_list;
List *temp; ListCell *temp;
FastListInit(&t_list); FastListInit(&t_list);
foreach(temp, ((BoolExpr *) qual)->args) foreach(temp, ((BoolExpr *) qual)->args)
@ -398,7 +398,7 @@ find_duplicate_ors(Expr *qual)
if (or_clause((Node *) qual)) if (or_clause((Node *) qual))
{ {
List *orlist = NIL; List *orlist = NIL;
List *temp; ListCell *temp;
/* Recurse */ /* Recurse */
foreach(temp, ((BoolExpr *) qual)->args) foreach(temp, ((BoolExpr *) qual)->args)
@ -412,7 +412,7 @@ find_duplicate_ors(Expr *qual)
else if (and_clause((Node *) qual)) else if (and_clause((Node *) qual))
{ {
List *andlist = NIL; List *andlist = NIL;
List *temp; ListCell *temp;
/* Recurse */ /* Recurse */
foreach(temp, ((BoolExpr *) qual)->args) foreach(temp, ((BoolExpr *) qual)->args)
@ -441,13 +441,12 @@ process_duplicate_ors(List *orlist)
int num_subclauses = 0; int num_subclauses = 0;
List *winners; List *winners;
List *neworlist; List *neworlist;
List *temp; ListCell *temp;
List *temp2;
if (orlist == NIL) if (orlist == NIL)
return NULL; /* probably can't happen */ return NULL; /* probably can't happen */
if (lnext(orlist) == NIL) if (length(orlist) == 1) /* single-expression OR (can this happen?) */
return lfirst(orlist); /* single-expression OR (can this happen?) */ return linitial(orlist);
/* /*
* Choose the shortest AND clause as the reference list --- obviously, * Choose the shortest AND clause as the reference list --- obviously,
@ -457,7 +456,7 @@ process_duplicate_ors(List *orlist)
*/ */
foreach(temp, orlist) foreach(temp, orlist)
{ {
Expr *clause = lfirst(temp); Expr *clause = (Expr *) lfirst(temp);
if (and_clause((Node *) clause)) if (and_clause((Node *) clause))
{ {
@ -489,12 +488,13 @@ process_duplicate_ors(List *orlist)
winners = NIL; winners = NIL;
foreach(temp, reference) foreach(temp, reference)
{ {
Expr *refclause = lfirst(temp); Expr *refclause = (Expr *) lfirst(temp);
bool win = true; bool win = true;
ListCell *temp2;
foreach(temp2, orlist) foreach(temp2, orlist)
{ {
Expr *clause = lfirst(temp2); Expr *clause = (Expr *) lfirst(temp2);
if (and_clause((Node *) clause)) if (and_clause((Node *) clause))
{ {
@ -537,7 +537,7 @@ process_duplicate_ors(List *orlist)
neworlist = NIL; neworlist = NIL;
foreach(temp, orlist) foreach(temp, orlist)
{ {
Expr *clause = lfirst(temp); Expr *clause = (Expr *) lfirst(temp);
if (and_clause((Node *) clause)) if (and_clause((Node *) clause))
{ {
@ -546,8 +546,8 @@ process_duplicate_ors(List *orlist)
subclauses = set_difference(subclauses, winners); subclauses = set_difference(subclauses, winners);
if (subclauses != NIL) if (subclauses != NIL)
{ {
if (lnext(subclauses) == NIL) if (length(subclauses) == 1)
neworlist = lappend(neworlist, lfirst(subclauses)); neworlist = lappend(neworlist, linitial(subclauses));
else else
neworlist = lappend(neworlist, make_andclause(subclauses)); neworlist = lappend(neworlist, make_andclause(subclauses));
} }
@ -577,8 +577,8 @@ process_duplicate_ors(List *orlist)
*/ */
if (neworlist != NIL) if (neworlist != NIL)
{ {
if (lnext(neworlist) == NIL) if (length(neworlist) == 1)
winners = lappend(winners, lfirst(neworlist)); winners = lappend(winners, linitial(neworlist));
else else
winners = lappend(winners, make_orclause(pull_ors(neworlist))); winners = lappend(winners, make_orclause(pull_ors(neworlist)));
} }
@ -587,8 +587,8 @@ process_duplicate_ors(List *orlist)
* And return the constructed AND clause, again being wary of a single * And return the constructed AND clause, again being wary of a single
* element and AND/OR flatness. * element and AND/OR flatness.
*/ */
if (lnext(winners) == NIL) if (length(winners) == 1)
return (Expr *) lfirst(winners); return (Expr *) linitial(winners);
else else
return make_andclause(pull_ands(winners)); return make_andclause(pull_ands(winners));
} }

View File

@ -15,7 +15,7 @@
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/prep/preptlist.c,v 1.66 2003/11/29 19:51:51 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/prep/preptlist.c,v 1.67 2004/05/26 04:41:26 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -122,10 +122,13 @@ expand_targetlist(List *tlist, int command_type,
Index result_relation, List *range_table) Index result_relation, List *range_table)
{ {
List *new_tlist = NIL; List *new_tlist = NIL;
ListCell *tlist_item;
Relation rel; Relation rel;
int attrno, int attrno,
numattrs; numattrs;
tlist_item = list_head(tlist);
/* /*
* The rewriter should have already ensured that the TLEs are in * The rewriter should have already ensured that the TLEs are in
* correct order; but we have to insert TLEs for any missing * correct order; but we have to insert TLEs for any missing
@ -143,15 +146,15 @@ expand_targetlist(List *tlist, int command_type,
Form_pg_attribute att_tup = rel->rd_att->attrs[attrno - 1]; Form_pg_attribute att_tup = rel->rd_att->attrs[attrno - 1];
TargetEntry *new_tle = NULL; TargetEntry *new_tle = NULL;
if (tlist != NIL) if (tlist_item != NULL)
{ {
TargetEntry *old_tle = (TargetEntry *) lfirst(tlist); TargetEntry *old_tle = (TargetEntry *) lfirst(tlist_item);
Resdom *resdom = old_tle->resdom; Resdom *resdom = old_tle->resdom;
if (!resdom->resjunk && resdom->resno == attrno) if (!resdom->resjunk && resdom->resno == attrno)
{ {
new_tle = old_tle; new_tle = old_tle;
tlist = lnext(tlist); tlist_item = lnext(tlist_item);
} }
} }
@ -259,9 +262,9 @@ expand_targetlist(List *tlist, int command_type,
* an UPDATE in a table with dropped columns, or an inheritance child * an UPDATE in a table with dropped columns, or an inheritance child
* table with extra columns.) * table with extra columns.)
*/ */
while (tlist) while (tlist_item)
{ {
TargetEntry *old_tle = (TargetEntry *) lfirst(tlist); TargetEntry *old_tle = (TargetEntry *) lfirst(tlist_item);
Resdom *resdom = old_tle->resdom; Resdom *resdom = old_tle->resdom;
if (!resdom->resjunk) if (!resdom->resjunk)
@ -275,7 +278,7 @@ expand_targetlist(List *tlist, int command_type,
} }
new_tlist = lappend(new_tlist, old_tle); new_tlist = lappend(new_tlist, old_tle);
attrno++; attrno++;
tlist = lnext(tlist); tlist_item = lnext(tlist_item);
} }
heap_close(rel, AccessShareLock); heap_close(rel, AccessShareLock);

View File

@ -14,7 +14,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/prep/prepunion.c,v 1.110 2004/05/11 22:43:55 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/prep/prepunion.c,v 1.111 2004/05/26 04:41:26 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -420,15 +420,19 @@ generate_setop_tlist(List *colTypes, int flag,
{ {
List *tlist = NIL; List *tlist = NIL;
int resno = 1; int resno = 1;
List *i; ListCell *i,
*j,
*k;
Resdom *resdom; Resdom *resdom;
Node *expr; Node *expr;
j = list_head(input_tlist);
k = list_head(refnames_tlist);
foreach(i, colTypes) foreach(i, colTypes)
{ {
Oid colType = lfirsto(i); Oid colType = lfirsto(i);
TargetEntry *inputtle = (TargetEntry *) lfirst(input_tlist); TargetEntry *inputtle = (TargetEntry *) lfirst(j);
TargetEntry *reftle = (TargetEntry *) lfirst(refnames_tlist); TargetEntry *reftle = (TargetEntry *) lfirst(k);
int32 colTypmod; int32 colTypmod;
Assert(inputtle->resdom->resno == resno); Assert(inputtle->resdom->resno == resno);
@ -476,8 +480,8 @@ generate_setop_tlist(List *colTypes, int flag,
pstrdup(reftle->resdom->resname), pstrdup(reftle->resdom->resname),
false); false);
tlist = lappend(tlist, makeTargetEntry(resdom, (Expr *) expr)); tlist = lappend(tlist, makeTargetEntry(resdom, (Expr *) expr));
input_tlist = lnext(input_tlist); j = lnext(j);
refnames_tlist = lnext(refnames_tlist); k = lnext(k);
} }
if (flag >= 0) if (flag >= 0)
@ -518,11 +522,12 @@ generate_append_tlist(List *colTypes, bool flag,
{ {
List *tlist = NIL; List *tlist = NIL;
int resno = 1; int resno = 1;
List *curColType; ListCell *curColType;
ListCell *ref_tl_item;
int colindex; int colindex;
Resdom *resdom; Resdom *resdom;
Node *expr; Node *expr;
List *planl; ListCell *planl;
int32 *colTypmods; int32 *colTypmods;
/* /*
@ -536,9 +541,9 @@ generate_append_tlist(List *colTypes, bool flag,
foreach(planl, input_plans) foreach(planl, input_plans)
{ {
Plan *subplan = (Plan *) lfirst(planl); Plan *subplan = (Plan *) lfirst(planl);
List *subtlist; ListCell *subtlist;
curColType = colTypes; curColType = list_head(colTypes);
colindex = 0; colindex = 0;
foreach(subtlist, subplan->targetlist) foreach(subtlist, subplan->targetlist)
{ {
@ -546,11 +551,11 @@ generate_append_tlist(List *colTypes, bool flag,
if (subtle->resdom->resjunk) if (subtle->resdom->resjunk)
continue; continue;
Assert(curColType != NIL); Assert(curColType != NULL);
if (subtle->resdom->restype == lfirsto(curColType)) if (subtle->resdom->restype == lfirst_oid(curColType))
{ {
/* If first subplan, copy the typmod; else compare */ /* If first subplan, copy the typmod; else compare */
if (planl == input_plans) if (planl == list_head(input_plans))
colTypmods[colindex] = subtle->resdom->restypmod; colTypmods[colindex] = subtle->resdom->restypmod;
else if (subtle->resdom->restypmod != colTypmods[colindex]) else if (subtle->resdom->restypmod != colTypmods[colindex])
colTypmods[colindex] = -1; colTypmods[colindex] = -1;
@ -563,18 +568,18 @@ generate_append_tlist(List *colTypes, bool flag,
curColType = lnext(curColType); curColType = lnext(curColType);
colindex++; colindex++;
} }
Assert(curColType == NIL); Assert(curColType == NULL);
} }
/* /*
* Now we can build the tlist for the Append. * Now we can build the tlist for the Append.
*/ */
colindex = 0; colindex = 0;
foreach(curColType, colTypes) forboth(curColType, colTypes, ref_tl_item, refnames_tlist)
{ {
Oid colType = lfirsto(curColType); Oid colType = lfirsto(curColType);
int32 colTypmod = colTypmods[colindex++]; int32 colTypmod = colTypmods[colindex++];
TargetEntry *reftle = (TargetEntry *) lfirst(refnames_tlist); TargetEntry *reftle = (TargetEntry *) lfirst(ref_tl_item);
Assert(reftle->resdom->resno == resno); Assert(reftle->resdom->resno == resno);
Assert(!reftle->resdom->resjunk); Assert(!reftle->resdom->resjunk);
@ -589,7 +594,6 @@ generate_append_tlist(List *colTypes, bool flag,
pstrdup(reftle->resdom->resname), pstrdup(reftle->resdom->resname),
false); false);
tlist = lappend(tlist, makeTargetEntry(resdom, (Expr *) expr)); tlist = lappend(tlist, makeTargetEntry(resdom, (Expr *) expr));
refnames_tlist = lnext(refnames_tlist);
} }
if (flag) if (flag)
@ -623,11 +627,12 @@ generate_append_tlist(List *colTypes, bool flag,
static bool static bool
tlist_same_datatypes(List *tlist, List *colTypes, bool junkOK) tlist_same_datatypes(List *tlist, List *colTypes, bool junkOK)
{ {
List *i; ListCell *l;
ListCell *curColType = list_head(colTypes);
foreach(i, tlist) foreach(l, tlist)
{ {
TargetEntry *tle = (TargetEntry *) lfirst(i); TargetEntry *tle = (TargetEntry *) lfirst(l);
if (tle->resdom->resjunk) if (tle->resdom->resjunk)
{ {
@ -636,14 +641,14 @@ tlist_same_datatypes(List *tlist, List *colTypes, bool junkOK)
} }
else else
{ {
if (colTypes == NIL) if (curColType == NULL)
return false; return false;
if (tle->resdom->restype != lfirsto(colTypes)) if (tle->resdom->restype != lfirst_oid(curColType))
return false; return false;
colTypes = lnext(colTypes); curColType = lnext(curColType);
} }
} }
if (colTypes != NIL) if (curColType != NULL)
return false; return false;
return true; return true;
} }
@ -667,10 +672,10 @@ find_all_inheritors(Oid parentrel)
*/ */
while (unexamined_relids != NIL) while (unexamined_relids != NIL)
{ {
Oid currentrel = lfirsto(unexamined_relids); Oid currentrel = linitial_oid(unexamined_relids);
List *currentchildren; List *currentchildren;
unexamined_relids = lnext(unexamined_relids); unexamined_relids = list_delete_first(unexamined_relids);
examined_relids = lappendo(examined_relids, currentrel); examined_relids = lappendo(examined_relids, currentrel);
currentchildren = find_inheritance_children(currentrel); currentchildren = find_inheritance_children(currentrel);
@ -719,7 +724,7 @@ expand_inherited_rtentry(Query *parse, Index rti, bool dup_parent)
Oid parentOID; Oid parentOID;
List *inhOIDs; List *inhOIDs;
List *inhRTIs; List *inhRTIs;
List *l; ListCell *l;
/* Does RT entry allow inheritance? */ /* Does RT entry allow inheritance? */
if (!rte->inh) if (!rte->inh)
@ -739,7 +744,7 @@ expand_inherited_rtentry(Query *parse, Index rti, bool dup_parent)
* case. This could happen despite above has_subclass() check, if * case. This could happen despite above has_subclass() check, if
* table once had a child but no longer does. * table once had a child but no longer does.
*/ */
if (lnext(inhOIDs) == NIL) if (length(inhOIDs) < 2)
return NIL; return NIL;
/* OK, it's an inheritance set; expand it */ /* OK, it's an inheritance set; expand it */
if (dup_parent) if (dup_parent)
@ -1020,7 +1025,7 @@ static List *
adjust_inherited_tlist(List *tlist, Oid old_relid, Oid new_relid) adjust_inherited_tlist(List *tlist, Oid old_relid, Oid new_relid)
{ {
bool changed_it = false; bool changed_it = false;
List *tl; ListCell *tl;
List *new_tlist; List *new_tlist;
bool more; bool more;
int attrno; int attrno;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.170 2004/05/10 22:44:45 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.171 2004/05/26 04:41:27 neilc Exp $
* *
* HISTORY * HISTORY
* AUTHOR DATE MAJOR EVENT * AUTHOR DATE MAJOR EVENT
@ -114,7 +114,7 @@ get_leftop(Expr *clause)
OpExpr *expr = (OpExpr *) clause; OpExpr *expr = (OpExpr *) clause;
if (expr->args != NIL) if (expr->args != NIL)
return lfirst(expr->args); return linitial(expr->args);
else else
return NULL; return NULL;
} }
@ -130,8 +130,8 @@ get_rightop(Expr *clause)
{ {
OpExpr *expr = (OpExpr *) clause; OpExpr *expr = (OpExpr *) clause;
if (expr->args != NIL && lnext(expr->args) != NIL) if (list_length(expr->args) >= 2)
return lfirst(lnext(expr->args)); return lsecond(expr->args);
else else
return NULL; return NULL;
} }
@ -176,7 +176,7 @@ make_notclause(Expr *notclause)
Expr * Expr *
get_notclausearg(Expr *notclause) get_notclausearg(Expr *notclause)
{ {
return lfirst(((BoolExpr *) notclause)->args); return linitial(((BoolExpr *) notclause)->args);
} }
/***************************************************************************** /*****************************************************************************
@ -278,8 +278,8 @@ make_ands_explicit(List *andclauses)
{ {
if (andclauses == NIL) if (andclauses == NIL)
return (Expr *) makeBoolConst(true, false); return (Expr *) makeBoolConst(true, false);
else if (lnext(andclauses) == NIL) else if (length(andclauses) == 1)
return (Expr *) lfirst(andclauses); return (Expr *) linitial(andclauses);
else else
return make_andclause(andclauses); return make_andclause(andclauses);
} }
@ -595,7 +595,7 @@ contain_mutable_functions_walker(Node *node, void *context)
if (IsA(node, SubLink)) if (IsA(node, SubLink))
{ {
SubLink *sublink = (SubLink *) node; SubLink *sublink = (SubLink *) node;
List *opid; ListCell *opid;
foreach(opid, sublink->operOids) foreach(opid, sublink->operOids)
{ {
@ -678,7 +678,7 @@ contain_volatile_functions_walker(Node *node, void *context)
if (IsA(node, SubLink)) if (IsA(node, SubLink))
{ {
SubLink *sublink = (SubLink *) node; SubLink *sublink = (SubLink *) node;
List *opid; ListCell *opid;
foreach(opid, sublink->operOids) foreach(opid, sublink->operOids)
{ {
@ -848,7 +848,7 @@ pull_constant_clauses(List *quals, List **constantQual)
{ {
FastList constqual, FastList constqual,
restqual; restqual;
List *q; ListCell *q;
FastListInit(&constqual); FastListInit(&constqual);
FastListInit(&restqual); FastListInit(&restqual);
@ -882,7 +882,7 @@ pull_constant_clauses(List *quals, List **constantQual)
bool bool
has_distinct_on_clause(Query *query) has_distinct_on_clause(Query *query)
{ {
List *targetList; ListCell *l;
/* Is there a DISTINCT clause at all? */ /* Is there a DISTINCT clause at all? */
if (query->distinctClause == NIL) if (query->distinctClause == NIL)
@ -901,9 +901,9 @@ has_distinct_on_clause(Query *query)
* This code assumes that the DISTINCT list is valid, ie, all its entries * This code assumes that the DISTINCT list is valid, ie, all its entries
* match some entry of the tlist. * match some entry of the tlist.
*/ */
foreach(targetList, query->targetList) foreach(l, query->targetList)
{ {
TargetEntry *tle = (TargetEntry *) lfirst(targetList); TargetEntry *tle = (TargetEntry *) lfirst(l);
if (tle->resdom->ressortgroupref == 0) if (tle->resdom->ressortgroupref == 0)
{ {
@ -998,8 +998,8 @@ CommuteClause(OpExpr *clause)
clause->opfuncid = InvalidOid; clause->opfuncid = InvalidOid;
/* opresulttype and opretset are assumed not to change */ /* opresulttype and opretset are assumed not to change */
temp = lfirst(clause->args); temp = linitial(clause->args);
lfirst(clause->args) = lsecond(clause->args); linitial(clause->args) = lsecond(clause->args);
lsecond(clause->args) = temp; lsecond(clause->args) = temp;
} }
@ -1162,7 +1162,7 @@ eval_const_expressions_mutator(Node *node, List *active_fns)
{ {
DistinctExpr *expr = (DistinctExpr *) node; DistinctExpr *expr = (DistinctExpr *) node;
List *args; List *args;
List *arg; ListCell *arg;
bool has_null_input = false; bool has_null_input = false;
bool all_null_input = true; bool all_null_input = true;
bool has_nonconst_input = false; bool has_nonconst_input = false;
@ -1281,8 +1281,8 @@ eval_const_expressions_mutator(Node *node, List *active_fns)
if (newargs == NIL) if (newargs == NIL)
return makeBoolConst(false, false); return makeBoolConst(false, false);
/* If only one nonconst-or-NULL input, it's the result */ /* If only one nonconst-or-NULL input, it's the result */
if (lnext(newargs) == NIL) if (length(newargs) == 1)
return (Node *) lfirst(newargs); return (Node *) linitial(newargs);
/* Else we still need an OR node */ /* Else we still need an OR node */
return (Node *) make_orclause(newargs); return (Node *) make_orclause(newargs);
} }
@ -1302,16 +1302,16 @@ eval_const_expressions_mutator(Node *node, List *active_fns)
if (newargs == NIL) if (newargs == NIL)
return makeBoolConst(true, false); return makeBoolConst(true, false);
/* If only one nonconst-or-NULL input, it's the result */ /* If only one nonconst-or-NULL input, it's the result */
if (lnext(newargs) == NIL) if (length(newargs) == 1)
return (Node *) lfirst(newargs); return (Node *) linitial(newargs);
/* Else we still need an AND node */ /* Else we still need an AND node */
return (Node *) make_andclause(newargs); return (Node *) make_andclause(newargs);
} }
case NOT_EXPR: case NOT_EXPR:
Assert(length(args) == 1); Assert(length(args) == 1);
if (IsA(lfirst(args), Const)) if (IsA(linitial(args), Const))
{ {
Const *const_input = (Const *) lfirst(args); Const *const_input = (Const *) linitial(args);
/* NOT NULL => NULL */ /* NOT NULL => NULL */
if (const_input->constisnull) if (const_input->constisnull)
@ -1320,13 +1320,13 @@ eval_const_expressions_mutator(Node *node, List *active_fns)
return makeBoolConst(!DatumGetBool(const_input->constvalue), return makeBoolConst(!DatumGetBool(const_input->constvalue),
false); false);
} }
else if (not_clause((Node *) lfirst(args))) else if (not_clause((Node *) linitial(args)))
{ {
/* Cancel NOT/NOT */ /* Cancel NOT/NOT */
return (Node *) get_notclausearg((Expr *) lfirst(args)); return (Node *) get_notclausearg((Expr *) linitial(args));
} }
/* Else we still need a NOT node */ /* Else we still need a NOT node */
return (Node *) make_notclause((Expr *) lfirst(args)); return (Node *) make_notclause((Expr *) linitial(args));
default: default:
elog(ERROR, "unrecognized boolop: %d", elog(ERROR, "unrecognized boolop: %d",
(int) expr->boolop); (int) expr->boolop);
@ -1414,7 +1414,7 @@ eval_const_expressions_mutator(Node *node, List *active_fns)
FastList newargs; FastList newargs;
Node *defresult; Node *defresult;
Const *const_input; Const *const_input;
List *arg; ListCell *arg;
/* Simplify the test expression, if any */ /* Simplify the test expression, if any */
newarg = eval_const_expressions_mutator((Node *) caseexpr->arg, newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
@ -1480,7 +1480,7 @@ eval_const_expressions_mutator(Node *node, List *active_fns)
ArrayExpr *newarray; ArrayExpr *newarray;
bool all_const = true; bool all_const = true;
FastList newelems; FastList newelems;
List *element; ListCell *element;
FastListInit(&newelems); FastListInit(&newelems);
foreach(element, arrayexpr->elements) foreach(element, arrayexpr->elements)
@ -1511,7 +1511,7 @@ eval_const_expressions_mutator(Node *node, List *active_fns)
CoalesceExpr *coalesceexpr = (CoalesceExpr *) node; CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
CoalesceExpr *newcoalesce; CoalesceExpr *newcoalesce;
FastList newargs; FastList newargs;
List *arg; ListCell *arg;
FastListInit(&newargs); FastListInit(&newargs);
foreach(arg, coalesceexpr->args) foreach(arg, coalesceexpr->args)
@ -1614,7 +1614,7 @@ static List *
simplify_or_arguments(List *args, bool *haveNull, bool *forceTrue) simplify_or_arguments(List *args, bool *haveNull, bool *forceTrue)
{ {
List *newargs = NIL; List *newargs = NIL;
List *larg; ListCell *larg;
foreach(larg, args) foreach(larg, args)
{ {
@ -1675,7 +1675,7 @@ static List *
simplify_and_arguments(List *args, bool *haveNull, bool *forceFalse) simplify_and_arguments(List *args, bool *haveNull, bool *forceFalse)
{ {
List *newargs = NIL; List *newargs = NIL;
List *larg; ListCell *larg;
foreach(larg, args) foreach(larg, args)
{ {
@ -1774,7 +1774,7 @@ evaluate_function(Oid funcid, Oid result_type, List *args,
Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple); Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
bool has_nonconst_input = false; bool has_nonconst_input = false;
bool has_null_input = false; bool has_null_input = false;
List *arg; ListCell *arg;
FuncExpr *newexpr; FuncExpr *newexpr;
/* /*
@ -1870,7 +1870,7 @@ inline_function(Oid funcid, Oid result_type, List *args,
Query *querytree; Query *querytree;
Node *newexpr; Node *newexpr;
int *usecounts; int *usecounts;
List *arg; ListCell *arg;
int i; int i;
/* /*
@ -1946,13 +1946,13 @@ inline_function(Oid funcid, Oid result_type, List *args,
if (length(raw_parsetree_list) != 1) if (length(raw_parsetree_list) != 1)
goto fail; goto fail;
querytree_list = parse_analyze(lfirst(raw_parsetree_list), querytree_list = parse_analyze(linitial(raw_parsetree_list),
argtypes, funcform->pronargs); argtypes, funcform->pronargs);
if (length(querytree_list) != 1) if (length(querytree_list) != 1)
goto fail; goto fail;
querytree = (Query *) lfirst(querytree_list); querytree = (Query *) linitial(querytree_list);
/* /*
* The single command must be a simple "SELECT expression". * The single command must be a simple "SELECT expression".
@ -1976,7 +1976,7 @@ inline_function(Oid funcid, Oid result_type, List *args,
length(querytree->targetList) != 1) length(querytree->targetList) != 1)
goto fail; goto fail;
newexpr = (Node *) ((TargetEntry *) lfirst(querytree->targetList))->expr; newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
/* /*
* If the function has any arguments declared as polymorphic types, * If the function has any arguments declared as polymorphic types,
@ -2330,7 +2330,7 @@ expression_tree_walker(Node *node,
bool (*walker) (), bool (*walker) (),
void *context) void *context)
{ {
List *temp; ListCell *temp;
/* /*
* The walker has already visited the current node, and so we need * The walker has already visited the current node, and so we need
@ -2576,7 +2576,7 @@ query_tree_walker(Query *query,
void *context, void *context,
int flags) int flags)
{ {
List *rt; ListCell *rt;
Assert(query != NULL && IsA(query, Query)); Assert(query != NULL && IsA(query, Query));
@ -2972,7 +2972,7 @@ expression_tree_mutator(Node *node,
* elements! * elements!
*/ */
FastList resultlist; FastList resultlist;
List *temp; ListCell *temp;
FastListInit(&resultlist); FastListInit(&resultlist);
foreach(temp, (List *) node) foreach(temp, (List *) node)
@ -3064,7 +3064,7 @@ query_tree_mutator(Query *query,
int flags) int flags)
{ {
FastList newrt; FastList newrt;
List *rt; ListCell *rt;
Assert(query != NULL && IsA(query, Query)); Assert(query != NULL && IsA(query, Query));

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/joininfo.c,v 1.37 2003/11/29 19:51:51 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/joininfo.c,v 1.38 2004/05/26 04:41:27 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -29,11 +29,11 @@
JoinInfo * JoinInfo *
find_joininfo_node(RelOptInfo *this_rel, Relids join_relids) find_joininfo_node(RelOptInfo *this_rel, Relids join_relids)
{ {
List *i; ListCell *l;
foreach(i, this_rel->joininfo) foreach(l, this_rel->joininfo)
{ {
JoinInfo *joininfo = (JoinInfo *) lfirst(i); JoinInfo *joininfo = (JoinInfo *) lfirst(l);
if (bms_equal(join_relids, joininfo->unjoined_relids)) if (bms_equal(join_relids, joininfo->unjoined_relids))
return joininfo; return joininfo;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/pathnode.c,v 1.104 2004/04/25 18:23:56 neilc Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/pathnode.c,v 1.105 2004/05/26 04:41:27 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -200,7 +200,7 @@ void
set_cheapest(RelOptInfo *parent_rel) set_cheapest(RelOptInfo *parent_rel)
{ {
List *pathlist = parent_rel->pathlist; List *pathlist = parent_rel->pathlist;
List *p; ListCell *p;
Path *cheapest_startup_path; Path *cheapest_startup_path;
Path *cheapest_total_path; Path *cheapest_total_path;
@ -209,9 +209,9 @@ set_cheapest(RelOptInfo *parent_rel)
if (pathlist == NIL) if (pathlist == NIL)
elog(ERROR, "could not devise a query plan for the given query"); elog(ERROR, "could not devise a query plan for the given query");
cheapest_startup_path = cheapest_total_path = (Path *) lfirst(pathlist); cheapest_startup_path = cheapest_total_path = (Path *) linitial(pathlist);
foreach(p, lnext(pathlist)) for_each_cell(p, lnext(list_head(pathlist)))
{ {
Path *path = (Path *) lfirst(p); Path *path = (Path *) lfirst(p);
int cmp; int cmp;
@ -269,17 +269,17 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
{ {
bool accept_new = true; /* unless we find a superior old bool accept_new = true; /* unless we find a superior old
* path */ * path */
List *insert_after = NIL; /* where to insert new item */ ListCell *insert_after = NULL; /* where to insert new item */
List *p1_prev = NIL; ListCell *p1_prev = NULL;
List *p1; ListCell *p1;
/* /*
* Loop to check proposed new path against old paths. Note it is * Loop to check proposed new path against old paths. Note it is
* possible for more than one old path to be tossed out because * possible for more than one old path to be tossed out because
* new_path dominates it. * new_path dominates it.
*/ */
p1 = parent_rel->pathlist; /* cannot use foreach here */ p1 = list_head(parent_rel->pathlist); /* cannot use foreach here */
while (p1 != NIL) while (p1 != NULL)
{ {
Path *old_path = (Path *) lfirst(p1); Path *old_path = (Path *) lfirst(p1);
bool remove_old = false; /* unless new proves superior */ bool remove_old = false; /* unless new proves superior */
@ -346,15 +346,14 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
*/ */
if (remove_old) if (remove_old)
{ {
List *p1_next = lnext(p1); parent_rel->pathlist = list_delete_cell(parent_rel->pathlist,
p1, p1_prev);
if (p1_prev) /* Delete the data pointed-to by the deleted cell */
lnext(p1_prev) = p1_next;
else
parent_rel->pathlist = p1_next;
pfree(old_path); pfree(old_path);
pfree(p1); /* this is why we can't use foreach */ if (p1_prev)
p1 = p1_next; p1 = lnext(p1_prev);
else
p1 = list_head(parent_rel->pathlist);
} }
else else
{ {
@ -378,7 +377,7 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
{ {
/* Accept the new path: insert it at proper place in pathlist */ /* Accept the new path: insert it at proper place in pathlist */
if (insert_after) if (insert_after)
lnext(insert_after) = lcons(new_path, lnext(insert_after)); lappend_cell(parent_rel->pathlist, insert_after, new_path);
else else
parent_rel->pathlist = lcons(new_path, parent_rel->pathlist); parent_rel->pathlist = lcons(new_path, parent_rel->pathlist);
} }
@ -508,7 +507,7 @@ AppendPath *
create_append_path(RelOptInfo *rel, List *subpaths) create_append_path(RelOptInfo *rel, List *subpaths)
{ {
AppendPath *pathnode = makeNode(AppendPath); AppendPath *pathnode = makeNode(AppendPath);
List *l; ListCell *l;
pathnode->path.pathtype = T_Append; pathnode->path.pathtype = T_Append;
pathnode->path.parent = rel; pathnode->path.parent = rel;
@ -522,7 +521,7 @@ create_append_path(RelOptInfo *rel, List *subpaths)
{ {
Path *subpath = (Path *) lfirst(l); Path *subpath = (Path *) lfirst(l);
if (l == subpaths) /* first node? */ if (l == list_head(subpaths)) /* first node? */
pathnode->path.startup_cost = subpath->startup_cost; pathnode->path.startup_cost = subpath->startup_cost;
pathnode->path.total_cost += subpath->total_cost; pathnode->path.total_cost += subpath->total_cost;
} }
@ -608,7 +607,7 @@ create_unique_path(Query *root, RelOptInfo *rel, Path *subpath)
Path agg_path; /* dummy for result of cost_agg */ Path agg_path; /* dummy for result of cost_agg */
MemoryContext oldcontext; MemoryContext oldcontext;
List *sub_targetlist; List *sub_targetlist;
List *l; ListCell *l;
int numCols; int numCols;
/* Caller made a mistake if subpath isn't cheapest_total */ /* Caller made a mistake if subpath isn't cheapest_total */
@ -783,7 +782,7 @@ is_distinct_query(Query *query)
*/ */
if (query->groupClause) if (query->groupClause)
{ {
List *gl; ListCell *gl;
foreach(gl, query->groupClause) foreach(gl, query->groupClause)
{ {
@ -818,7 +817,7 @@ is_distinct_query(Query *query)
static bool static bool
hash_safe_tlist(List *tlist) hash_safe_tlist(List *tlist)
{ {
List *tl; ListCell *tl;
foreach(tl, tlist) foreach(tl, tlist)
{ {

View File

@ -9,7 +9,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/plancat.c,v 1.91 2004/01/04 00:07:32 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/plancat.c,v 1.92 2004/05/26 04:41:27 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -75,14 +75,14 @@ get_relation_info(Oid relationObjectId, RelOptInfo *rel)
if (hasindex) if (hasindex)
{ {
List *indexoidlist, List *indexoidlist;
*indexoidscan; ListCell *l;
indexoidlist = RelationGetIndexList(relation); indexoidlist = RelationGetIndexList(relation);
foreach(indexoidscan, indexoidlist) foreach(l, indexoidlist)
{ {
Oid indexoid = lfirsto(indexoidscan); Oid indexoid = lfirsto(l);
Relation indexRelation; Relation indexRelation;
Form_pg_index index; Form_pg_index index;
IndexOptInfo *info; IndexOptInfo *info;
@ -384,7 +384,7 @@ has_subclass(Oid relationId)
bool bool
has_unique_index(RelOptInfo *rel, AttrNumber attno) has_unique_index(RelOptInfo *rel, AttrNumber attno)
{ {
List *ilist; ListCell *ilist;
foreach(ilist, rel->indexlist) foreach(ilist, rel->indexlist)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/relnode.c,v 1.56 2004/04/25 18:23:56 neilc Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/relnode.c,v 1.57 2004/05/26 04:41:27 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -47,21 +47,21 @@ static void subbuild_joinrel_joinlist(RelOptInfo *joinrel,
void void
build_base_rel(Query *root, int relid) build_base_rel(Query *root, int relid)
{ {
List *rels; ListCell *l;
RelOptInfo *rel; RelOptInfo *rel;
/* Rel should not exist already */ /* Rel should not exist already */
foreach(rels, root->base_rel_list) foreach(l, root->base_rel_list)
{ {
rel = (RelOptInfo *) lfirst(rels); rel = (RelOptInfo *) lfirst(l);
if (relid == rel->relid) if (relid == rel->relid)
elog(ERROR, "rel already exists"); elog(ERROR, "rel already exists");
} }
/* It should not exist as an "other" rel, either */ /* It should not exist as an "other" rel, either */
foreach(rels, root->other_rel_list) foreach(l, root->other_rel_list)
{ {
rel = (RelOptInfo *) lfirst(rels); rel = (RelOptInfo *) lfirst(l);
if (relid == rel->relid) if (relid == rel->relid)
elog(ERROR, "rel already exists as \"other\" rel"); elog(ERROR, "rel already exists as \"other\" rel");
} }
@ -82,21 +82,21 @@ build_base_rel(Query *root, int relid)
RelOptInfo * RelOptInfo *
build_other_rel(Query *root, int relid) build_other_rel(Query *root, int relid)
{ {
List *rels; ListCell *l;
RelOptInfo *rel; RelOptInfo *rel;
/* Already made? */ /* Already made? */
foreach(rels, root->other_rel_list) foreach(l, root->other_rel_list)
{ {
rel = (RelOptInfo *) lfirst(rels); rel = (RelOptInfo *) lfirst(l);
if (relid == rel->relid) if (relid == rel->relid)
return rel; return rel;
} }
/* It should not exist as a base rel */ /* It should not exist as a base rel */
foreach(rels, root->base_rel_list) foreach(l, root->base_rel_list)
{ {
rel = (RelOptInfo *) lfirst(rels); rel = (RelOptInfo *) lfirst(l);
if (relid == rel->relid) if (relid == rel->relid)
elog(ERROR, "rel already exists as base rel"); elog(ERROR, "rel already exists as base rel");
} }
@ -187,19 +187,19 @@ make_base_rel(Query *root, int relid)
RelOptInfo * RelOptInfo *
find_base_rel(Query *root, int relid) find_base_rel(Query *root, int relid)
{ {
List *rels; ListCell *l;
RelOptInfo *rel; RelOptInfo *rel;
foreach(rels, root->base_rel_list) foreach(l, root->base_rel_list)
{ {
rel = (RelOptInfo *) lfirst(rels); rel = (RelOptInfo *) lfirst(l);
if (relid == rel->relid) if (relid == rel->relid)
return rel; return rel;
} }
foreach(rels, root->other_rel_list) foreach(l, root->other_rel_list)
{ {
rel = (RelOptInfo *) lfirst(rels); rel = (RelOptInfo *) lfirst(l);
if (relid == rel->relid) if (relid == rel->relid)
return rel; return rel;
} }
@ -217,11 +217,11 @@ find_base_rel(Query *root, int relid)
RelOptInfo * RelOptInfo *
find_join_rel(Query *root, Relids relids) find_join_rel(Query *root, Relids relids)
{ {
List *joinrels; ListCell *l;
foreach(joinrels, root->join_rel_list) foreach(l, root->join_rel_list)
{ {
RelOptInfo *rel = (RelOptInfo *) lfirst(joinrels); RelOptInfo *rel = (RelOptInfo *) lfirst(l);
if (bms_equal(rel->relids, relids)) if (bms_equal(rel->relids, relids))
return rel; return rel;
@ -363,8 +363,7 @@ static void
build_joinrel_tlist(Query *root, RelOptInfo *joinrel) build_joinrel_tlist(Query *root, RelOptInfo *joinrel)
{ {
Relids relids = joinrel->relids; Relids relids = joinrel->relids;
List *rels; ListCell *rels;
List *vars;
FastListInit(&joinrel->reltargetlist); FastListInit(&joinrel->reltargetlist);
joinrel->width = 0; joinrel->width = 0;
@ -372,6 +371,7 @@ build_joinrel_tlist(Query *root, RelOptInfo *joinrel)
foreach(rels, root->base_rel_list) foreach(rels, root->base_rel_list)
{ {
RelOptInfo *baserel = (RelOptInfo *) lfirst(rels); RelOptInfo *baserel = (RelOptInfo *) lfirst(rels);
ListCell *vars;
if (!bms_is_member(baserel->relid, relids)) if (!bms_is_member(baserel->relid, relids))
continue; continue;
@ -481,7 +481,7 @@ subbuild_joinrel_restrictlist(RelOptInfo *joinrel,
List *joininfo_list) List *joininfo_list)
{ {
List *restrictlist = NIL; List *restrictlist = NIL;
List *xjoininfo; ListCell *xjoininfo;
foreach(xjoininfo, joininfo_list) foreach(xjoininfo, joininfo_list)
{ {
@ -515,7 +515,7 @@ static void
subbuild_joinrel_joinlist(RelOptInfo *joinrel, subbuild_joinrel_joinlist(RelOptInfo *joinrel,
List *joininfo_list) List *joininfo_list)
{ {
List *xjoininfo; ListCell *xjoininfo;
foreach(xjoininfo, joininfo_list) foreach(xjoininfo, joininfo_list)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/restrictinfo.c,v 1.26 2004/02/27 21:48:04 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/restrictinfo.c,v 1.27 2004/05/26 04:41:27 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -93,14 +93,14 @@ make_restrictinfo_from_indexclauses(List *indexclauses,
{ {
List *withris = NIL; List *withris = NIL;
List *withoutris = NIL; List *withoutris = NIL;
List *orlist; ListCell *orlist;
/* Empty list probably can't happen, but here's what to do */ /* Empty list probably can't happen, but here's what to do */
if (indexclauses == NIL) if (indexclauses == NIL)
return NIL; return NIL;
/* If single indexscan, just return the ANDed clauses */ /* If single indexscan, just return the ANDed clauses */
if (lnext(indexclauses) == NIL) if (length(indexclauses) == 1)
return (List *) lfirst(indexclauses); return (List *) linitial(indexclauses);
/* Else we need an OR RestrictInfo structure */ /* Else we need an OR RestrictInfo structure */
foreach(orlist, indexclauses) foreach(orlist, indexclauses)
{ {
@ -206,7 +206,7 @@ make_sub_restrictinfos(Expr *clause, bool is_pushed_down,
if (or_clause((Node *) clause)) if (or_clause((Node *) clause))
{ {
List *orlist = NIL; List *orlist = NIL;
List *temp; ListCell *temp;
foreach(temp, ((BoolExpr *) clause)->args) foreach(temp, ((BoolExpr *) clause)->args)
orlist = lappend(orlist, orlist = lappend(orlist,
@ -218,7 +218,7 @@ make_sub_restrictinfos(Expr *clause, bool is_pushed_down,
else if (and_clause((Node *) clause)) else if (and_clause((Node *) clause))
{ {
List *andlist = NIL; List *andlist = NIL;
List *temp; ListCell *temp;
foreach(temp, ((BoolExpr *) clause)->args) foreach(temp, ((BoolExpr *) clause)->args)
andlist = lappend(andlist, andlist = lappend(andlist,
@ -257,7 +257,7 @@ List *
get_actual_clauses(List *restrictinfo_list) get_actual_clauses(List *restrictinfo_list)
{ {
List *result = NIL; List *result = NIL;
List *temp; ListCell *temp;
foreach(temp, restrictinfo_list) foreach(temp, restrictinfo_list)
{ {
@ -280,7 +280,7 @@ void
get_actual_join_clauses(List *restrictinfo_list, get_actual_join_clauses(List *restrictinfo_list,
List **joinquals, List **otherquals) List **joinquals, List **otherquals)
{ {
List *temp; ListCell *temp;
*joinquals = NIL; *joinquals = NIL;
*otherquals = NIL; *otherquals = NIL;
@ -317,7 +317,7 @@ remove_redundant_join_clauses(Query *root, List *restrictinfo_list,
JoinType jointype) JoinType jointype)
{ {
List *result = NIL; List *result = NIL;
List *item; ListCell *item;
QualCost cost; QualCost cost;
/* /*
@ -380,7 +380,7 @@ select_nonredundant_join_clauses(Query *root,
JoinType jointype) JoinType jointype)
{ {
List *result = NIL; List *result = NIL;
List *item; ListCell *item;
foreach(item, restrictinfo_list) foreach(item, restrictinfo_list)
{ {
@ -431,7 +431,7 @@ join_clause_is_redundant(Query *root,
List *reference_list, List *reference_list,
JoinType jointype) JoinType jointype)
{ {
List *refitem; ListCell *refitem;
/* always consider exact duplicates redundant */ /* always consider exact duplicates redundant */
foreach(refitem, reference_list) foreach(refitem, reference_list)

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/tlist.c,v 1.62 2004/01/07 18:56:26 neilc Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/tlist.c,v 1.63 2004/05/26 04:41:27 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -31,7 +31,7 @@
TargetEntry * TargetEntry *
tlistentry_member(Node *node, List *targetlist) tlistentry_member(Node *node, List *targetlist)
{ {
List *temp; ListCell *temp;
foreach(temp, targetlist) foreach(temp, targetlist)
{ {
@ -138,11 +138,11 @@ List *
add_to_flat_tlist(List *tlist, List *vars) add_to_flat_tlist(List *tlist, List *vars)
{ {
int next_resdomno = length(tlist) + 1; int next_resdomno = length(tlist) + 1;
List *v; ListCell *v;
foreach(v, vars) foreach(v, vars)
{ {
Var *var = lfirst(v); Var *var = (Var *) lfirst(v);
if (!tlistentry_member((Node *) var, tlist)) if (!tlistentry_member((Node *) var, tlist))
{ {
@ -173,7 +173,7 @@ get_sortgroupclause_tle(SortClause *sortClause,
List *targetList) List *targetList)
{ {
Index refnumber = sortClause->tleSortGroupRef; Index refnumber = sortClause->tleSortGroupRef;
List *l; ListCell *l;
foreach(l, targetList) foreach(l, targetList)
{ {
@ -212,7 +212,7 @@ List *
get_sortgrouplist_exprs(List *sortClauses, List *targetList) get_sortgrouplist_exprs(List *sortClauses, List *targetList)
{ {
List *result = NIL; List *result = NIL;
List *l; ListCell *l;
foreach(l, sortClauses) foreach(l, sortClauses)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/util/var.c,v 1.56 2004/05/10 22:44:45 tgl Exp $ * $PostgreSQL: pgsql/src/backend/optimizer/util/var.c,v 1.57 2004/05/26 04:41:27 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -515,7 +515,7 @@ flatten_join_alias_vars_mutator(Node *node,
/* Must expand whole-row reference */ /* Must expand whole-row reference */
RowExpr *rowexpr; RowExpr *rowexpr;
List *fields = NIL; List *fields = NIL;
List *l; ListCell *l;
foreach(l, rte->joinaliasvars) foreach(l, rte->joinaliasvars)
{ {

View File

@ -6,7 +6,7 @@
* Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 1994, Regents of the University of California
* *
* $PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.300 2004/05/23 17:10:54 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.301 2004/05/26 04:41:29 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -240,28 +240,20 @@ do_parse_analyze(Node *parseTree, ParseState *pstate)
List *extras_before = NIL; List *extras_before = NIL;
List *extras_after = NIL; List *extras_after = NIL;
Query *query; Query *query;
List *listscan; ListCell *l;
query = transformStmt(pstate, parseTree, &extras_before, &extras_after); query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
/* don't need to access result relation any more */ /* don't need to access result relation any more */
release_pstate_resources(pstate); release_pstate_resources(pstate);
while (extras_before != NIL) foreach(l, extras_before)
{ result = nconc(result, parse_sub_analyze(lfirst(l), pstate));
result = nconc(result,
parse_sub_analyze(lfirst(extras_before), pstate));
extras_before = lnext(extras_before);
}
result = lappend(result, query); result = lappend(result, query);
while (extras_after != NIL) foreach(l, extras_after)
{ result = nconc(result, parse_sub_analyze(lfirst(l), pstate));
result = nconc(result,
parse_sub_analyze(lfirst(extras_after), pstate));
extras_after = lnext(extras_after);
}
/* /*
* Make sure that only the original query is marked original. We have * Make sure that only the original query is marked original. We have
@ -270,9 +262,9 @@ do_parse_analyze(Node *parseTree, ParseState *pstate)
* mark only the original query as allowed to set the command-result * mark only the original query as allowed to set the command-result
* tag. * tag.
*/ */
foreach(listscan, result) foreach(l, result)
{ {
Query *q = lfirst(listscan); Query *q = lfirst(l);
if (q == query) if (q == query)
{ {
@ -428,8 +420,8 @@ transformViewStmt(ParseState *pstate, ViewStmt *stmt,
*/ */
if (stmt->aliases != NIL) if (stmt->aliases != NIL)
{ {
List *aliaslist = stmt->aliases; ListCell *alist_item = list_head(stmt->aliases);
List *targetList; ListCell *targetList;
foreach(targetList, stmt->query->targetList) foreach(targetList, stmt->query->targetList)
{ {
@ -442,13 +434,13 @@ transformViewStmt(ParseState *pstate, ViewStmt *stmt,
/* junk columns don't get aliases */ /* junk columns don't get aliases */
if (rd->resjunk) if (rd->resjunk)
continue; continue;
rd->resname = pstrdup(strVal(lfirst(aliaslist))); rd->resname = pstrdup(strVal(lfirst(alist_item)));
aliaslist = lnext(aliaslist); alist_item = lnext(alist_item);
if (aliaslist == NIL) if (alist_item == NULL)
break; /* done assigning aliases */ break; /* done assigning aliases */
} }
if (aliaslist != NIL) if (alist_item != NULL)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("CREATE VIEW specifies more column " errmsg("CREATE VIEW specifies more column "
@ -506,9 +498,9 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
List *sub_namespace; List *sub_namespace;
List *icolumns; List *icolumns;
List *attrnos; List *attrnos;
List *icols; /* to become ListCell */ ListCell *icols;
List *attnos; /* to become ListCell */ ListCell *attnos;
List *tl; ListCell *tl;
qry->commandType = CMD_INSERT; qry->commandType = CMD_INSERT;
pstate->p_is_insert = true; pstate->p_is_insert = true;
@ -666,14 +658,14 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
/* /*
* Prepare columns for assignment to target table. * Prepare columns for assignment to target table.
*/ */
icols = icolumns; icols = list_head(icolumns);
attnos = attrnos; attnos = list_head(attrnos);
foreach(tl, qry->targetList) foreach(tl, qry->targetList)
{ {
TargetEntry *tle = (TargetEntry *) lfirst(tl); TargetEntry *tle = (TargetEntry *) lfirst(tl);
ResTarget *col; ResTarget *col;
if (icols == NIL || attnos == NIL) if (icols == NULL || attnos == NULL)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("INSERT has more expressions than target columns"))); errmsg("INSERT has more expressions than target columns")));
@ -694,7 +686,7 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
* present in the columns list. Don't do the check unless an explicit * present in the columns list. Don't do the check unless an explicit
* columns list was given, though. * columns list was given, though.
*/ */
if (stmt->cols != NIL && (icols != NIL || attnos != NIL)) if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("INSERT has more target columns than expressions"))); errmsg("INSERT has more target columns than expressions")));
@ -810,7 +802,7 @@ transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
{ {
CreateStmtContext cxt; CreateStmtContext cxt;
Query *q; Query *q;
List *elements; ListCell *elements;
cxt.stmtType = "CREATE TABLE"; cxt.stmtType = "CREATE TABLE";
cxt.relation = stmt->relation; cxt.relation = stmt->relation;
@ -895,7 +887,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
bool is_serial; bool is_serial;
bool saw_nullable; bool saw_nullable;
Constraint *constraint; Constraint *constraint;
List *clist; ListCell *clist;
cxt->columns = lappend(cxt->columns, column); cxt->columns = lappend(cxt->columns, column);
@ -903,7 +895,7 @@ transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
is_serial = false; is_serial = false;
if (length(column->typename->names) == 1) if (length(column->typename->names) == 1)
{ {
char *typname = strVal(lfirst(column->typename->names)); char *typname = strVal(linitial(column->typename->names));
if (strcmp(typname, "serial") == 0 || if (strcmp(typname, "serial") == 0 ||
strcmp(typname, "serial4") == 0) strcmp(typname, "serial4") == 0)
@ -1256,13 +1248,10 @@ transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
static void static void
transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt) transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
{ {
List *listptr;
List *keys;
IndexStmt *index; IndexStmt *index;
IndexElem *iparam;
ColumnDef *column;
List *columns;
List *indexlist = NIL; List *indexlist = NIL;
ListCell *listptr;
ListCell *l;
/* /*
* Run through the constraints that need to generate an index. For * Run through the constraints that need to generate an index. For
@ -1273,6 +1262,8 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
foreach(listptr, cxt->ixconstraints) foreach(listptr, cxt->ixconstraints)
{ {
Constraint *constraint = lfirst(listptr); Constraint *constraint = lfirst(listptr);
ListCell *keys;
IndexElem *iparam;
Assert(IsA(constraint, Constraint)); Assert(IsA(constraint, Constraint));
Assert((constraint->contype == CONSTR_PRIMARY) Assert((constraint->contype == CONSTR_PRIMARY)
@ -1317,11 +1308,12 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
{ {
char *key = strVal(lfirst(keys)); char *key = strVal(lfirst(keys));
bool found = false; bool found = false;
ColumnDef *column = NULL;
ListCell *columns;
column = NULL;
foreach(columns, cxt->columns) foreach(columns, cxt->columns)
{ {
column = lfirst(columns); column = (ColumnDef *) lfirst(columns);
Assert(IsA(column, ColumnDef)); Assert(IsA(column, ColumnDef));
if (strcmp(column->colname, key) == 0) if (strcmp(column->colname, key) == 0)
{ {
@ -1347,11 +1339,11 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
else if (cxt->inhRelations) else if (cxt->inhRelations)
{ {
/* try inherited tables */ /* try inherited tables */
List *inher; ListCell *inher;
foreach(inher, cxt->inhRelations) foreach(inher, cxt->inhRelations)
{ {
RangeVar *inh = lfirst(inher); RangeVar *inh = (RangeVar *) lfirst(inher);
Relation rel; Relation rel;
int count; int count;
@ -1447,19 +1439,21 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
/* Make sure we keep the PKEY index in preference to others... */ /* Make sure we keep the PKEY index in preference to others... */
cxt->alist = makeList1(cxt->pkey); cxt->alist = makeList1(cxt->pkey);
} }
while (indexlist != NIL)
{
index = lfirst(indexlist);
/* if it's pkey, it's already in cxt->alist */ foreach(l, indexlist)
if (index != cxt->pkey)
{ {
bool keep = true; bool keep = true;
List *priorlist; ListCell *k;
foreach(priorlist, cxt->alist) index = lfirst(l);
/* if it's pkey, it's already in cxt->alist */
if (index == cxt->pkey)
continue;
foreach(k, cxt->alist)
{ {
IndexStmt *priorindex = lfirst(priorlist); IndexStmt *priorindex = lfirst(k);
if (equal(index->indexParams, priorindex->indexParams)) if (equal(index->indexParams, priorindex->indexParams))
{ {
@ -1480,16 +1474,13 @@ transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
if (keep) if (keep)
cxt->alist = lappend(cxt->alist, index); cxt->alist = lappend(cxt->alist, index);
} }
indexlist = lnext(indexlist);
}
} }
static void static void
transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt, transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
bool skipValidation, bool isAddConstraint) bool skipValidation, bool isAddConstraint)
{ {
List *fkclist; ListCell *fkclist;
if (cxt->fkconstraints == NIL) if (cxt->fkconstraints == NIL)
return; return;
@ -1550,7 +1541,7 @@ transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
{ {
Query *qry; Query *qry;
RangeTblEntry *rte = NULL; RangeTblEntry *rte = NULL;
List *l; ListCell *l;
qry = makeNode(Query); qry = makeNode(Query);
qry->commandType = CMD_UTILITY; qry->commandType = CMD_UTILITY;
@ -1721,15 +1712,15 @@ transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
} }
else else
{ {
List *oldactions; ListCell *l;
List *newactions = NIL; List *newactions = NIL;
/* /*
* transform each statement, like parse_sub_analyze() * transform each statement, like parse_sub_analyze()
*/ */
foreach(oldactions, stmt->actions) foreach(l, stmt->actions)
{ {
Node *action = (Node *) lfirst(oldactions); Node *action = (Node *) lfirst(l);
ParseState *sub_pstate = make_parsestate(pstate->parentParseState); ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
Query *sub_qry, Query *sub_qry,
*top_subqry; *top_subqry;
@ -1986,9 +1977,9 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Node *limitCount; Node *limitCount;
List *forUpdate; List *forUpdate;
Node *node; Node *node;
List *lefttl, ListCell *left_tlist,
*dtlist, *dtlist;
*targetvars, List *targetvars,
*targetnames, *targetnames,
*sv_namespace, *sv_namespace,
*sv_rtable; *sv_rtable;
@ -2067,15 +2058,17 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
qry->targetList = NIL; qry->targetList = NIL;
targetvars = NIL; targetvars = NIL;
targetnames = NIL; targetnames = NIL;
lefttl = leftmostQuery->targetList; left_tlist = list_head(leftmostQuery->targetList);
foreach(dtlist, sostmt->colTypes) foreach(dtlist, sostmt->colTypes)
{ {
Oid colType = lfirsto(dtlist); Oid colType = lfirsto(dtlist);
Resdom *leftResdom = ((TargetEntry *) lfirst(lefttl))->resdom; Resdom *leftResdom;
char *colName; char *colName;
Resdom *resdom; Resdom *resdom;
Expr *expr; Expr *expr;
leftResdom = ((TargetEntry *) lfirst(left_tlist))->resdom;
Assert(!leftResdom->resjunk); Assert(!leftResdom->resjunk);
colName = pstrdup(leftResdom->resname); colName = pstrdup(leftResdom->resname);
resdom = makeResdom((AttrNumber) pstate->p_next_resno++, resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
@ -2092,7 +2085,7 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
makeTargetEntry(resdom, expr)); makeTargetEntry(resdom, expr));
targetvars = lappend(targetvars, expr); targetvars = lappend(targetvars, expr);
targetnames = lappend(targetnames, makeString(colName)); targetnames = lappend(targetnames, makeString(colName));
lefttl = lnext(lefttl); left_tlist = lnext(left_tlist);
} }
/* /*
@ -2239,7 +2232,7 @@ transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
selectList = parse_sub_analyze((Node *) stmt, pstate); selectList = parse_sub_analyze((Node *) stmt, pstate);
Assert(length(selectList) == 1); Assert(length(selectList) == 1);
selectQuery = (Query *) lfirst(selectList); selectQuery = (Query *) linitial(selectList);
Assert(IsA(selectQuery, Query)); Assert(IsA(selectQuery, Query));
/* /*
@ -2282,6 +2275,8 @@ transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
SetOperationStmt *op = makeNode(SetOperationStmt); SetOperationStmt *op = makeNode(SetOperationStmt);
List *lcoltypes; List *lcoltypes;
List *rcoltypes; List *rcoltypes;
ListCell *l;
ListCell *r;
const char *context; const char *context;
context = (stmt->op == SETOP_UNION ? "UNION" : context = (stmt->op == SETOP_UNION ? "UNION" :
@ -2308,18 +2303,17 @@ transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("each %s query must have the same number of columns", errmsg("each %s query must have the same number of columns",
context))); context)));
op->colTypes = NIL; op->colTypes = NIL;
while (lcoltypes != NIL) forboth(l, lcoltypes, r, rcoltypes)
{ {
Oid lcoltype = lfirsto(lcoltypes); Oid lcoltype = lfirsto(l);
Oid rcoltype = lfirsto(rcoltypes); Oid rcoltype = lfirsto(r);
Oid rescoltype; Oid rescoltype;
rescoltype = select_common_type(makeListo2(lcoltype, rcoltype), rescoltype = select_common_type(makeListo2(lcoltype, rcoltype),
context); context);
op->colTypes = lappendo(op->colTypes, rescoltype); op->colTypes = lappendo(op->colTypes, rescoltype);
lcoltypes = lnext(lcoltypes);
rcoltypes = lnext(rcoltypes);
} }
return (Node *) op; return (Node *) op;
@ -2339,7 +2333,7 @@ getSetColTypes(ParseState *pstate, Node *node)
RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable); RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
Query *selectQuery = rte->subquery; Query *selectQuery = rte->subquery;
List *result = NIL; List *result = NIL;
List *tl; ListCell *tl;
Assert(selectQuery != NULL); Assert(selectQuery != NULL);
/* Get types of non-junk columns */ /* Get types of non-junk columns */
@ -2373,22 +2367,25 @@ getSetColTypes(ParseState *pstate, Node *node)
static void static void
applyColumnNames(List *dst, List *src) applyColumnNames(List *dst, List *src)
{ {
ListCell *dst_item = list_head(dst);
ListCell *src_item = list_head(src);
if (length(src) > length(dst)) if (length(src) > length(dst))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("CREATE TABLE AS specifies too many column names"))); errmsg("CREATE TABLE AS specifies too many column names")));
while (src != NIL && dst != NIL) while (src_item != NULL && dst_item != NULL)
{ {
TargetEntry *d = (TargetEntry *) lfirst(dst); TargetEntry *d = (TargetEntry *) lfirst(dst_item);
ColumnDef *s = (ColumnDef *) lfirst(src); ColumnDef *s = (ColumnDef *) lfirst(src_item);
Assert(d->resdom && !d->resdom->resjunk); Assert(d->resdom && !d->resdom->resjunk);
d->resdom->resname = pstrdup(s->colname); d->resdom->resname = pstrdup(s->colname);
dst = lnext(dst); dst_item = lnext(dst_item);
src = lnext(src); src_item = lnext(src_item);
} }
} }
@ -2402,8 +2399,8 @@ transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
{ {
Query *qry = makeNode(Query); Query *qry = makeNode(Query);
Node *qual; Node *qual;
List *origTargetList; ListCell *origTargetList;
List *tl; ListCell *tl;
qry->commandType = CMD_UPDATE; qry->commandType = CMD_UPDATE;
pstate->p_is_update = true; pstate->p_is_update = true;
@ -2441,7 +2438,8 @@ transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1; pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
/* Prepare non-junk columns for assignment to target table */ /* Prepare non-junk columns for assignment to target table */
origTargetList = stmt->targetList; origTargetList = list_head(stmt->targetList);
foreach(tl, qry->targetList) foreach(tl, qry->targetList)
{ {
TargetEntry *tle = (TargetEntry *) lfirst(tl); TargetEntry *tle = (TargetEntry *) lfirst(tl);
@ -2460,7 +2458,7 @@ transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
resnode->resname = NULL; resnode->resname = NULL;
continue; continue;
} }
if (origTargetList == NIL) if (origTargetList == NULL)
elog(ERROR, "UPDATE target count mismatch --- internal error"); elog(ERROR, "UPDATE target count mismatch --- internal error");
origTarget = (ResTarget *) lfirst(origTargetList); origTarget = (ResTarget *) lfirst(origTargetList);
@ -2471,7 +2469,7 @@ transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
origTargetList = lnext(origTargetList); origTargetList = lnext(origTargetList);
} }
if (origTargetList != NIL) if (origTargetList != NULL)
elog(ERROR, "UPDATE target count mismatch --- internal error"); elog(ERROR, "UPDATE target count mismatch --- internal error");
return qry; return qry;
@ -2487,7 +2485,7 @@ transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
{ {
CreateStmtContext cxt; CreateStmtContext cxt;
Query *qry; Query *qry;
List *lcmd, ListCell *lcmd,
*l; *l;
List *newcmds = NIL; List *newcmds = NIL;
bool skipValidation = true; bool skipValidation = true;
@ -2687,7 +2685,7 @@ transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
if (nargs) if (nargs)
{ {
List *l; ListCell *l;
int i = 0; int i = 0;
argtoids = (Oid *) palloc(nargs * sizeof(Oid)); argtoids = (Oid *) palloc(nargs * sizeof(Oid));
@ -2717,7 +2715,7 @@ transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
if (length(queries) != 1) if (length(queries) != 1)
elog(ERROR, "unexpected extra stuff in prepared statement"); elog(ERROR, "unexpected extra stuff in prepared statement");
stmt->query = lfirst(queries); stmt->query = linitial(queries);
return result; return result;
} }
@ -2737,7 +2735,7 @@ transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
{ {
int nparams = length(stmt->params); int nparams = length(stmt->params);
int nexpected = length(paramtypes); int nexpected = length(paramtypes);
List *l; ListCell *l, *l2;
int i = 1; int i = 1;
if (nparams != nexpected) if (nparams != nexpected)
@ -2748,11 +2746,11 @@ transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
errdetail("Expected %d parameters but got %d.", errdetail("Expected %d parameters but got %d.",
nexpected, nparams))); nexpected, nparams)));
foreach(l, stmt->params) forboth(l, stmt->params, l2, paramtypes)
{ {
Node *expr = lfirst(l); Node *expr = lfirst(l);
Oid expected_type_id, Oid expected_type_id = lfirsto(l2);
given_type_id; Oid given_type_id;
expr = transformExpr(pstate, expr); expr = transformExpr(pstate, expr);
@ -2767,7 +2765,6 @@ transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
errmsg("cannot use aggregate function in EXECUTE parameter"))); errmsg("cannot use aggregate function in EXECUTE parameter")));
given_type_id = exprType(expr); given_type_id = exprType(expr);
expected_type_id = lfirsto(paramtypes);
expr = coerce_to_target_type(pstate, expr, given_type_id, expr = coerce_to_target_type(pstate, expr, given_type_id,
expected_type_id, -1, expected_type_id, -1,
@ -2784,8 +2781,6 @@ transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
errhint("You will need to rewrite or cast the expression."))); errhint("You will need to rewrite or cast the expression.")));
lfirst(l) = expr; lfirst(l) = expr;
paramtypes = lnext(paramtypes);
i++; i++;
} }
} }
@ -2825,13 +2820,13 @@ static void
transformForUpdate(Query *qry, List *forUpdate) transformForUpdate(Query *qry, List *forUpdate)
{ {
List *rowMarks = qry->rowMarks; List *rowMarks = qry->rowMarks;
List *l; ListCell *l;
List *rt; ListCell *rt;
Index i; Index i;
CheckSelectForUpdate(qry); CheckSelectForUpdate(qry);
if (lfirst(forUpdate) == NULL) if (linitial(forUpdate) == NULL)
{ {
/* all regular tables used in query */ /* all regular tables used in query */
i = 0; i = 0;
@ -2912,7 +2907,7 @@ transformForUpdate(Query *qry, List *forUpdate)
break; /* out of foreach loop */ break; /* out of foreach loop */
} }
} }
if (rt == NIL) if (rt == NULL)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_TABLE), (errcode(ERRCODE_UNDEFINED_TABLE),
errmsg("relation \"%s\" in FOR UPDATE clause not found in FROM clause", errmsg("relation \"%s\" in FOR UPDATE clause not found in FROM clause",
@ -2938,7 +2933,7 @@ transformConstraintAttrs(List *constraintList)
Node *lastprimarynode = NULL; Node *lastprimarynode = NULL;
bool saw_deferrability = false; bool saw_deferrability = false;
bool saw_initially = false; bool saw_initially = false;
List *clist; ListCell *clist;
foreach(clist, constraintList) foreach(clist, constraintList)
{ {
@ -3113,7 +3108,7 @@ analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
{ {
CreateSchemaStmtContext cxt; CreateSchemaStmtContext cxt;
List *result; List *result;
List *elements; ListCell *elements;
cxt.stmtType = "CREATE SCHEMA"; cxt.stmtType = "CREATE SCHEMA";
cxt.schemaname = stmt->schemaname; cxt.schemaname = stmt->schemaname;

View File

@ -11,7 +11,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.454 2004/05/10 22:44:45 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.455 2004/05/26 04:41:29 neilc Exp $
* *
* HISTORY * HISTORY
* AUTHOR DATE MAJOR EVENT * AUTHOR DATE MAJOR EVENT
@ -2385,15 +2385,15 @@ DefineStmt:
case 1: case 1:
r->catalogname = NULL; r->catalogname = NULL;
r->schemaname = NULL; r->schemaname = NULL;
r->relname = strVal(lfirst($3)); r->relname = strVal(linitial($3));
break; break;
case 2: case 2:
r->catalogname = NULL; r->catalogname = NULL;
r->schemaname = strVal(lfirst($3)); r->schemaname = strVal(linitial($3));
r->relname = strVal(lsecond($3)); r->relname = strVal(lsecond($3));
break; break;
case 3: case 3:
r->catalogname = strVal(lfirst($3)); r->catalogname = strVal(linitial($3));
r->schemaname = strVal(lsecond($3)); r->schemaname = strVal(lsecond($3));
r->relname = strVal(lthird($3)); r->relname = strVal(lthird($3));
break; break;
@ -6020,7 +6020,7 @@ a_expr: c_expr { $$ = $1; }
else else
{ {
Node *n = NULL; Node *n = NULL;
List *l; ListCell *l;
foreach(l, (List *) $3) foreach(l, (List *) $3)
{ {
Node *cmp; Node *cmp;
@ -6052,7 +6052,7 @@ a_expr: c_expr { $$ = $1; }
else else
{ {
Node *n = NULL; Node *n = NULL;
List *l; ListCell *l;
foreach(l, (List *) $4) foreach(l, (List *) $4)
{ {
Node *cmp; Node *cmp;
@ -7168,11 +7168,11 @@ qualified_name:
{ {
case 2: case 2:
$$->catalogname = NULL; $$->catalogname = NULL;
$$->schemaname = strVal(lfirst($1)); $$->schemaname = strVal(linitial($1));
$$->relname = strVal(lsecond($1)); $$->relname = strVal(lsecond($1));
break; break;
case 3: case 3:
$$->catalogname = strVal(lfirst($1)); $$->catalogname = strVal(linitial($1));
$$->schemaname = strVal(lsecond($1)); $$->schemaname = strVal(lsecond($1));
$$->relname = strVal(lthird($1)); $$->relname = strVal(lthird($1));
break; break;
@ -7865,7 +7865,7 @@ static Node *
makeRowNullTest(NullTestType test, RowExpr *row) makeRowNullTest(NullTestType test, RowExpr *row)
{ {
Node *result = NULL; Node *result = NULL;
List *arg; ListCell *arg;
foreach(arg, row->args) foreach(arg, row->args)
{ {
@ -7928,7 +7928,7 @@ static List *
extractArgTypes(List *parameters) extractArgTypes(List *parameters)
{ {
List *result = NIL; List *result = NIL;
List *i; ListCell *i;
foreach(i, parameters) foreach(i, parameters)
{ {

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/parse_agg.c,v 1.61 2004/01/28 07:46:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/parse_agg.c,v 1.62 2004/05/26 04:41:29 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -99,7 +99,7 @@ parseCheckAggregates(ParseState *pstate, Query *qry)
{ {
List *groupClauses = NIL; List *groupClauses = NIL;
bool have_non_var_grouping; bool have_non_var_grouping;
List *lst; ListCell *l;
bool hasJoinRTEs; bool hasJoinRTEs;
Node *clause; Node *clause;
@ -129,9 +129,9 @@ parseCheckAggregates(ParseState *pstate, Query *qry)
* While we are at it, build a list of the acceptable GROUP BY * While we are at it, build a list of the acceptable GROUP BY
* expressions for use by check_ungrouped_columns(). * expressions for use by check_ungrouped_columns().
*/ */
foreach(lst, qry->groupClause) foreach(l, qry->groupClause)
{ {
GroupClause *grpcl = (GroupClause *) lfirst(lst); GroupClause *grpcl = (GroupClause *) lfirst(l);
Node *expr; Node *expr;
expr = get_sortgroupclause_expr(grpcl, qry->targetList); expr = get_sortgroupclause_expr(grpcl, qry->targetList);
@ -151,9 +151,9 @@ parseCheckAggregates(ParseState *pstate, Query *qry)
* no rangetable entries are RTE_JOIN kind. * no rangetable entries are RTE_JOIN kind.
*/ */
hasJoinRTEs = false; hasJoinRTEs = false;
foreach(lst, pstate->p_rtable) foreach(l, pstate->p_rtable)
{ {
RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst); RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
if (rte->rtekind == RTE_JOIN) if (rte->rtekind == RTE_JOIN)
{ {
@ -172,9 +172,9 @@ parseCheckAggregates(ParseState *pstate, Query *qry)
* recursive scans. (Note we have to flatten aliases before this.) * recursive scans. (Note we have to flatten aliases before this.)
*/ */
have_non_var_grouping = false; have_non_var_grouping = false;
foreach(lst, groupClauses) foreach(l, groupClauses)
{ {
if (!IsA((Node *) lfirst(lst), Var)) if (!IsA((Node *) lfirst(l), Var))
{ {
have_non_var_grouping = true; have_non_var_grouping = true;
break; break;
@ -236,7 +236,7 @@ static bool
check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_walker(Node *node,
check_ungrouped_columns_context *context) check_ungrouped_columns_context *context)
{ {
List *gl; ListCell *gl;
if (node == NULL) if (node == NULL)
return false; return false;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/parse_clause.c,v 1.129 2004/05/23 17:10:54 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/parse_clause.c,v 1.130 2004/05/26 04:41:29 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -79,7 +79,7 @@ static TargetEntry *findTargetlistEntry(ParseState *pstate, Node *node,
void void
transformFromClause(ParseState *pstate, List *frmList) transformFromClause(ParseState *pstate, List *frmList)
{ {
List *fl; ListCell *fl;
/* /*
* The grammar will have produced a list of RangeVars, * The grammar will have produced a list of RangeVars,
@ -231,14 +231,15 @@ extractRemainingColumns(List *common_colnames,
{ {
List *new_colnames = NIL; List *new_colnames = NIL;
List *new_colvars = NIL; List *new_colvars = NIL;
List *lnames, ListCell *lnames, *lvars;
*lvars = src_colvars;
foreach(lnames, src_colnames) Assert(length(src_colnames) == length(src_colvars));
forboth(lnames, src_colnames, lvars, src_colvars)
{ {
char *colname = strVal(lfirst(lnames)); char *colname = strVal(lfirst(lnames));
bool match = false; bool match = false;
List *cnames; ListCell *cnames;
foreach(cnames, common_colnames) foreach(cnames, common_colnames)
{ {
@ -256,8 +257,6 @@ extractRemainingColumns(List *common_colnames,
new_colnames = lappend(new_colnames, lfirst(lnames)); new_colnames = lappend(new_colnames, lfirst(lnames));
new_colvars = lappend(new_colvars, lfirst(lvars)); new_colvars = lappend(new_colvars, lfirst(lvars));
} }
lvars = lnext(lvars);
} }
*res_colnames = new_colnames; *res_colnames = new_colnames;
@ -273,8 +272,7 @@ static Node *
transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars) transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
{ {
Node *result = NULL; Node *result = NULL;
List *lvars, ListCell *lvars, *rvars;
*rvars = rightVars;
/* /*
* We cheat a little bit here by building an untransformed operator * We cheat a little bit here by building an untransformed operator
@ -282,7 +280,7 @@ transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
* because transformExpr() won't complain about already-transformed * because transformExpr() won't complain about already-transformed
* subnodes. * subnodes.
*/ */
foreach(lvars, leftVars) forboth(lvars, leftVars, rvars, rightVars)
{ {
Node *lvar = (Node *) lfirst(lvars); Node *lvar = (Node *) lfirst(lvars);
Node *rvar = (Node *) lfirst(rvars); Node *rvar = (Node *) lfirst(rvars);
@ -299,8 +297,6 @@ transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
a = makeA_Expr(AEXPR_AND, NIL, result, (Node *) e); a = makeA_Expr(AEXPR_AND, NIL, result, (Node *) e);
result = (Node *) a; result = (Node *) a;
} }
rvars = lnext(rvars);
} }
/* /*
@ -314,7 +310,7 @@ transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
result = coerce_to_boolean(pstate, result, "JOIN/USING"); result = coerce_to_boolean(pstate, result, "JOIN/USING");
return result; return result;
} /* transformJoinUsingClause() */ }
/* transformJoinOnClause() /* transformJoinOnClause()
* Transform the qual conditions for JOIN/ON. * Transform the qual conditions for JOIN/ON.
@ -435,7 +431,7 @@ transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
*/ */
if (length(parsetrees) != 1) if (length(parsetrees) != 1)
elog(ERROR, "unexpected parse analysis result for subquery in FROM"); elog(ERROR, "unexpected parse analysis result for subquery in FROM");
query = (Query *) lfirst(parsetrees); query = (Query *) linitial(parsetrees);
if (query == NULL || !IsA(query, Query)) if (query == NULL || !IsA(query, Query))
elog(ERROR, "unexpected parse analysis result for subquery in FROM"); elog(ERROR, "unexpected parse analysis result for subquery in FROM");
@ -686,7 +682,7 @@ transformFromClauseItem(ParseState *pstate, Node *n, List **containedRels)
if (j->isNatural) if (j->isNatural)
{ {
List *rlist = NIL; List *rlist = NIL;
List *lx, ListCell *lx,
*rx; *rx;
Assert(j->using == NIL); /* shouldn't have USING() too */ Assert(j->using == NIL); /* shouldn't have USING() too */
@ -731,14 +727,14 @@ transformFromClauseItem(ParseState *pstate, Node *n, List **containedRels)
List *ucols = j->using; List *ucols = j->using;
List *l_usingvars = NIL; List *l_usingvars = NIL;
List *r_usingvars = NIL; List *r_usingvars = NIL;
List *ucol; ListCell *ucol;
Assert(j->quals == NULL); /* shouldn't have ON() too */ Assert(j->quals == NULL); /* shouldn't have ON() too */
foreach(ucol, ucols) foreach(ucol, ucols)
{ {
char *u_colname = strVal(lfirst(ucol)); char *u_colname = strVal(lfirst(ucol));
List *col; ListCell *col;
int ndx; int ndx;
int l_index = -1; int l_index = -1;
int r_index = -1; int r_index = -1;
@ -1083,7 +1079,7 @@ static TargetEntry *
findTargetlistEntry(ParseState *pstate, Node *node, List **tlist, int clause) findTargetlistEntry(ParseState *pstate, Node *node, List **tlist, int clause)
{ {
TargetEntry *target_result = NULL; TargetEntry *target_result = NULL;
List *tl; ListCell *tl;
Node *expr; Node *expr;
/*---------- /*----------
@ -1129,7 +1125,7 @@ findTargetlistEntry(ParseState *pstate, Node *node, List **tlist, int clause)
length(((ColumnRef *) node)->fields) == 1 && length(((ColumnRef *) node)->fields) == 1 &&
((ColumnRef *) node)->indirection == NIL) ((ColumnRef *) node)->indirection == NIL)
{ {
char *name = strVal(lfirst(((ColumnRef *) node)->fields)); char *name = strVal(linitial(((ColumnRef *) node)->fields));
if (clause == GROUP_CLAUSE) if (clause == GROUP_CLAUSE)
{ {
@ -1255,8 +1251,11 @@ List *
transformGroupClause(ParseState *pstate, List *grouplist, transformGroupClause(ParseState *pstate, List *grouplist,
List **targetlist, List *sortClause) List **targetlist, List *sortClause)
{ {
List *glist = NIL, List *glist = NIL;
*gl; ListCell *gl;
ListCell *sortItem;
sortItem = list_head(sortClause);
foreach(gl, grouplist) foreach(gl, grouplist)
{ {
@ -1293,17 +1292,17 @@ transformGroupClause(ParseState *pstate, List *grouplist,
* any user-supplied ordering operator will bring equal values * any user-supplied ordering operator will bring equal values
* together, which is all that GROUP BY needs. * together, which is all that GROUP BY needs.
*/ */
if (sortClause && if (sortItem &&
((SortClause *) lfirst(sortClause))->tleSortGroupRef == ((SortClause *) lfirst(sortItem))->tleSortGroupRef ==
tle->resdom->ressortgroupref) tle->resdom->ressortgroupref)
{ {
ordering_op = ((SortClause *) lfirst(sortClause))->sortop; ordering_op = ((SortClause *) lfirst(sortItem))->sortop;
sortClause = lnext(sortClause); sortItem = lnext(sortItem);
} }
else else
{ {
ordering_op = ordering_oper_opid(restype); ordering_op = ordering_oper_opid(restype);
sortClause = NIL; /* disregard ORDER BY once match fails */ sortItem = NULL; /* disregard ORDER BY once match fails */
} }
grpcl = makeNode(GroupClause); grpcl = makeNode(GroupClause);
@ -1329,7 +1328,7 @@ transformSortClause(ParseState *pstate,
bool resolveUnknown) bool resolveUnknown)
{ {
List *sortlist = NIL; List *sortlist = NIL;
List *olitem; ListCell *olitem;
foreach(olitem, orderlist) foreach(olitem, orderlist)
{ {
@ -1361,14 +1360,14 @@ transformDistinctClause(ParseState *pstate, List *distinctlist,
List **targetlist, List **sortClause) List **targetlist, List **sortClause)
{ {
List *result = NIL; List *result = NIL;
List *slitem; ListCell *slitem;
List *dlitem; ListCell *dlitem;
/* No work if there was no DISTINCT clause */ /* No work if there was no DISTINCT clause */
if (distinctlist == NIL) if (distinctlist == NIL)
return NIL; return NIL;
if (lfirst(distinctlist) == NIL) if (linitial(distinctlist) == NULL)
{ {
/* We had SELECT DISTINCT */ /* We had SELECT DISTINCT */
@ -1423,7 +1422,7 @@ transformDistinctClause(ParseState *pstate, List *distinctlist,
* match in any order, but implementing that check seems like more * match in any order, but implementing that check seems like more
* trouble than it's worth. * trouble than it's worth.
*/ */
List *nextsortlist = *sortClause; ListCell *nextsortlist = list_head(*sortClause);
foreach(dlitem, distinctlist) foreach(dlitem, distinctlist)
{ {
@ -1432,7 +1431,7 @@ transformDistinctClause(ParseState *pstate, List *distinctlist,
tle = findTargetlistEntry(pstate, lfirst(dlitem), tle = findTargetlistEntry(pstate, lfirst(dlitem),
targetlist, DISTINCT_ON_CLAUSE); targetlist, DISTINCT_ON_CLAUSE);
if (nextsortlist != NIL) if (nextsortlist != NULL)
{ {
SortClause *scl = (SortClause *) lfirst(nextsortlist); SortClause *scl = (SortClause *) lfirst(nextsortlist);
@ -1463,7 +1462,7 @@ transformDistinctClause(ParseState *pstate, List *distinctlist,
break; break;
} }
} }
if (slitem == NIL) /* should not happen */ if (slitem == NULL) /* should not happen */
elog(ERROR, "failed to add DISTINCT ON clause to target list"); elog(ERROR, "failed to add DISTINCT ON clause to target list");
} }
} }
@ -1486,11 +1485,11 @@ List *
addAllTargetsToSortList(ParseState *pstate, List *sortlist, addAllTargetsToSortList(ParseState *pstate, List *sortlist,
List *targetlist, bool resolveUnknown) List *targetlist, bool resolveUnknown)
{ {
List *i; ListCell *l;
foreach(i, targetlist) foreach(l, targetlist)
{ {
TargetEntry *tle = (TargetEntry *) lfirst(i); TargetEntry *tle = (TargetEntry *) lfirst(l);
if (!tle->resdom->resjunk) if (!tle->resdom->resjunk)
sortlist = addTargetToSortList(pstate, tle, sortlist = addTargetToSortList(pstate, tle,
@ -1575,7 +1574,7 @@ Index
assignSortGroupRef(TargetEntry *tle, List *tlist) assignSortGroupRef(TargetEntry *tle, List *tlist)
{ {
Index maxRef; Index maxRef;
List *l; ListCell *l;
if (tle->resdom->ressortgroupref) /* already has one? */ if (tle->resdom->ressortgroupref) /* already has one? */
return tle->resdom->ressortgroupref; return tle->resdom->ressortgroupref;
@ -1605,15 +1604,15 @@ bool
targetIsInSortList(TargetEntry *tle, List *sortList) targetIsInSortList(TargetEntry *tle, List *sortList)
{ {
Index ref = tle->resdom->ressortgroupref; Index ref = tle->resdom->ressortgroupref;
List *i; ListCell *l;
/* no need to scan list if tle has no marker */ /* no need to scan list if tle has no marker */
if (ref == 0) if (ref == 0)
return false; return false;
foreach(i, sortList) foreach(l, sortList)
{ {
SortClause *scl = (SortClause *) lfirst(i); SortClause *scl = (SortClause *) lfirst(l);
if (scl->tleSortGroupRef == ref) if (scl->tleSortGroupRef == ref)
return true; return true;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/parse_coerce.c,v 2.115 2004/05/10 22:44:46 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/parse_coerce.c,v 2.116 2004/05/26 04:41:30 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -546,7 +546,7 @@ coerce_record_to_complex(ParseState *pstate, Node *node,
List *args = NIL; List *args = NIL;
List *newargs; List *newargs;
int i; int i;
List *arg; ListCell *arg;
if (node && IsA(node, RowExpr)) if (node && IsA(node, RowExpr))
{ {
@ -720,14 +720,15 @@ select_common_type(List *typeids, const char *context)
{ {
Oid ptype; Oid ptype;
CATEGORY pcategory; CATEGORY pcategory;
List *l; ListCell *type_item;
Assert(typeids != NIL); Assert(typeids != NIL);
ptype = getBaseType(lfirsto(typeids)); ptype = getBaseType(linitial_oid(typeids));
pcategory = TypeCategory(ptype); pcategory = TypeCategory(ptype);
foreach(l, lnext(typeids))
for_each_cell(type_item, lnext(list_head(typeids)))
{ {
Oid ntype = getBaseType(lfirsto(l)); Oid ntype = getBaseType(lfirsto(type_item));
/* move on to next one if no new information... */ /* move on to next one if no new information... */
if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype)) if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
@ -746,7 +747,6 @@ select_common_type(List *typeids, const char *context)
*/ */
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH), (errcode(ERRCODE_DATATYPE_MISMATCH),
/* /*
* translator: first %s is name of a SQL construct, eg * translator: first %s is name of a SQL construct, eg
* CASE * CASE

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/parse_expr.c,v 1.170 2004/05/10 22:44:46 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/parse_expr.c,v 1.171 2004/05/26 04:41:30 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -100,7 +100,7 @@ transformExpr(ParseState *pstate, Node *expr)
int paramno = pref->number; int paramno = pref->number;
ParseState *toppstate; ParseState *toppstate;
Param *param; Param *param;
List *fields; ListCell *fields;
/* /*
* Find topmost ParseState, which is where paramtype info * Find topmost ParseState, which is where paramtype info
@ -176,7 +176,7 @@ transformExpr(ParseState *pstate, Node *expr)
case T_ExprFieldSelect: case T_ExprFieldSelect:
{ {
ExprFieldSelect *efs = (ExprFieldSelect *) expr; ExprFieldSelect *efs = (ExprFieldSelect *) expr;
List *fields; ListCell *fields;
result = transformExpr(pstate, efs->arg); result = transformExpr(pstate, efs->arg);
/* handle qualification, if any */ /* handle qualification, if any */
@ -219,7 +219,7 @@ transformExpr(ParseState *pstate, Node *expr)
*/ */
if (Transform_null_equals && if (Transform_null_equals &&
length(a->name) == 1 && length(a->name) == 1 &&
strcmp(strVal(lfirst(a->name)), "=") == 0 && strcmp(strVal(linitial(a->name)), "=") == 0 &&
(exprIsNullConstant(lexpr) || (exprIsNullConstant(lexpr) ||
exprIsNullConstant(rexpr))) exprIsNullConstant(rexpr)))
{ {
@ -396,7 +396,7 @@ transformExpr(ParseState *pstate, Node *expr)
* Checking an expression for match to type. * Checking an expression for match to type.
* Will result in a boolean constant node. * Will result in a boolean constant node.
*/ */
List *telem; ListCell *telem;
A_Const *n; A_Const *n;
Oid ltype, Oid ltype,
rtype; rtype;
@ -418,7 +418,7 @@ transformExpr(ParseState *pstate, Node *expr)
* Flip the sense of the result for not * Flip the sense of the result for not
* equals. * equals.
*/ */
if (strcmp(strVal(lfirst(a->name)), "!=") == 0) if (strcmp(strVal(linitial(a->name)), "!=") == 0)
matched = (!matched); matched = (!matched);
n = makeNode(A_Const); n = makeNode(A_Const);
@ -436,12 +436,15 @@ transformExpr(ParseState *pstate, Node *expr)
{ {
FuncCall *fn = (FuncCall *) expr; FuncCall *fn = (FuncCall *) expr;
List *targs; List *targs;
List *args; ListCell *args;
/* /*
* Transform the list of arguments. We use a shallow list * Transform the list of arguments. We use a shallow list
* copy and then transform-in-place to avoid O(N^2) * copy and then transform-in-place to avoid O(N^2)
* behavior from repeated lappend's. * behavior from repeated lappend's.
*
* XXX: repeated lappend() would no longer result in
* O(n^2) behavior; worth reconsidering this design?
*/ */
targs = listCopy(fn->args); targs = listCopy(fn->args);
foreach(args, targs) foreach(args, targs)
@ -473,7 +476,7 @@ transformExpr(ParseState *pstate, Node *expr)
qtrees = parse_sub_analyze(sublink->subselect, pstate); qtrees = parse_sub_analyze(sublink->subselect, pstate);
if (length(qtrees) != 1) if (length(qtrees) != 1)
elog(ERROR, "bad query in sub-select"); elog(ERROR, "bad query in sub-select");
qtree = (Query *) lfirst(qtrees); qtree = (Query *) linitial(qtrees);
if (qtree->commandType != CMD_SELECT || if (qtree->commandType != CMD_SELECT ||
qtree->resultRelation != 0) qtree->resultRelation != 0)
elog(ERROR, "bad query in sub-select"); elog(ERROR, "bad query in sub-select");
@ -493,20 +496,20 @@ transformExpr(ParseState *pstate, Node *expr)
else if (sublink->subLinkType == EXPR_SUBLINK || else if (sublink->subLinkType == EXPR_SUBLINK ||
sublink->subLinkType == ARRAY_SUBLINK) sublink->subLinkType == ARRAY_SUBLINK)
{ {
List *tlist = qtree->targetList; ListCell *tlist_item = list_head(qtree->targetList);
/* /*
* Make sure the subselect delivers a single column * Make sure the subselect delivers a single column
* (ignoring resjunk targets). * (ignoring resjunk targets).
*/ */
if (tlist == NIL || if (tlist_item == NULL ||
((TargetEntry *) lfirst(tlist))->resdom->resjunk) ((TargetEntry *) lfirst(tlist_item))->resdom->resjunk)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("subquery must return a column"))); errmsg("subquery must return a column")));
while ((tlist = lnext(tlist)) != NIL) while ((tlist_item = lnext(tlist_item)) != NULL)
{ {
if (!((TargetEntry *) lfirst(tlist))->resdom->resjunk) if (!((TargetEntry *) lfirst(tlist_item))->resdom->resjunk)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("subquery must return only one column"))); errmsg("subquery must return only one column")));
@ -531,11 +534,12 @@ transformExpr(ParseState *pstate, Node *expr)
bool needNot = false; bool needNot = false;
List *op = sublink->operName; List *op = sublink->operName;
char *opname = strVal(llast(op)); char *opname = strVal(llast(op));
List *elist; ListCell *l;
ListCell *ll_item;
/* transform lefthand expressions */ /* transform lefthand expressions */
foreach(elist, left_list) foreach(l, left_list)
lfirst(elist) = transformExpr(pstate, lfirst(elist)); lfirst(l) = transformExpr(pstate, lfirst(l));
/* /*
* If the expression is "<> ALL" (with unqualified * If the expression is "<> ALL" (with unqualified
@ -578,23 +582,23 @@ transformExpr(ParseState *pstate, Node *expr)
*/ */
sublink->operOids = NIL; sublink->operOids = NIL;
while (right_list != NIL) ll_item = list_head(left_list);
foreach(l, right_list)
{ {
TargetEntry *tent = (TargetEntry *) lfirst(right_list); TargetEntry *tent = (TargetEntry *) lfirst(l);
Node *lexpr; Node *lexpr;
Operator optup; Operator optup;
Form_pg_operator opform; Form_pg_operator opform;
right_list = lnext(right_list);
if (tent->resdom->resjunk) if (tent->resdom->resjunk)
continue; continue;
if (left_list == NIL) if (ll_item == NULL)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("subquery has too many columns"))); errmsg("subquery has too many columns")));
lexpr = lfirst(left_list); lexpr = lfirst(ll_item);
left_list = lnext(left_list); ll_item = lnext(ll_item);
/* /*
* It's OK to use oper() not compatible_oper() * It's OK to use oper() not compatible_oper()
@ -627,7 +631,7 @@ transformExpr(ParseState *pstate, Node *expr)
ReleaseSysCache(optup); ReleaseSysCache(optup);
} }
if (left_list != NIL) if (ll_item != NULL)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("subquery has too few columns"))); errmsg("subquery has too few columns")));
@ -651,7 +655,7 @@ transformExpr(ParseState *pstate, Node *expr)
CaseTestExpr *placeholder; CaseTestExpr *placeholder;
List *newargs; List *newargs;
List *typeids; List *typeids;
List *args; ListCell *l;
Node *defresult; Node *defresult;
Oid ptype; Oid ptype;
@ -679,9 +683,9 @@ transformExpr(ParseState *pstate, Node *expr)
/* transform the list of arguments */ /* transform the list of arguments */
newargs = NIL; newargs = NIL;
typeids = NIL; typeids = NIL;
foreach(args, c->args) foreach(l, c->args)
{ {
CaseWhen *w = (CaseWhen *) lfirst(args); CaseWhen *w = (CaseWhen *) lfirst(l);
CaseWhen *neww = makeNode(CaseWhen); CaseWhen *neww = makeNode(CaseWhen);
Node *warg; Node *warg;
@ -741,9 +745,9 @@ transformExpr(ParseState *pstate, Node *expr)
"CASE/ELSE"); "CASE/ELSE");
/* Convert when-clause results, if necessary */ /* Convert when-clause results, if necessary */
foreach(args, newc->args) foreach(l, newc->args)
{ {
CaseWhen *w = (CaseWhen *) lfirst(args); CaseWhen *w = (CaseWhen *) lfirst(l);
w->result = (Expr *) w->result = (Expr *)
coerce_to_common_type(pstate, coerce_to_common_type(pstate,
@ -763,7 +767,7 @@ transformExpr(ParseState *pstate, Node *expr)
List *newelems = NIL; List *newelems = NIL;
List *newcoercedelems = NIL; List *newcoercedelems = NIL;
List *typeids = NIL; List *typeids = NIL;
List *element; ListCell *element;
Oid array_type; Oid array_type;
Oid element_type; Oid element_type;
@ -827,7 +831,7 @@ transformExpr(ParseState *pstate, Node *expr)
RowExpr *r = (RowExpr *) expr; RowExpr *r = (RowExpr *) expr;
RowExpr *newr = makeNode(RowExpr); RowExpr *newr = makeNode(RowExpr);
List *newargs = NIL; List *newargs = NIL;
List *arg; ListCell *arg;
/* Transform the field expressions */ /* Transform the field expressions */
foreach(arg, r->args) foreach(arg, r->args)
@ -855,7 +859,7 @@ transformExpr(ParseState *pstate, Node *expr)
List *newargs = NIL; List *newargs = NIL;
List *newcoercedargs = NIL; List *newcoercedargs = NIL;
List *typeids = NIL; List *typeids = NIL;
List *args; ListCell *args;
foreach(args, c->args) foreach(args, c->args)
{ {
@ -1024,7 +1028,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
{ {
case 1: case 1:
{ {
char *name = strVal(lfirst(cref->fields)); char *name = strVal(linitial(cref->fields));
/* Try to identify as an unqualified column */ /* Try to identify as an unqualified column */
node = colNameToVar(pstate, name, false); node = colNameToVar(pstate, name, false);
@ -1070,7 +1074,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
} }
case 2: case 2:
{ {
char *name1 = strVal(lfirst(cref->fields)); char *name1 = strVal(linitial(cref->fields));
char *name2 = strVal(lsecond(cref->fields)); char *name2 = strVal(lsecond(cref->fields));
/* Whole-row reference? */ /* Whole-row reference? */
@ -1099,7 +1103,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
} }
case 3: case 3:
{ {
char *name1 = strVal(lfirst(cref->fields)); char *name1 = strVal(linitial(cref->fields));
char *name2 = strVal(lsecond(cref->fields)); char *name2 = strVal(lsecond(cref->fields));
char *name3 = strVal(lthird(cref->fields)); char *name3 = strVal(lthird(cref->fields));
@ -1125,7 +1129,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
} }
case 4: case 4:
{ {
char *name1 = strVal(lfirst(cref->fields)); char *name1 = strVal(linitial(cref->fields));
char *name2 = strVal(lsecond(cref->fields)); char *name2 = strVal(lsecond(cref->fields));
char *name3 = strVal(lthird(cref->fields)); char *name3 = strVal(lthird(cref->fields));
char *name4 = strVal(lfourth(cref->fields)); char *name4 = strVal(lfourth(cref->fields));
@ -1316,7 +1320,7 @@ exprType(Node *expr)
if (!qtree || !IsA(qtree, Query)) if (!qtree || !IsA(qtree, Query))
elog(ERROR, "cannot get type for untransformed sublink"); elog(ERROR, "cannot get type for untransformed sublink");
tent = (TargetEntry *) lfirst(qtree->targetList); tent = (TargetEntry *) linitial(qtree->targetList);
Assert(IsA(tent, TargetEntry)); Assert(IsA(tent, TargetEntry));
Assert(!tent->resdom->resjunk); Assert(!tent->resdom->resjunk);
if (sublink->subLinkType == EXPR_SUBLINK) if (sublink->subLinkType == EXPR_SUBLINK)
@ -1355,7 +1359,7 @@ exprType(Node *expr)
/* get the type of the subselect's first target column */ /* get the type of the subselect's first target column */
TargetEntry *tent; TargetEntry *tent;
tent = (TargetEntry *) lfirst(subplan->plan->targetlist); tent = (TargetEntry *) linitial(subplan->plan->targetlist);
Assert(IsA(tent, TargetEntry)); Assert(IsA(tent, TargetEntry));
Assert(!tent->resdom->resjunk); Assert(!tent->resdom->resjunk);
if (subplan->subLinkType == EXPR_SUBLINK) if (subplan->subLinkType == EXPR_SUBLINK)
@ -1403,7 +1407,7 @@ exprType(Node *expr)
type = ((CoalesceExpr *) expr)->coalescetype; type = ((CoalesceExpr *) expr)->coalescetype;
break; break;
case T_NullIfExpr: case T_NullIfExpr:
type = exprType((Node *) lfirst(((NullIfExpr *) expr)->args)); type = exprType((Node *) linitial(((NullIfExpr *) expr)->args));
break; break;
case T_NullTest: case T_NullTest:
type = BOOLOID; type = BOOLOID;
@ -1481,7 +1485,7 @@ exprTypmod(Node *expr)
CaseExpr *cexpr = (CaseExpr *) expr; CaseExpr *cexpr = (CaseExpr *) expr;
Oid casetype = cexpr->casetype; Oid casetype = cexpr->casetype;
int32 typmod; int32 typmod;
List *arg; ListCell *arg;
if (!cexpr->defresult) if (!cexpr->defresult)
return -1; return -1;
@ -1514,9 +1518,9 @@ exprTypmod(Node *expr)
CoalesceExpr *cexpr = (CoalesceExpr *) expr; CoalesceExpr *cexpr = (CoalesceExpr *) expr;
Oid coalescetype = cexpr->coalescetype; Oid coalescetype = cexpr->coalescetype;
int32 typmod; int32 typmod;
List *arg; ListCell *arg;
typmod = exprTypmod((Node *) lfirst(cexpr->args)); typmod = exprTypmod((Node *) linitial(cexpr->args));
foreach(arg, cexpr->args) foreach(arg, cexpr->args)
{ {
Node *e = (Node *) lfirst(arg); Node *e = (Node *) lfirst(arg);
@ -1533,7 +1537,7 @@ exprTypmod(Node *expr)
{ {
NullIfExpr *nexpr = (NullIfExpr *) expr; NullIfExpr *nexpr = (NullIfExpr *) expr;
return exprTypmod((Node *) lfirst(nexpr->args)); return exprTypmod((Node *) linitial(nexpr->args));
} }
break; break;
case T_CoerceToDomain: case T_CoerceToDomain:
@ -1644,8 +1648,8 @@ make_row_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree)
*rrow; *rrow;
List *largs, List *largs,
*rargs; *rargs;
List *largl, ListCell *l,
*rargl; *r;
char *oprname; char *oprname;
BoolExprType boolop; BoolExprType boolop;
@ -1690,15 +1694,12 @@ make_row_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree)
boolop = 0; /* keep compiler quiet */ boolop = 0; /* keep compiler quiet */
} }
/* XXX use forboth */ forboth(l, largs, r, rargs)
rargl = rargs;
foreach(largl, largs)
{ {
Node *larg = (Node *) lfirst(largl); Node *larg = (Node *) lfirst(l);
Node *rarg = (Node *) lfirst(rargl); Node *rarg = (Node *) lfirst(r);
Node *cmp; Node *cmp;
rargl = lnext(rargl);
cmp = (Node *) make_op(pstate, opname, larg, rarg); cmp = (Node *) make_op(pstate, opname, larg, rarg);
cmp = coerce_to_boolean(pstate, cmp, "row comparison"); cmp = coerce_to_boolean(pstate, cmp, "row comparison");
if (result == NULL) if (result == NULL)
@ -1732,8 +1733,8 @@ make_row_distinct_op(ParseState *pstate, List *opname,
*rrow; *rrow;
List *largs, List *largs,
*rargs; *rargs;
List *largl, ListCell *l,
*rargl; *r;
/* Inputs are untransformed RowExprs */ /* Inputs are untransformed RowExprs */
lrow = (RowExpr *) transformExpr(pstate, ltree); lrow = (RowExpr *) transformExpr(pstate, ltree);
@ -1748,15 +1749,12 @@ make_row_distinct_op(ParseState *pstate, List *opname,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("unequal number of entries in row expression"))); errmsg("unequal number of entries in row expression")));
/* XXX use forboth */ forboth(l, largs, r, rargs)
rargl = rargs;
foreach(largl, largs)
{ {
Node *larg = (Node *) lfirst(largl); Node *larg = (Node *) lfirst(l);
Node *rarg = (Node *) lfirst(rargl); Node *rarg = (Node *) lfirst(r);
Node *cmp; Node *cmp;
rargl = lnext(rargl);
cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg); cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg);
if (result == NULL) if (result == NULL)
result = cmp; result = cmp;

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/parse_func.c,v 1.168 2004/04/02 21:30:44 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/parse_func.c,v 1.169 2004/05/26 04:41:30 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -67,7 +67,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
{ {
Oid rettype; Oid rettype;
Oid funcid; Oid funcid;
List *i; ListCell *l;
Node *first_arg = NULL; Node *first_arg = NULL;
int nargs = length(fargs); int nargs = length(fargs);
int argn; int argn;
@ -91,7 +91,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
if (fargs) if (fargs)
{ {
first_arg = lfirst(fargs); first_arg = linitial(fargs);
Assert(first_arg != NULL); Assert(first_arg != NULL);
} }
@ -108,7 +108,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
if (argtype == RECORDOID || ISCOMPLEX(argtype)) if (argtype == RECORDOID || ISCOMPLEX(argtype))
{ {
retval = ParseComplexProjection(pstate, retval = ParseComplexProjection(pstate,
strVal(lfirst(funcname)), strVal(linitial(funcname)),
first_arg); first_arg);
if (retval) if (retval)
return retval; return retval;
@ -126,9 +126,9 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
MemSet(actual_arg_types, 0, FUNC_MAX_ARGS * sizeof(Oid)); MemSet(actual_arg_types, 0, FUNC_MAX_ARGS * sizeof(Oid));
argn = 0; argn = 0;
foreach(i, fargs) foreach(l, fargs)
{ {
Node *arg = lfirst(i); Node *arg = lfirst(l);
actual_arg_types[argn++] = exprType(arg); actual_arg_types[argn++] = exprType(arg);
} }
@ -149,8 +149,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
* We can do it as a trivial coercion. coerce_type can handle * We can do it as a trivial coercion. coerce_type can handle
* these cases, so why duplicate code... * these cases, so why duplicate code...
*/ */
return coerce_type(pstate, lfirst(fargs), actual_arg_types[0], return coerce_type(pstate, linitial(fargs),
rettype, actual_arg_types[0], rettype,
COERCION_EXPLICIT, COERCE_EXPLICIT_CALL); COERCION_EXPLICIT, COERCE_EXPLICIT_CALL);
} }
else if (fdresult == FUNCDETAIL_NORMAL) else if (fdresult == FUNCDETAIL_NORMAL)
@ -183,7 +183,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
{ {
Assert(nargs == 1); Assert(nargs == 1);
Assert(length(funcname) == 1); Assert(length(funcname) == 1);
unknown_attribute(pstate, first_arg, strVal(lfirst(funcname))); unknown_attribute(pstate, first_arg, strVal(linitial(funcname)));
} }
/* /*
@ -240,7 +240,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
aggref->aggfnoid = funcid; aggref->aggfnoid = funcid;
aggref->aggtype = rettype; aggref->aggtype = rettype;
aggref->target = lfirst(fargs); aggref->target = linitial(fargs);
aggref->aggstar = agg_star; aggref->aggstar = agg_star;
aggref->aggdistinct = agg_distinct; aggref->aggdistinct = agg_distinct;
@ -725,7 +725,7 @@ func_get_detail(List *funcname,
!ISCOMPLEX(targetType)) !ISCOMPLEX(targetType))
{ {
Oid sourceType = argtypes[0]; Oid sourceType = argtypes[0];
Node *arg1 = lfirst(fargs); Node *arg1 = linitial(fargs);
if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) || if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) ||
(find_coercion_pathway(targetType, sourceType, (find_coercion_pathway(targetType, sourceType,
@ -896,37 +896,51 @@ static int
find_inheritors(Oid relid, Oid **supervec) find_inheritors(Oid relid, Oid **supervec)
{ {
Relation inhrel; Relation inhrel;
HeapScanDesc inhscan;
ScanKeyData skey;
HeapTuple inhtup;
Oid *relidvec;
int nvisited; int nvisited;
List *visited, List *visited,
*queue; *queue;
List *elt; ListCell *queue_item;
bool newrelid;
nvisited = 0; /*
queue = NIL; * Begin the search at the relation itself, so add relid to the
* queue.
*/
queue = list_make1_oid(relid);
visited = NIL; visited = NIL;
inhrel = heap_openr(InheritsRelationName, AccessShareLock); inhrel = heap_openr(InheritsRelationName, AccessShareLock);
/* /*
* Use queue to do a breadth-first traversal of the inheritance graph * Use queue to do a breadth-first traversal of the inheritance
* from the relid supplied up to the root. At the top of the loop, * graph from the relid supplied up to the root. Notice that we
* relid is the OID of the reltype to check next, queue is the list of * append to the queue inside the loop --- this is okay because
* pending relids to check after this one, and visited is the list of * the foreach() macro doesn't advance queue_item until the next
* relids we need to output. * loop iteration begins.
*/ */
do foreach(queue_item, queue)
{ {
/* find all types this relid inherits from, and add them to queue */ Oid this_relid = lfirst_oid(queue_item);
ScanKeyData skey;
HeapScanDesc inhscan;
HeapTuple inhtup;
/* If we've seen this relid already, skip it */
if (list_member_oid(visited, this_relid))
continue;
/*
* Okay, this is a not-yet-seen relid. Add it to the list of
* already-visited OIDs, then find all the types this relid
* inherits from and add them to the queue. The one exception
* is we don't add the original relation to 'visited'.
*/
if (queue_item != list_head(queue))
visited = lappend_oid(visited, this_relid);
ScanKeyInit(&skey, ScanKeyInit(&skey,
Anum_pg_inherits_inhrelid, Anum_pg_inherits_inhrelid,
BTEqualStrategyNumber, F_OIDEQ, BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relid)); ObjectIdGetDatum(this_relid));
inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey); inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey);
@ -934,54 +948,34 @@ find_inheritors(Oid relid, Oid **supervec)
{ {
Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup); Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup);
queue = lappendo(queue, inh->inhparent); queue = lappend_oid(queue, inh->inhparent);
} }
heap_endscan(inhscan); heap_endscan(inhscan);
/* pull next unvisited relid off the queue */
newrelid = false;
while (queue != NIL)
{
relid = lfirsto(queue);
queue = lnext(queue);
if (!oidMember(relid, visited))
{
newrelid = true;
break;
} }
}
if (newrelid)
{
visited = lappendo(visited, relid);
nvisited++;
}
} while (newrelid);
heap_close(inhrel, AccessShareLock); heap_close(inhrel, AccessShareLock);
nvisited = list_length(visited);
if (nvisited > 0) if (nvisited > 0)
{ {
relidvec = (Oid *) palloc(nvisited * sizeof(Oid)); Oid *relidvec;
ListCell *l;
relidvec = (Oid *) palloc(nvisited * sizeof(*relidvec));
*supervec = relidvec; *supervec = relidvec;
foreach(elt, visited) foreach(l, visited)
{ {
/* return the type id, rather than the relation id */ /* return the type id, rather than the relation id */
*relidvec++ = get_rel_type_id(lfirsto(elt)); *relidvec++ = get_rel_type_id(lfirst_oid(l));
} }
} }
else else
*supervec = NULL; *supervec = NULL;
freeList(visited); freeList(visited);
freeList(queue);
/*
* there doesn't seem to be any equally easy way to release the queue
* list cells, but since they're palloc'd space it's not critical.
*/
return nvisited; return nvisited;
} }
@ -1117,7 +1111,7 @@ make_fn_arguments(ParseState *pstate,
Oid *actual_arg_types, Oid *actual_arg_types,
Oid *declared_arg_types) Oid *declared_arg_types)
{ {
List *current_fargs; ListCell *current_fargs;
int i = 0; int i = 0;
foreach(current_fargs, fargs) foreach(current_fargs, fargs)
@ -1403,6 +1397,7 @@ LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
Oid argoids[FUNC_MAX_ARGS]; Oid argoids[FUNC_MAX_ARGS];
int argcount; int argcount;
int i; int i;
ListCell *args_item;
MemSet(argoids, 0, FUNC_MAX_ARGS * sizeof(Oid)); MemSet(argoids, 0, FUNC_MAX_ARGS * sizeof(Oid));
argcount = length(argtypes); argcount = length(argtypes);
@ -1412,9 +1407,10 @@ LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
errmsg("functions cannot have more than %d arguments", errmsg("functions cannot have more than %d arguments",
FUNC_MAX_ARGS))); FUNC_MAX_ARGS)));
args_item = list_head(argtypes);
for (i = 0; i < argcount; i++) for (i = 0; i < argcount; i++)
{ {
TypeName *t = (TypeName *) lfirst(argtypes); TypeName *t = (TypeName *) lfirst(args_item);
argoids[i] = LookupTypeName(t); argoids[i] = LookupTypeName(t);
@ -1424,7 +1420,7 @@ LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
errmsg("type \"%s\" does not exist", errmsg("type \"%s\" does not exist",
TypeNameToString(t)))); TypeNameToString(t))));
argtypes = lnext(argtypes); args_item = lnext(args_item);
} }
return LookupFuncName(funcname, argcount, argoids, noError); return LookupFuncName(funcname, argcount, argoids, noError);

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/parse_node.c,v 1.82 2003/11/29 19:51:52 pgsql Exp $ * $PostgreSQL: pgsql/src/backend/parser/parse_node.c,v 1.83 2004/05/26 04:41:30 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -106,7 +106,7 @@ transformArraySubscripts(ParseState *pstate,
bool isSlice = forceSlice; bool isSlice = forceSlice;
List *upperIndexpr = NIL; List *upperIndexpr = NIL;
List *lowerIndexpr = NIL; List *lowerIndexpr = NIL;
List *idx; ListCell *idx;
ArrayRef *aref; ArrayRef *aref;
/* Get the type tuple for the array */ /* Get the type tuple for the array */

View File

@ -8,7 +8,7 @@
* *
* *
* IDENTIFICATION * IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/parse_relation.c,v 1.94 2004/04/18 18:12:58 tgl Exp $ * $PostgreSQL: pgsql/src/backend/parser/parse_relation.c,v 1.95 2004/05/26 04:41:30 neilc Exp $
* *
*------------------------------------------------------------------------- *-------------------------------------------------------------------------
*/ */
@ -174,7 +174,7 @@ scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
} }
else if (IsA(nsnode, List)) else if (IsA(nsnode, List))
{ {
List *l; ListCell *l;
foreach(l, (List *) nsnode) foreach(l, (List *) nsnode)
{ {
@ -249,7 +249,7 @@ scanNameSpaceForRelid(ParseState *pstate, Node *nsnode, Oid relid)
} }
else if (IsA(nsnode, List)) else if (IsA(nsnode, List))
{ {
List *l; ListCell *l;
foreach(l, (List *) nsnode) foreach(l, (List *) nsnode)
{ {
@ -321,7 +321,7 @@ checkNameSpaceConflicts(ParseState *pstate, Node *namespace1,
} }
else if (IsA(namespace1, List)) else if (IsA(namespace1, List))
{ {
List *l; ListCell *l;
foreach(l, (List *) namespace1) foreach(l, (List *) namespace1)
checkNameSpaceConflicts(pstate, lfirst(l), namespace2); checkNameSpaceConflicts(pstate, lfirst(l), namespace2);
@ -378,7 +378,7 @@ scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
} }
else if (IsA(nsnode, List)) else if (IsA(nsnode, List))
{ {
List *l; ListCell *l;
foreach(l, (List *) nsnode) foreach(l, (List *) nsnode)
scanNameSpaceForConflict(pstate, lfirst(l), rte1, aliasname1); scanNameSpaceForConflict(pstate, lfirst(l), rte1, aliasname1);
@ -397,7 +397,7 @@ int
RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up) RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
{ {
int index; int index;
List *temp; ListCell *l;
if (sublevels_up) if (sublevels_up)
*sublevels_up = 0; *sublevels_up = 0;
@ -405,9 +405,9 @@ RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
while (pstate != NULL) while (pstate != NULL)
{ {
index = 1; index = 1;
foreach(temp, pstate->p_rtable) foreach(l, pstate->p_rtable)
{ {
if (rte == (RangeTblEntry *) lfirst(temp)) if (rte == (RangeTblEntry *) lfirst(l))
return index; return index;
index++; index++;
} }
@ -460,7 +460,7 @@ scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname)
{ {
Node *result = NULL; Node *result = NULL;
int attnum = 0; int attnum = 0;
List *c; ListCell *c;
/* /*
* Scan the user column names (or aliases) for a match. Complain if * Scan the user column names (or aliases) for a match. Complain if
@ -546,7 +546,7 @@ colNameToVar(ParseState *pstate, char *colname, bool localonly)
while (pstate != NULL) while (pstate != NULL)
{ {
List *ns; ListCell *ns;
/* /*
* We need to look only at top-level namespace items, and even for * We need to look only at top-level namespace items, and even for
@ -841,7 +841,7 @@ addRangeTableEntryForSubquery(ParseState *pstate,
Alias *eref; Alias *eref;
int numaliases; int numaliases;
int varattno; int varattno;
List *tlistitem; ListCell *tlistitem;
rte->rtekind = RTE_SUBQUERY; rte->rtekind = RTE_SUBQUERY;
rte->relid = InvalidOid; rte->relid = InvalidOid;
@ -1027,7 +1027,7 @@ addRangeTableEntryForFunction(ParseState *pstate,
} }
else if (functyptype == 'p' && funcrettype == RECORDOID) else if (functyptype == 'p' && funcrettype == RECORDOID)
{ {
List *col; ListCell *col;
/* Use the column definition list to form the alias list */ /* Use the column definition list to form the alias list */
eref->colnames = NIL; eref->colnames = NIL;
@ -1101,11 +1101,8 @@ addRangeTableEntryForJoin(ParseState *pstate,
/* fill in any unspecified alias columns */ /* fill in any unspecified alias columns */
if (numaliases < length(colnames)) if (numaliases < length(colnames))
{ eref->colnames = nconc(eref->colnames,
while (numaliases-- > 0) list_copy_tail(colnames, numaliases));
colnames = lnext(colnames);
eref->colnames = nconc(eref->colnames, colnames);
}
rte->eref = eref; rte->eref = eref;
@ -1145,7 +1142,7 @@ isForUpdate(ParseState *pstate, char *refname)
{ {
if (pstate->p_forUpdate != NIL) if (pstate->p_forUpdate != NIL)
{ {
if (lfirst(pstate->p_forUpdate) == NULL) if (linitial(pstate->p_forUpdate) == NULL)
{ {
/* all tables used in query */ /* all tables used in query */
return true; return true;
@ -1153,7 +1150,7 @@ isForUpdate(ParseState *pstate, char *refname)
else else
{ {
/* just the named tables */ /* just the named tables */
List *l; ListCell *l;
foreach(l, pstate->p_forUpdate) foreach(l, pstate->p_forUpdate)
{ {
@ -1282,8 +1279,8 @@ expandRTE(ParseState *pstate, RangeTblEntry *rte,
case RTE_SUBQUERY: case RTE_SUBQUERY:
{ {
/* Subquery RTE */ /* Subquery RTE */
List *aliasp = rte->eref->colnames; ListCell *aliasp_item = list_head(rte->eref->colnames);
List *tlistitem; ListCell *tlistitem;
varattno = 0; varattno = 0;
foreach(tlistitem, rte->subquery->targetList) foreach(tlistitem, rte->subquery->targetList)
@ -1298,10 +1295,10 @@ expandRTE(ParseState *pstate, RangeTblEntry *rte,
if (colnames) if (colnames)
{ {
/* Assume there is one alias per target item */ /* Assume there is one alias per target item */
char *label = strVal(lfirst(aliasp)); char *label = strVal(lfirst(aliasp_item));
*colnames = lappend(*colnames, makeString(pstrdup(label))); *colnames = lappend(*colnames, makeString(pstrdup(label)));
aliasp = lnext(aliasp); aliasp_item = lnext(aliasp_item);
} }
if (colvars) if (colvars)
@ -1385,7 +1382,7 @@ expandRTE(ParseState *pstate, RangeTblEntry *rte,
*/ */
if (colnames) if (colnames)
*colnames = lappend(*colnames, *colnames = lappend(*colnames,
lfirst(rte->eref->colnames)); linitial(rte->eref->colnames));
if (colvars) if (colvars)
{ {
@ -1400,7 +1397,7 @@ expandRTE(ParseState *pstate, RangeTblEntry *rte,
} }
else if (functyptype == 'p' && funcrettype == RECORDOID) else if (functyptype == 'p' && funcrettype == RECORDOID)
{ {
List *col; ListCell *col;
int attnum = 0; int attnum = 0;
foreach(col, coldeflist) foreach(col, coldeflist)
@ -1442,39 +1439,36 @@ expandRTE(ParseState *pstate, RangeTblEntry *rte,
case RTE_JOIN: case RTE_JOIN:
{ {
/* Join RTE */ /* Join RTE */
List *aliasp = rte->eref->colnames; ListCell *colname;
List *aliasvars = rte->joinaliasvars; ListCell *aliasvar;
Assert(length(rte->eref->colnames) == length(rte->joinaliasvars));
varattno = 0; varattno = 0;
while (aliasp) forboth (colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
{ {
Assert(aliasvars);
varattno++; varattno++;
if (colnames) if (colnames)
{ {
char *label = strVal(lfirst(aliasp)); char *label = strVal(lfirst(colname));
*colnames = lappend(*colnames, makeString(pstrdup(label))); *colnames = lappend(*colnames, makeString(pstrdup(label)));
} }
if (colvars) if (colvars)
{ {
Node *aliasvar = (Node *) lfirst(aliasvars); Node *avar = (Node *) lfirst(aliasvar);
Var *varnode; Var *varnode;
varnode = makeVar(rtindex, varattno, varnode = makeVar(rtindex, varattno,
exprType(aliasvar), exprType(avar),
exprTypmod(aliasvar), exprTypmod(avar),
sublevels_up); sublevels_up);
*colvars = lappend(*colvars, varnode); *colvars = lappend(*colvars, varnode);
} }
aliasp = lnext(aliasp);
aliasvars = lnext(aliasvars);
} }
Assert(aliasvars == NIL);
} }
break; break;
default: default:
@ -1492,14 +1486,16 @@ expandRelAttrs(ParseState *pstate, RangeTblEntry *rte)
{ {
List *names, List *names,
*vars; *vars;
ListCell *name,
*var;
List *te_list = NIL; List *te_list = NIL;
expandRTE(pstate, rte, &names, &vars); expandRTE(pstate, rte, &names, &vars);
while (names) forboth (name, names, var, vars)
{ {
char *label = strVal(lfirst(names)); char *label = strVal(lfirst(name));
Node *varnode = (Node *) lfirst(vars); Node *varnode = (Node *) lfirst(var);
TargetEntry *te = makeNode(TargetEntry); TargetEntry *te = makeNode(TargetEntry);
te->resdom = makeResdom((AttrNumber) pstate->p_next_resno++, te->resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
@ -1509,12 +1505,9 @@ expandRelAttrs(ParseState *pstate, RangeTblEntry *rte)
false); false);
te->expr = (Expr *) varnode; te->expr = (Expr *) varnode;
te_list = lappend(te_list, te); te_list = lappend(te_list, te);
names = lnext(names);
vars = lnext(vars);
} }
Assert(vars == NIL); /* lists not same length? */ Assert(name == NULL && var == NULL); /* lists not the same length? */
return te_list; return te_list;
} }
@ -1790,11 +1783,11 @@ get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
TargetEntry * TargetEntry *
get_tle_by_resno(List *tlist, AttrNumber resno) get_tle_by_resno(List *tlist, AttrNumber resno)
{ {
List *i; ListCell *l;
foreach(i, tlist) foreach(l, tlist)
{ {
TargetEntry *tle = (TargetEntry *) lfirst(i); TargetEntry *tle = (TargetEntry *) lfirst(l);
if (tle->resdom->resno == resno) if (tle->resdom->resno == resno)
return tle; return tle;
@ -1917,7 +1910,7 @@ static void
warnAutoRange(ParseState *pstate, RangeVar *relation) warnAutoRange(ParseState *pstate, RangeVar *relation)
{ {
bool foundInFromCl = false; bool foundInFromCl = false;
List *temp; ListCell *temp;
if (!add_missing_from) if (!add_missing_from)
{ {

Some files were not shown because too many files have changed in this diff Show More