From bbe40c94e2293849d977da4720ef76d13160347a Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@2ndquadrant.com>
Date: Wed, 15 Feb 2023 17:32:53 +0100
Subject: [PATCH 01/10] Fix handling of multi-column BRIN indexes

When evaluating clauses on multiple keys of multi-column BRIN indexes,
the results should be combined using AND, and we can stop evaluating
once we find a mismatching scan key.

The existing code was simply scanning a range as long as the last batch
of scan keys returned true.
---
 src/backend/access/brin/brin.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index de1427a1e0..85ae795949 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -660,7 +660,7 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 												PointerGetDatum(bval),
 												PointerGetDatum(keys[attno - 1]),
 												Int32GetDatum(nkeys[attno - 1]));
-						addrange = DatumGetBool(add);
+						addrange &= DatumGetBool(add);
 					}
 					else
 					{
@@ -681,11 +681,18 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 													PointerGetDatum(bdesc),
 													PointerGetDatum(bval),
 													PointerGetDatum(keys[attno - 1][keyno]));
-							addrange = DatumGetBool(add);
+							addrange &= DatumGetBool(add);
 							if (!addrange)
 								break;
 						}
 					}
+
+					/*
+					 * We found a clause that eliminates this range. No point
+					 * in evaluating more clauses.
+					 */
+					if (!addrange)
+						break;
 				}
 			}
 		}
-- 
2.39.1

