--- pgsql-clean//src/bin/psql/command.c	2003-05-23 22:34:41.000000000 +1000
+++ pgsql5/src/bin/psql/command.c	2003-08-18 01:34:05.000000000 +1000
@@ -65,6 +65,7 @@
 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf);
 static bool do_connect(const char *new_dbname, const char *new_user);
 static bool do_shell(const char *command);
+static bool do_foreach(const char *arg, PQExpBuffer query_buf);
 
 /*----------
  * HandleSlashCmds:
@@ -475,7 +476,19 @@
 			free(encoding);
 		}
 	}
-
+	
+	/* \for -- Execute query multiple times with substitution */
+	else if (strcmp(cmd, "for") == 0)
+	{
+		/* query_buf = query buffer
+		   string = query to get options */
+		success = do_foreach( string, query_buf );
+		/* Clear query buffer */
+		resetPQExpBuffer(query_buf);
+		/* Mark rest of string as parsed */
+		string += strlen( string );
+	}
+	
 	/* \f -- change field separator */
 	else if (strcmp(cmd, "f") == 0)
 	{
@@ -1960,3 +1973,55 @@
 	}
 	return true;
 }
+
+/* Implement the \for command */
+static bool
+do_foreach(const char *arg, PQExpBuffer query_buf)
+{
+	/* arg is the query that gives the arguments, query_buf is the string to be looped */
+	PGresult   *res;
+	int ntuples, i;
+
+	/* Execute the outer query */
+	res = PSQLexec(arg, false);
+	if (!res)
+		return false;
+	
+	ntuples = PQntuples( res );
+	
+	for( i=0; i<ntuples; i++ )
+	{
+		PQExpBufferData buf;
+		char *ptr = query_buf->data;
+		char *ptr2;
+		
+		/* Perform substitution */
+		initPQExpBuffer(&buf);
+		while( (ptr2 = strchr( ptr, ':' )) != NULL )
+		{
+			int fieldnum;
+			
+			/* Not really binary, but we can choose the number of bytes */
+			appendBinaryPQExpBuffer( &buf, ptr, ptr2 - ptr );
+			ptr = ptr2;
+			fieldnum = strtol( ptr2+1, &ptr2, 10 );
+			
+			/* Only expand numbers that are in range, we don't want to expand the wrong thing */
+			if( ptr2 != ptr+1 && fieldnum > 0 && fieldnum <= PQnfields( res ) )
+			{
+				appendPQExpBuffer( &buf, "%s", PQgetvalue( res, i, fieldnum-1 ) );
+				ptr = ptr2;
+			}
+			else  /* Invalid field */
+			{
+				appendPQExpBufferChar( &buf, ':' );
+				ptr++;
+			}
+		}
+		appendPQExpBuffer( &buf, "%s", ptr );
+		/* Later well have to execute the expanded query */
+		printf( "Expanded to: %s\n", buf.data );
+		termPQExpBuffer( &buf );
+	}
+	return true;
+}
