| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.expression.aggregate; |
| 7 |
|
| 8 |
import java.math.BigDecimal; |
| 9 |
import java.math.BigInteger; |
| 10 |
import java.util.ArrayList; |
| 11 |
import java.util.Arrays; |
| 12 |
|
| 13 |
import org.h2.api.IntervalQualifier; |
| 14 |
import org.h2.command.query.QueryOrderBy; |
| 15 |
import org.h2.engine.Database; |
| 16 |
import org.h2.engine.SessionLocal; |
| 17 |
import org.h2.expression.Expression; |
| 18 |
import org.h2.expression.ExpressionColumn; |
| 19 |
import org.h2.index.Cursor; |
| 20 |
import org.h2.index.Index; |
| 21 |
import org.h2.mode.DefaultNullOrdering; |
| 22 |
import org.h2.result.SearchRow; |
| 23 |
import org.h2.result.SortOrder; |
| 24 |
import org.h2.table.Column; |
| 25 |
import org.h2.table.Table; |
| 26 |
import org.h2.table.TableFilter; |
| 27 |
import org.h2.util.DateTimeUtils; |
| 28 |
import org.h2.util.IntervalUtils; |
| 29 |
import org.h2.value.CompareMode; |
| 30 |
import org.h2.value.Value; |
| 31 |
import org.h2.value.ValueDate; |
| 32 |
import org.h2.value.ValueInterval; |
| 33 |
import org.h2.value.ValueNull; |
| 34 |
import org.h2.value.ValueNumeric; |
| 35 |
import org.h2.value.ValueTime; |
| 36 |
import org.h2.value.ValueTimeTimeZone; |
| 37 |
import org.h2.value.ValueTimestamp; |
| 38 |
import org.h2.value.ValueTimestampTimeZone; |
| 39 |
|
| 40 |
/** |
| 41 |
* PERCENTILE_CONT, PERCENTILE_DISC, and MEDIAN inverse distribution functions. |
| 42 |
*/ |
| 43 |
final class Percentile { |
| 44 |
|
| 45 |
/** |
| 46 |
* BigDecimal value of 0.5. |
| 47 |
*/ |
| 48 |
static final BigDecimal HALF = BigDecimal.valueOf(0.5d); |
| 49 |
|
| 50 |
private static boolean isNullsLast(DefaultNullOrdering defaultNullOrdering, Index index) { |
| 51 |
return defaultNullOrdering.compareNull(true, index.getIndexColumns()[0].sortType) > 0; |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Get the index (if any) for the column specified in the inverse |
| 56 |
* distribution function. |
| 57 |
* |
| 58 |
* @param database the database |
| 59 |
* @param on the expression (usually a column expression) |
| 60 |
* @return the index, or null |
| 61 |
*/ |
| 62 |
static Index getColumnIndex(Database database, Expression on) { |
| 63 |
DefaultNullOrdering defaultNullOrdering = database.getDefaultNullOrdering(); |
| 64 |
if (on instanceof ExpressionColumn) { |
| 65 |
ExpressionColumn col = (ExpressionColumn) on; |
| 66 |
Column column = col.getColumn(); |
| 67 |
TableFilter filter = col.getTableFilter(); |
| 68 |
if (filter != null) { |
| 69 |
Table table = filter.getTable(); |
| 70 |
ArrayList<Index> indexes = table.getIndexes(); |
| 71 |
Index result = null; |
| 72 |
if (indexes != null) { |
| 73 |
boolean nullable = column.isNullable(); |
| 74 |
for (int i = 1, size = indexes.size(); i < size; i++) { |
| 75 |
Index index = indexes.get(i); |
| 76 |
if (!index.canFindNext()) { |
| 77 |
continue; |
| 78 |
} |
| 79 |
if (!index.isFirstColumn(column)) { |
| 80 |
continue; |
| 81 |
} |
| 82 |
// Prefer index without nulls last for nullable columns |
| 83 |
if (result == null || result.getColumns().length > index.getColumns().length |
| 84 |
|| nullable && isNullsLast(defaultNullOrdering, result) |
| 85 |
&& !isNullsLast(defaultNullOrdering, index)) { |
| 86 |
result = index; |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
return result; |
| 91 |
} |
| 92 |
} |
| 93 |
return null; |
| 94 |
} |
| 95 |
|
| 96 |
/** |
| 97 |
* Get the result from the array of values. |
| 98 |
* |
| 99 |
* @param session the session |
| 100 |
* @param array array with values |
| 101 |
* @param dataType the data type |
| 102 |
* @param orderByList ORDER BY list |
| 103 |
* @param percentile argument of percentile function, or 0.5d for median |
| 104 |
* @param interpolate whether value should be interpolated |
| 105 |
* @return the result |
| 106 |
*/ |
| 107 |
static Value getValue(SessionLocal session, Value[] array, int dataType, ArrayList<QueryOrderBy> orderByList, |
| 108 |
BigDecimal percentile, boolean interpolate) { |
| 109 |
final CompareMode compareMode = session.getDatabase().getCompareMode(); |
| 110 |
Arrays.sort(array, compareMode); |
| 111 |
int count = array.length; |
| 112 |
boolean reverseIndex = orderByList != null && (orderByList.get(0).sortType & SortOrder.DESCENDING) != 0; |
| 113 |
BigDecimal fpRow = BigDecimal.valueOf(count - 1).multiply(percentile); |
| 114 |
int rowIdx1 = fpRow.intValue(); |
| 115 |
BigDecimal factor = fpRow.subtract(BigDecimal.valueOf(rowIdx1)); |
| 116 |
int rowIdx2; |
| 117 |
if (factor.signum() == 0) { |
| 118 |
interpolate = false; |
| 119 |
rowIdx2 = rowIdx1; |
| 120 |
} else { |
| 121 |
rowIdx2 = rowIdx1 + 1; |
| 122 |
if (!interpolate) { |
| 123 |
if (factor.compareTo(HALF) > 0) { |
| 124 |
rowIdx1 = rowIdx2; |
| 125 |
} else { |
| 126 |
rowIdx2 = rowIdx1; |
| 127 |
} |
| 128 |
} |
| 129 |
} |
| 130 |
if (reverseIndex) { |
| 131 |
rowIdx1 = count - 1 - rowIdx1; |
| 132 |
rowIdx2 = count - 1 - rowIdx2; |
| 133 |
} |
| 134 |
Value v = array[rowIdx1]; |
| 135 |
if (!interpolate) { |
| 136 |
return v; |
| 137 |
} |
| 138 |
return interpolate(v, array[rowIdx2], factor, dataType, session, compareMode); |
| 139 |
} |
| 140 |
|
| 141 |
/** |
| 142 |
* Get the result from the index. |
| 143 |
* |
| 144 |
* @param session the session |
| 145 |
* @param expression the expression |
| 146 |
* @param dataType the data type |
| 147 |
* @param orderByList ORDER BY list |
| 148 |
* @param percentile argument of percentile function, or 0.5d for median |
| 149 |
* @param interpolate whether value should be interpolated |
| 150 |
* @return the result |
| 151 |
*/ |
| 152 |
static Value getFromIndex(SessionLocal session, Expression expression, int dataType, |
| 153 |
ArrayList<QueryOrderBy> orderByList, BigDecimal percentile, boolean interpolate) { |
| 154 |
Database db = session.getDatabase(); |
| 155 |
Index index = getColumnIndex(db, expression); |
| 156 |
long count = index.getRowCount(session); |
| 157 |
if (count == 0) { |
| 158 |
return ValueNull.INSTANCE; |
| 159 |
} |
| 160 |
Cursor cursor = index.find(session, null, null); |
| 161 |
cursor.next(); |
| 162 |
int columnId = index.getColumns()[0].getColumnId(); |
| 163 |
ExpressionColumn expr = (ExpressionColumn) expression; |
| 164 |
if (expr.getColumn().isNullable()) { |
| 165 |
boolean hasNulls = false; |
| 166 |
SearchRow row; |
| 167 |
// Try to skip nulls from the start first with the same cursor that |
| 168 |
// will be used to read values. |
| 169 |
while (count > 0) { |
| 170 |
row = cursor.getSearchRow(); |
| 171 |
if (row == null) { |
| 172 |
return ValueNull.INSTANCE; |
| 173 |
} |
| 174 |
if (row.getValue(columnId) == ValueNull.INSTANCE) { |
| 175 |
count--; |
| 176 |
cursor.next(); |
| 177 |
hasNulls = true; |
| 178 |
} else { |
| 179 |
break; |
| 180 |
} |
| 181 |
} |
| 182 |
if (count == 0) { |
| 183 |
return ValueNull.INSTANCE; |
| 184 |
} |
| 185 |
// If no nulls found and if index orders nulls last create a second |
| 186 |
// cursor to count nulls at the end. |
| 187 |
if (!hasNulls && isNullsLast(db.getDefaultNullOrdering(), index)) { |
| 188 |
TableFilter tableFilter = expr.getTableFilter(); |
| 189 |
SearchRow check = tableFilter.getTable().getTemplateSimpleRow(true); |
| 190 |
check.setValue(columnId, ValueNull.INSTANCE); |
| 191 |
Cursor nullsCursor = index.find(session, check, check); |
| 192 |
while (nullsCursor.next()) { |
| 193 |
count--; |
| 194 |
} |
| 195 |
if (count <= 0) { |
| 196 |
return ValueNull.INSTANCE; |
| 197 |
} |
| 198 |
} |
| 199 |
} |
| 200 |
boolean reverseIndex = (orderByList != null ? orderByList.get(0).sortType & SortOrder.DESCENDING : 0) |
| 201 |
!= (index.getIndexColumns()[0].sortType & SortOrder.DESCENDING); |
| 202 |
BigDecimal fpRow = BigDecimal.valueOf(count - 1).multiply(percentile); |
| 203 |
long rowIdx1 = fpRow.longValue(); |
| 204 |
BigDecimal factor = fpRow.subtract(BigDecimal.valueOf(rowIdx1)); |
| 205 |
long rowIdx2; |
| 206 |
if (factor.signum() == 0) { |
| 207 |
interpolate = false; |
| 208 |
rowIdx2 = rowIdx1; |
| 209 |
} else { |
| 210 |
rowIdx2 = rowIdx1 + 1; |
| 211 |
if (!interpolate) { |
| 212 |
if (factor.compareTo(HALF) > 0) { |
| 213 |
rowIdx1 = rowIdx2; |
| 214 |
} else { |
| 215 |
rowIdx2 = rowIdx1; |
| 216 |
} |
| 217 |
} |
| 218 |
} |
| 219 |
long skip = reverseIndex ? count - 1 - rowIdx2 : rowIdx1; |
| 220 |
for (int i = 0; i < skip; i++) { |
| 221 |
cursor.next(); |
| 222 |
} |
| 223 |
SearchRow row = cursor.getSearchRow(); |
| 224 |
if (row == null) { |
| 225 |
return ValueNull.INSTANCE; |
| 226 |
} |
| 227 |
Value v = row.getValue(columnId); |
| 228 |
if (v == ValueNull.INSTANCE) { |
| 229 |
return v; |
| 230 |
} |
| 231 |
if (interpolate) { |
| 232 |
cursor.next(); |
| 233 |
row = cursor.getSearchRow(); |
| 234 |
if (row == null) { |
| 235 |
return v; |
| 236 |
} |
| 237 |
Value v2 = row.getValue(columnId); |
| 238 |
if (v2 == ValueNull.INSTANCE) { |
| 239 |
return v; |
| 240 |
} |
| 241 |
if (reverseIndex) { |
| 242 |
Value t = v; |
| 243 |
v = v2; |
| 244 |
v2 = t; |
| 245 |
} |
| 246 |
return interpolate(v, v2, factor, dataType, session, db.getCompareMode()); |
| 247 |
} |
| 248 |
return v; |
| 249 |
} |
| 250 |
|
| 251 |
private static Value interpolate(Value v0, Value v1, BigDecimal factor, int dataType, SessionLocal session, |
| 252 |
CompareMode compareMode) { |
| 253 |
if (v0.compareTo(v1, session, compareMode) == 0) { |
| 254 |
return v0; |
| 255 |
} |
| 256 |
switch (dataType) { |
| 257 |
case Value.TINYINT: |
| 258 |
case Value.SMALLINT: |
| 259 |
case Value.INTEGER: |
| 260 |
return ValueNumeric.get( |
| 261 |
interpolateDecimal(BigDecimal.valueOf(v0.getInt()), BigDecimal.valueOf(v1.getInt()), factor)); |
| 262 |
case Value.BIGINT: |
| 263 |
return ValueNumeric.get( |
| 264 |
interpolateDecimal(BigDecimal.valueOf(v0.getLong()), BigDecimal.valueOf(v1.getLong()), factor)); |
| 265 |
case Value.NUMERIC: |
| 266 |
case Value.DECFLOAT: |
| 267 |
return ValueNumeric.get(interpolateDecimal(v0.getBigDecimal(), v1.getBigDecimal(), factor)); |
| 268 |
case Value.REAL: |
| 269 |
case Value.DOUBLE: |
| 270 |
return ValueNumeric.get( |
| 271 |
interpolateDecimal( |
| 272 |
BigDecimal.valueOf(v0.getDouble()), BigDecimal.valueOf(v1.getDouble()), factor)); |
| 273 |
case Value.TIME: { |
| 274 |
ValueTime t0 = (ValueTime) v0, t1 = (ValueTime) v1; |
| 275 |
BigDecimal n0 = BigDecimal.valueOf(t0.getNanos()); |
| 276 |
BigDecimal n1 = BigDecimal.valueOf(t1.getNanos()); |
| 277 |
return ValueTime.fromNanos(interpolateDecimal(n0, n1, factor).longValue()); |
| 278 |
} |
| 279 |
case Value.TIME_TZ: { |
| 280 |
ValueTimeTimeZone t0 = (ValueTimeTimeZone) v0, t1 = (ValueTimeTimeZone) v1; |
| 281 |
BigDecimal n0 = BigDecimal.valueOf(t0.getNanos()); |
| 282 |
BigDecimal n1 = BigDecimal.valueOf(t1.getNanos()); |
| 283 |
BigDecimal offset = BigDecimal.valueOf(t0.getTimeZoneOffsetSeconds()) |
| 284 |
.multiply(BigDecimal.ONE.subtract(factor)) |
| 285 |
.add(BigDecimal.valueOf(t1.getTimeZoneOffsetSeconds()).multiply(factor)); |
| 286 |
int intOffset = offset.intValue(); |
| 287 |
BigDecimal intOffsetBD = BigDecimal.valueOf(intOffset); |
| 288 |
BigDecimal bd = interpolateDecimal(n0, n1, factor); |
| 289 |
if (offset.compareTo(intOffsetBD) != 0) { |
| 290 |
bd = bd.add( |
| 291 |
offset.subtract(intOffsetBD).multiply(BigDecimal.valueOf(DateTimeUtils.NANOS_PER_SECOND))); |
| 292 |
} |
| 293 |
long timeNanos = bd.longValue(); |
| 294 |
if (timeNanos < 0L) { |
| 295 |
timeNanos += DateTimeUtils.NANOS_PER_SECOND; |
| 296 |
intOffset++; |
| 297 |
} else if (timeNanos >= DateTimeUtils.NANOS_PER_DAY) { |
| 298 |
timeNanos -= DateTimeUtils.NANOS_PER_SECOND; |
| 299 |
intOffset--; |
| 300 |
} |
| 301 |
return ValueTimeTimeZone.fromNanos(timeNanos, intOffset); |
| 302 |
} |
| 303 |
case Value.DATE: { |
| 304 |
ValueDate d0 = (ValueDate) v0, d1 = (ValueDate) v1; |
| 305 |
BigDecimal a0 = BigDecimal.valueOf(DateTimeUtils.absoluteDayFromDateValue(d0.getDateValue())); |
| 306 |
BigDecimal a1 = BigDecimal.valueOf(DateTimeUtils.absoluteDayFromDateValue(d1.getDateValue())); |
| 307 |
return ValueDate.fromDateValue( |
| 308 |
DateTimeUtils.dateValueFromAbsoluteDay(interpolateDecimal(a0, a1, factor).longValue())); |
| 309 |
} |
| 310 |
case Value.TIMESTAMP: { |
| 311 |
ValueTimestamp ts0 = (ValueTimestamp) v0, ts1 = (ValueTimestamp) v1; |
| 312 |
BigDecimal a0 = timestampToDecimal(ts0.getDateValue(), ts0.getTimeNanos()); |
| 313 |
BigDecimal a1 = timestampToDecimal(ts1.getDateValue(), ts1.getTimeNanos()); |
| 314 |
BigInteger[] dr = interpolateDecimal(a0, a1, factor).toBigInteger() |
| 315 |
.divideAndRemainder(IntervalUtils.NANOS_PER_DAY_BI); |
| 316 |
long absoluteDay = dr[0].longValue(); |
| 317 |
long timeNanos = dr[1].longValue(); |
| 318 |
if (timeNanos < 0) { |
| 319 |
timeNanos += DateTimeUtils.NANOS_PER_DAY; |
| 320 |
absoluteDay--; |
| 321 |
} |
| 322 |
return ValueTimestamp.fromDateValueAndNanos( |
| 323 |
DateTimeUtils.dateValueFromAbsoluteDay(absoluteDay), timeNanos); |
| 324 |
} |
| 325 |
case Value.TIMESTAMP_TZ: { |
| 326 |
ValueTimestampTimeZone ts0 = (ValueTimestampTimeZone) v0, ts1 = (ValueTimestampTimeZone) v1; |
| 327 |
BigDecimal a0 = timestampToDecimal(ts0.getDateValue(), ts0.getTimeNanos()); |
| 328 |
BigDecimal a1 = timestampToDecimal(ts1.getDateValue(), ts1.getTimeNanos()); |
| 329 |
BigDecimal offset = BigDecimal.valueOf(ts0.getTimeZoneOffsetSeconds()) |
| 330 |
.multiply(BigDecimal.ONE.subtract(factor)) |
| 331 |
.add(BigDecimal.valueOf(ts1.getTimeZoneOffsetSeconds()).multiply(factor)); |
| 332 |
int intOffset = offset.intValue(); |
| 333 |
BigDecimal intOffsetBD = BigDecimal.valueOf(intOffset); |
| 334 |
BigDecimal bd = interpolateDecimal(a0, a1, factor); |
| 335 |
if (offset.compareTo(intOffsetBD) != 0) { |
| 336 |
bd = bd.add( |
| 337 |
offset.subtract(intOffsetBD).multiply(BigDecimal.valueOf(DateTimeUtils.NANOS_PER_SECOND))); |
| 338 |
} |
| 339 |
BigInteger[] dr = bd.toBigInteger().divideAndRemainder(IntervalUtils.NANOS_PER_DAY_BI); |
| 340 |
long absoluteDay = dr[0].longValue(); |
| 341 |
long timeNanos = dr[1].longValue(); |
| 342 |
if (timeNanos < 0) { |
| 343 |
timeNanos += DateTimeUtils.NANOS_PER_DAY; |
| 344 |
absoluteDay--; |
| 345 |
} |
| 346 |
return ValueTimestampTimeZone.fromDateValueAndNanos(DateTimeUtils.dateValueFromAbsoluteDay(absoluteDay), |
| 347 |
timeNanos, intOffset); |
| 348 |
} |
| 349 |
case Value.INTERVAL_YEAR: |
| 350 |
case Value.INTERVAL_MONTH: |
| 351 |
case Value.INTERVAL_DAY: |
| 352 |
case Value.INTERVAL_HOUR: |
| 353 |
case Value.INTERVAL_MINUTE: |
| 354 |
case Value.INTERVAL_SECOND: |
| 355 |
case Value.INTERVAL_YEAR_TO_MONTH: |
| 356 |
case Value.INTERVAL_DAY_TO_HOUR: |
| 357 |
case Value.INTERVAL_DAY_TO_MINUTE: |
| 358 |
case Value.INTERVAL_DAY_TO_SECOND: |
| 359 |
case Value.INTERVAL_HOUR_TO_MINUTE: |
| 360 |
case Value.INTERVAL_HOUR_TO_SECOND: |
| 361 |
case Value.INTERVAL_MINUTE_TO_SECOND: |
| 362 |
return IntervalUtils.intervalFromAbsolute(IntervalQualifier.valueOf(dataType - Value.INTERVAL_YEAR), |
| 363 |
interpolateDecimal(new BigDecimal(IntervalUtils.intervalToAbsolute((ValueInterval) v0)), |
| 364 |
new BigDecimal(IntervalUtils.intervalToAbsolute((ValueInterval) v1)), factor) |
| 365 |
.toBigInteger()); |
| 366 |
default: |
| 367 |
// Use the same rules as PERCENTILE_DISC |
| 368 |
return (factor.compareTo(HALF) > 0 ? v1 : v0); |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
private static BigDecimal timestampToDecimal(long dateValue, long timeNanos) { |
| 373 |
return new BigDecimal(BigInteger.valueOf(DateTimeUtils.absoluteDayFromDateValue(dateValue)) |
| 374 |
.multiply(IntervalUtils.NANOS_PER_DAY_BI).add(BigInteger.valueOf(timeNanos))); |
| 375 |
} |
| 376 |
|
| 377 |
private static BigDecimal interpolateDecimal(BigDecimal d0, BigDecimal d1, BigDecimal factor) { |
| 378 |
return d0.multiply(BigDecimal.ONE.subtract(factor)).add(d1.multiply(factor)); |
| 379 |
} |
| 380 |
|
| 381 |
private Percentile() { |
| 382 |
} |
| 383 |
|
| 384 |
} |