/* * pg_brin_bins.c * BRIN operator classes storing a bitmap of value bins * * Copyright (c) 2026, Takeshi Ideriha * * The bins operator classes split the value domain of the indexed column into * BINS_NBINS bins and record, with one bit per bin, which bins contain * at least one value within each block range. This is based on the idea of * column imprints (Sidirourgos and Kersten, "Column Imprints: A Secondary * Index Structure", SIGMOD 2013). */ #include "postgres.h" #include #include "access/brin_internal.h" #include "access/brin_tuple.h" #include "access/reloptions.h" #include "access/stratnum.h" #include "catalog/pg_amop.h" #include "catalog/pg_type.h" #include "utils/builtins.h" #include "utils/date.h" #include "fmgr.h" #include "utils/lsyscache.h" #include "utils/rel.h" #include "utils/syscache.h" #include "utils/timestamp.h" PG_MODULE_MAGIC; #define BINS_NBINS 64 #define BINS_NBOUNDS (BINS_NBINS - 1) #define MIN_BOUNDARY_DEFAULT 0 #define MAX_BOUNDARY_DEFAULT 0 typedef struct BinsOpaque { Oid cached_subtype; FmgrInfo strategy_procinfos[BTMaxStrategyNumber]; Datum bin_upper_bounds[BINS_NBOUNDS]; /* upper bound (exclusive) of bins */ } BinsOpaque; /* * BRIN bins reloptions */ typedef struct BinsOptions { int32 vl_len_; /* varlena header (do not touch directly!) */ double minBoundaryValue; /* min boundary for bins */ double maxBoundaryValue; /* max boundary for bins */ } BinsOptions; static Datum bins_double_to_datum(Oid typoid, double value); static FmgrInfo *bins_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype, uint16 strategynum); static int bins_get_binno(Datum val, Datum *bin_upper_bounds, FmgrInfo *cmpGreaterFn, Oid colloid); PG_FUNCTION_INFO_V1(brin_bins_opcinfo); /* * Build BrinOpcInfo * We check reloptions here as well. brin_bins_opcinfo is called at BrinDesc * is build including index creation time. This would be the suitable time for * option check. */ Datum brin_bins_opcinfo(PG_FUNCTION_ARGS) { Oid typoid = PG_GETARG_OID(0); /* column type */ BrinOpcInfo *result; BinsOpaque *opaque; BinsOptions *opts = (BinsOptions *) PG_GET_OPCLASS_OPTIONS(); double width; int i; if (opts->minBoundaryValue == MIN_BOUNDARY_DEFAULT && opts->maxBoundaryValue == MAX_BOUNDARY_DEFAULT) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("min_boundary_value and max_boundary_value must be " "specified"))); if (opts->minBoundaryValue >= opts->maxBoundaryValue) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("min_boundary_value must be less than max_boundary_value"))); /* * opaque->strategy_procinfos is initialized lazily; here it is set to * all-uninitialized by palloc0 which sets fn_oid to InvalidOid. */ result = palloc0(MAXALIGN(SizeofBrinOpcInfo(1)) + sizeof(BinsOpaque)); result->oi_nstored = 1; result->oi_regular_nulls = true; result->oi_opaque = (BinsOpaque *) MAXALIGN((char *) result + SizeofBrinOpcInfo(1)); result->oi_typcache[0] = lookup_type_cache(INT8OID, 0); /* * Bin 0 holds values below minBoundaryValue, bin 63 values at or above * maxBoundaryValue, and the other bins in between [minBoundaryValue, * maxBoundaryValue) into equal width. * bin_upper_bounds[i] is the (exclusive) upper bound of bin i. */ width = (opts->maxBoundaryValue - opts->minBoundaryValue) / (BINS_NBOUNDS - 1); opaque = (BinsOpaque *)result->oi_opaque; /* * Convert both ends first so that an out-of-range error reports the * value the user specified. All the inner boundaries lie between them, * so they are within range if both ends are. */ opaque->bin_upper_bounds[0] = bins_double_to_datum(typoid, opts->minBoundaryValue); opaque->bin_upper_bounds[BINS_NBOUNDS - 1] = bins_double_to_datum(typoid, opts->maxBoundaryValue); for (i = 1; i < BINS_NBOUNDS - 1; i++) opaque->bin_upper_bounds[i] = bins_double_to_datum(typoid, opts->minBoundaryValue + width * i); PG_RETURN_POINTER(result); } PG_FUNCTION_INFO_V1(brin_bins_add_value); /* * Find the bin of the given new value and set the corresponding bit in the * summary bitmap. If the bit is already set, the summary does not change, * so return false. Otherwise, update the bitmap and return true. */ Datum brin_bins_add_value(PG_FUNCTION_ARGS) { BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0); BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1); Datum newval = PG_GETARG_DATUM(2); bool isnull PG_USED_FOR_ASSERTS_ONLY = PG_GETARG_BOOL(3); Oid colloid = PG_GET_COLLATION(); FmgrInfo *cmpGreaterFn; Form_pg_attribute attr; AttrNumber attno; int binno; BinsOpaque *opaque; uint64 bitmap; uint64 new_bit; Assert(!isnull); attno = column->bv_attno; attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1); opaque = (BinsOpaque *) bdesc->bd_info[attno - 1]->oi_opaque; cmpGreaterFn = bins_get_strategy_procinfo(bdesc, attno, attr->atttypid, BTGreaterStrategyNumber); binno = bins_get_binno(newval, opaque->bin_upper_bounds, cmpGreaterFn, colloid); new_bit = UINT64CONST(1) << binno; /* If there is no existing index tuple, use a given value as a new tuple */ if (column->bv_allnulls) { column->bv_values[0] = Int64GetDatum((int64) new_bit); column->bv_allnulls = false; PG_RETURN_BOOL(true); } bitmap = (uint64) DatumGetInt64(column->bv_values[0]); if ((bitmap & new_bit) == new_bit) PG_RETURN_BOOL(false); column->bv_values[0] = Int64GetDatum((int64)(bitmap | new_bit)); PG_RETURN_BOOL(true); } PG_FUNCTION_INFO_V1(brin_bins_consistent); /* * Given an index tuple corresponding to a certain page range and a scan key, * return whether the scan key is consistent with the index tuple (bitmap). * Return true if so, false otherwise. * * Each key is converted into a range of bins, and the ranges of all keys are * intersected. */ Datum brin_bins_consistent(PG_FUNCTION_ARGS) { BrinDesc *bdesc = (BrinDesc *) PG_GETARG_POINTER(0); BrinValues *column = (BrinValues *) PG_GETARG_POINTER(1); ScanKey *keys = (ScanKey *) PG_GETARG_POINTER(2); int nkeys = PG_GETARG_INT32(3); Oid colloid = PG_GET_COLLATION(), subtype; AttrNumber attno; Datum value; FmgrInfo *cmpGreaterFn; int keyno; int binno; int bit_width; int low_binno = 0; int high_binno = BINS_NBINS - 1; BinsOpaque *opaque; uint64 scan_bitmap; uint64 bitmap; attno = column->bv_attno; opaque = (BinsOpaque *) bdesc->bd_info[attno - 1]->oi_opaque; /* * Check all ScanKey and turn the keys information into a bitmap * representing the conditions */ for (keyno = 0; keyno < nkeys; keyno++) { ScanKey key = keys[keyno]; /* NULL keys are handled and filtered-out in bringetbitmap */ Assert(!(key->sk_flags & SK_ISNULL)); attno = key->sk_attno; subtype = key->sk_subtype; value = key->sk_argument; cmpGreaterFn = bins_get_strategy_procinfo(bdesc, attno, subtype, BTGreaterStrategyNumber); binno = bins_get_binno(value, opaque->bin_upper_bounds, cmpGreaterFn, colloid); switch (key->sk_strategy) { case BTLessStrategyNumber: case BTLessEqualStrategyNumber: high_binno = Min(high_binno, binno); break; case BTEqualStrategyNumber: low_binno = Max(low_binno, binno); high_binno = Min(high_binno, binno); break; case BTGreaterEqualStrategyNumber: case BTGreaterStrategyNumber: low_binno = Max(low_binno, binno); break; default: /* shouldn't happen */ elog(ERROR, "invalid strategy number %d", key->sk_strategy); break; } } /* * If the conditions are contradictory, no heap tuples should be returned. */ if (low_binno > high_binno) PG_RETURN_BOOL(false); bit_width = high_binno - low_binno + 1; if (bit_width == BINS_NBINS) scan_bitmap = ~UINT64CONST(0); else scan_bitmap = ((UINT64CONST(1) << bit_width) - 1 ) << low_binno; bitmap = (uint64) DatumGetInt64(column->bv_values[0]); if ((scan_bitmap & bitmap) != 0) PG_RETURN_BOOL(true); PG_RETURN_BOOL(false); } PG_FUNCTION_INFO_V1(brin_bins_union); /* * Given two BrinValues, update the first of them as a union of the summary * values contained in both. The second one is untouched. * * Note: BRIN doc says union API should return bool but the caller does not care * the return value and all the other union functions of core BRIN operator * class return void. */ Datum brin_bins_union(PG_FUNCTION_ARGS) { /* we don't use 1st argument (BrinDesc *) */ BrinValues *col_a = (BrinValues *) PG_GETARG_POINTER(1); BrinValues *col_b = (BrinValues *) PG_GETARG_POINTER(2); uint64 bitmap_a; uint64 bitmap_b; Assert(col_a->bv_attno == col_b->bv_attno); Assert(!col_a->bv_allnulls && !col_b->bv_allnulls); bitmap_a = (uint64) DatumGetInt64(col_a->bv_values[0]); bitmap_b = (uint64) DatumGetInt64(col_b->bv_values[0]); bitmap_a = bitmap_a | bitmap_b; col_a->bv_values[0] = Int64GetDatum((int64)bitmap_a); PG_RETURN_VOID(); } PG_FUNCTION_INFO_V1(brin_bins_options); Datum brin_bins_options(PG_FUNCTION_ARGS) { local_relopts *relopts = (local_relopts *) PG_GETARG_POINTER(0); init_local_reloptions(relopts, sizeof(BinsOptions)); add_local_real_reloption(relopts, "min_boundary_value", "lower boundary of the inner bins", MIN_BOUNDARY_DEFAULT, -DBL_MAX, DBL_MAX, offsetof(BinsOptions, minBoundaryValue)); add_local_real_reloption(relopts, "max_boundary_value", "upper boundary of the inner bins", MAX_BOUNDARY_DEFAULT, -DBL_MAX, DBL_MAX, offsetof(BinsOptions, maxBoundaryValue)); PG_RETURN_VOID(); } PG_FUNCTION_INFO_V1(brin_bins_datetime_value_date); Datum brin_bins_datetime_value_date(PG_FUNCTION_ARGS) { DateADT date = PG_GETARG_DATEADT(0); PG_RETURN_FLOAT8((float8) date); } PG_FUNCTION_INFO_V1(brin_bins_datetime_value_timestamp); Datum brin_bins_datetime_value_timestamp(PG_FUNCTION_ARGS) { Timestamp ts = PG_GETARG_TIMESTAMP(0); PG_RETURN_FLOAT8((float8) ts); } PG_FUNCTION_INFO_V1(brin_bins_datetime_value_timestamptz); Datum brin_bins_datetime_value_timestamptz(PG_FUNCTION_ARGS) { TimestampTz ts = PG_GETARG_TIMESTAMPTZ(0); PG_RETURN_FLOAT8((float8) ts); } /* * Convert a boundary value given as double into a Datum of the column type. * This is the only place that depends on the column type. */ static Datum bins_double_to_datum(Oid typoid, double value) { double rounded = rint(value); switch (typoid) { case INT2OID: if (!FLOAT8_FITS_IN_INT16(rounded)) goto out_of_range; return Int16GetDatum((int16) rounded); case INT4OID: if (!FLOAT8_FITS_IN_INT32(rounded)) goto out_of_range; return Int32GetDatum((int32) rounded); case INT8OID: if (!FLOAT8_FITS_IN_INT64(rounded)) goto out_of_range; return Int64GetDatum((int64) rounded); case FLOAT4OID: if (fabs(value) > FLT_MAX) goto out_of_range; return Float4GetDatum((float4) value); case FLOAT8OID: return Float8GetDatum(value); case DATEOID: /* days since 2000-01-01 */ if (!FLOAT8_FITS_IN_INT32(rounded)) goto out_of_range; return DateADTGetDatum((DateADT) rounded); case TIMESTAMPOID: /* microseconds since 2000-01-01 00:00:00 */ case TIMESTAMPTZOID: if (!FLOAT8_FITS_IN_INT64(rounded)) goto out_of_range; return TimestampGetDatum((Timestamp) rounded); default: elog(ERROR, "brin bins: unsupported type %u", typoid); } out_of_range: ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("boundary value %g is out of range for type %s", value, format_type_be(typoid)))); return (Datum) 0; /* keep compiler quiet */ } /* * Return bin number corresponding to the heap column value. */ static int bins_get_binno(Datum val, Datum* bin_upper_bounds, FmgrInfo *cmpGreaterFn, Oid colloid) { int low = 0; int high = BINS_NBOUNDS; int mid; Datum compar; while (low < high) { mid = (low + high)/2; compar = FunctionCall2Coll(cmpGreaterFn, colloid, bin_upper_bounds[mid], val); if (DatumGetBool(compar)) high = mid; else low = mid +1; } return low; } /* * Cache and return the procedure for the given strategy. * * Note: this function mirrors brin_minmax.c in the postgres source code. */ static FmgrInfo * bins_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype, uint16 strategynum) { BinsOpaque *opaque; Assert(strategynum >= 1 && strategynum <= BTMaxStrategyNumber); opaque = (BinsOpaque *) bdesc->bd_info[attno - 1]->oi_opaque; /* * We cache the procedures for the previous subtype in the opaque struct, * to avoid repetitive syscache lookups. If the subtype changed, * invalidate all the cached entries. */ if (opaque->cached_subtype != subtype) { uint16 i; for (i = 1; i <= BTMaxStrategyNumber; i++) opaque->strategy_procinfos[i - 1].fn_oid = InvalidOid; opaque->cached_subtype = subtype; } if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid) { Form_pg_attribute attr; HeapTuple tuple; Oid opfamily, oprid; opfamily = bdesc->bd_index->rd_opfamily[attno - 1]; attr = TupleDescAttr(bdesc->bd_tupdesc, attno - 1); tuple = SearchSysCache4(AMOPSTRATEGY, ObjectIdGetDatum(opfamily), ObjectIdGetDatum(attr->atttypid), ObjectIdGetDatum(subtype), UInt16GetDatum(strategynum)); if (!HeapTupleIsValid(tuple)) elog(ERROR, "missing operator %d(%u,%u) in opfamily %u", strategynum, attr->atttypid, subtype, opfamily); oprid = DatumGetObjectId(SysCacheGetAttrNotNull(AMOPSTRATEGY, tuple, Anum_pg_amop_amopopr)); ReleaseSysCache(tuple); Assert(RegProcedureIsValid(oprid)); fmgr_info_cxt(get_opcode(oprid), &opaque->strategy_procinfos[strategynum - 1], bdesc->bd_context); } return &opaque->strategy_procinfos[strategynum - 1]; }