parallel-incremental-sort-v2.patch

text/plain

Filename: parallel-incremental-sort-v2.patch
Type: text/plain
Part: 0
Message: Re: [PATCH] Incremental sort (was: PoC: Partial sort)

Patch

Format: unified
Series: patch v2
File+
src/backend/optimizer/path/allpaths.c 22 0
src/backend/optimizer/path/costsize.c 2 10
diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index 3efc807164..d7bf33f64d 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -2719,6 +2719,8 @@ generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
 	{
 		Path	   *subpath = (Path *) lfirst(lc);
 		GatherMergePath *path;
+		bool		is_sorted;
+		int			presorted_keys;
 
 		if (subpath->pathkeys == NIL)
 			continue;
@@ -2727,6 +2729,26 @@ generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
 		path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
 										subpath->pathkeys, NULL, rowsp);
 		add_path(rel, &path->path);
+
+		/* consider incremental sort */
+		is_sorted = pathkeys_common_contained_in(root->sort_pathkeys,
+												 subpath->pathkeys, &presorted_keys);
+
+		if (!is_sorted && (presorted_keys > 0))
+		{
+			/* Also consider incremental sort. */
+			subpath = (Path *) create_incremental_sort_path(root,
+															rel,
+															subpath,
+															root->sort_pathkeys,
+															presorted_keys,
+															-1);
+
+			path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
+											subpath->pathkeys, NULL, rowsp);
+
+			add_path(rel, &path->path);
+		}
 	}
 }
 
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index 7f820e7351..c6aa17ba67 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -1875,16 +1875,8 @@ cost_incremental_sort(Path *path,
 				   limit_tuples);
 
 	/* If we have a LIMIT, adjust the number of groups we'll have to return. */
-	if (limit_tuples > 0 && limit_tuples < input_tuples)
-	{
-		output_tuples = limit_tuples;
-		output_groups = floor(output_tuples / group_tuples) + 1;
-	}
-	else
-	{
-		output_tuples = input_tuples;
-		output_groups = input_groups;
-	}
+	output_tuples = input_tuples;
+	output_groups = input_groups;
 
 	/*
 	 * Startup cost of incremental sort is the startup cost of its first group