270a271,272
> void _PG_init(void);
> 
372a375
> static void prefetch_more_data(ForeignScanState *node);
425a429,430
> static bool fdw_prefetch_data;
> 
1377a1383,1387
> 	create_cursor(node);
> 	if (fdw_prefetch_data)
> 	{
> 		prefetch_more_data(node);
> 	}
2989a3000,3010
> static void
> prefetch_more_data(ForeignScanState *node)
> {
> 	PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
> 	char		sql[64];
> 	snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
> 			 fsstate->fetch_size, fsstate->cursor_number);
> 	if (!PQsendQuery(fsstate->conn, sql))
> 		pgfdw_report_error(ERROR, NULL, fsstate->conn, false, sql);
> }
> 
3019c3040,3042
< 		res = pgfdw_exec_query(conn, sql);
---
> 		res = fdw_prefetch_data
> 			? pgfdw_get_result(conn, sql)
> 			: pgfdw_exec_query(conn, sql);
3049d3071
< 
3051a3074,3075
> 		if (!fsstate->eof_reached)
> 			prefetch_more_data(node);
4836a4861,4879
> 
> static bool
> contains_complex_aggregate(Node *node, void *context)
> {
> 	if (node == NULL)
> 		return false;
> 
> 	if (IsA(node, Aggref))
> 	{
> 		Aggref* agg = (Aggref*)node;
> 		return agg->aggtranstype != agg->aggtype;
> 	}
> 
> 	return expression_tree_walker(node,
> 								  contains_complex_aggregate,
> 								  context);
> }
> 
> 
4866c4909
< 		if (extra->isPartial)
---
> 		if (extra->isPartial && expression_tree_walker((Node*)extra->pathTarget->exprs, contains_complex_aggregate, NULL))
5190a5234,5246
> }
> 
> void _PG_init(void)
> {
> 	DefineCustomBoolVariable(
> 		"postgres_fdw.use_prefetch",
> 		"Prefetch data from cursor",
> 		NULL,
> 		&fdw_prefetch_data,
> 		false,
> 		PGC_SUSET,
> 		0,
> 		NULL, NULL, NULL);
