| 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.index; |
| 7 |
|
| 8 |
import java.util.ArrayList; |
| 9 |
import java.util.concurrent.TimeUnit; |
| 10 |
|
| 11 |
import org.h2.api.ErrorCode; |
| 12 |
import org.h2.command.Parser; |
| 13 |
import org.h2.command.query.AllColumnsForPlan; |
| 14 |
import org.h2.command.query.Query; |
| 15 |
import org.h2.command.query.SelectUnion; |
| 16 |
import org.h2.engine.Constants; |
| 17 |
import org.h2.engine.SessionLocal; |
| 18 |
import org.h2.expression.Parameter; |
| 19 |
import org.h2.expression.condition.Comparison; |
| 20 |
import org.h2.message.DbException; |
| 21 |
import org.h2.result.LocalResult; |
| 22 |
import org.h2.result.ResultInterface; |
| 23 |
import org.h2.result.Row; |
| 24 |
import org.h2.result.SearchRow; |
| 25 |
import org.h2.result.SortOrder; |
| 26 |
import org.h2.table.Column; |
| 27 |
import org.h2.table.IndexColumn; |
| 28 |
import org.h2.table.QueryExpressionTable; |
| 29 |
import org.h2.table.TableFilter; |
| 30 |
import org.h2.table.TableView; |
| 31 |
import org.h2.util.IntArray; |
| 32 |
import org.h2.value.Value; |
| 33 |
|
| 34 |
/** |
| 35 |
* This object represents a virtual index for a query expression. |
| 36 |
*/ |
| 37 |
public class QueryExpressionIndex extends Index implements SpatialIndex { |
| 38 |
|
| 39 |
private static final long MAX_AGE_NANOS = |
| 40 |
TimeUnit.MILLISECONDS.toNanos(Constants.VIEW_COST_CACHE_MAX_AGE); |
| 41 |
|
| 42 |
private final QueryExpressionTable table; |
| 43 |
private final String querySQL; |
| 44 |
private final ArrayList<Parameter> originalParameters; |
| 45 |
private boolean recursive; |
| 46 |
private final int[] indexMasks; |
| 47 |
private Query query; |
| 48 |
private final SessionLocal createSession; |
| 49 |
|
| 50 |
/** |
| 51 |
* The time in nanoseconds when this index (and its cost) was calculated. |
| 52 |
*/ |
| 53 |
private final long evaluatedAt; |
| 54 |
|
| 55 |
/** |
| 56 |
* Constructor for the original index in {@link TableView}. |
| 57 |
* |
| 58 |
* @param table the query expression table |
| 59 |
* @param querySQL the query SQL |
| 60 |
* @param originalParameters the original parameters |
| 61 |
* @param recursive if the view is recursive |
| 62 |
*/ |
| 63 |
public QueryExpressionIndex(QueryExpressionTable table, String querySQL, |
| 64 |
ArrayList<Parameter> originalParameters, boolean recursive) { |
| 65 |
super(table, 0, null, null, 0, IndexType.createNonUnique(false)); |
| 66 |
this.table = table; |
| 67 |
this.querySQL = querySQL; |
| 68 |
this.originalParameters = originalParameters; |
| 69 |
this.recursive = recursive; |
| 70 |
columns = new Column[0]; |
| 71 |
this.createSession = null; |
| 72 |
this.indexMasks = null; |
| 73 |
// this is a main index of TableView, it does not need eviction time |
| 74 |
// stamp |
| 75 |
evaluatedAt = Long.MIN_VALUE; |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Constructor for plan item generation. Over this index the query will be |
| 80 |
* executed. |
| 81 |
* |
| 82 |
* @param table the query expression table |
| 83 |
* @param index the main index |
| 84 |
* @param session the session |
| 85 |
* @param masks the masks |
| 86 |
* @param filters table filters |
| 87 |
* @param filter current filter |
| 88 |
* @param sortOrder sort order |
| 89 |
*/ |
| 90 |
public QueryExpressionIndex(QueryExpressionTable table, QueryExpressionIndex index, SessionLocal session, |
| 91 |
int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder) { |
| 92 |
super(table, 0, null, null, 0, IndexType.createNonUnique(false)); |
| 93 |
this.table = table; |
| 94 |
this.querySQL = index.querySQL; |
| 95 |
this.originalParameters = index.originalParameters; |
| 96 |
this.recursive = index.recursive; |
| 97 |
this.indexMasks = masks; |
| 98 |
this.createSession = session; |
| 99 |
columns = new Column[0]; |
| 100 |
if (!recursive) { |
| 101 |
query = getQuery(session, masks); |
| 102 |
} |
| 103 |
if (recursive || table.getTopQuery() != null) { |
| 104 |
evaluatedAt = Long.MAX_VALUE; |
| 105 |
} else { |
| 106 |
long time = System.nanoTime(); |
| 107 |
if (time == Long.MAX_VALUE) { |
| 108 |
time++; |
| 109 |
} |
| 110 |
evaluatedAt = time; |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
public SessionLocal getSession() { |
| 115 |
return createSession; |
| 116 |
} |
| 117 |
|
| 118 |
public boolean isExpired() { |
| 119 |
assert evaluatedAt != Long.MIN_VALUE : "must not be called for main index of TableView"; |
| 120 |
return !recursive && table.getTopQuery() == null && System.nanoTime() - evaluatedAt > MAX_AGE_NANOS; |
| 121 |
} |
| 122 |
|
| 123 |
@Override |
| 124 |
public String getPlanSQL() { |
| 125 |
return query == null ? null : query.getPlanSQL(TRACE_SQL_FLAGS | ADD_PLAN_INFORMATION); |
| 126 |
} |
| 127 |
|
| 128 |
@Override |
| 129 |
public void close(SessionLocal session) { |
| 130 |
// nothing to do |
| 131 |
} |
| 132 |
|
| 133 |
@Override |
| 134 |
public void add(SessionLocal session, Row row) { |
| 135 |
throw DbException.getUnsupportedException("VIEW"); |
| 136 |
} |
| 137 |
|
| 138 |
@Override |
| 139 |
public void remove(SessionLocal session, Row row) { |
| 140 |
throw DbException.getUnsupportedException("VIEW"); |
| 141 |
} |
| 142 |
|
| 143 |
@Override |
| 144 |
public double getCost(SessionLocal session, int[] masks, |
| 145 |
TableFilter[] filters, int filter, SortOrder sortOrder, |
| 146 |
AllColumnsForPlan allColumnsSet) { |
| 147 |
return recursive ? 1000 : query.getCost(); |
| 148 |
} |
| 149 |
|
| 150 |
@Override |
| 151 |
public Cursor find(SessionLocal session, SearchRow first, SearchRow last) { |
| 152 |
return find(session, first, last, null); |
| 153 |
} |
| 154 |
|
| 155 |
@Override |
| 156 |
public Cursor findByGeometry(SessionLocal session, SearchRow first, SearchRow last, SearchRow intersection) { |
| 157 |
return find(session, first, last, intersection); |
| 158 |
} |
| 159 |
|
| 160 |
private Cursor findRecursive(SearchRow first, SearchRow last) { |
| 161 |
TableView view = (TableView) table; |
| 162 |
ResultInterface recursiveResult = view.getRecursiveResult(); |
| 163 |
if (recursiveResult != null) { |
| 164 |
recursiveResult.reset(); |
| 165 |
return new QueryExpressionCursor(this, recursiveResult, first, last); |
| 166 |
} |
| 167 |
if (query == null) { |
| 168 |
Parser parser = new Parser(createSession); |
| 169 |
parser.setRightsChecked(true); |
| 170 |
parser.setSuppliedParameters(originalParameters); |
| 171 |
query = (Query) parser.prepare(querySQL); |
| 172 |
query.setNeverLazy(true); |
| 173 |
} |
| 174 |
if (!query.isUnion()) { |
| 175 |
throw DbException.get(ErrorCode.SYNTAX_ERROR_2, |
| 176 |
"recursive queries without UNION"); |
| 177 |
} |
| 178 |
SelectUnion union = (SelectUnion) query; |
| 179 |
Query left = union.getLeft(); |
| 180 |
left.setNeverLazy(true); |
| 181 |
// to ensure the last result is not closed |
| 182 |
left.disableCache(); |
| 183 |
ResultInterface resultInterface = left.query(0); |
| 184 |
LocalResult localResult = union.getEmptyResult(); |
| 185 |
// ensure it is not written to disk, |
| 186 |
// because it is not closed normally |
| 187 |
localResult.setMaxMemoryRows(Integer.MAX_VALUE); |
| 188 |
while (resultInterface.next()) { |
| 189 |
Value[] cr = resultInterface.currentRow(); |
| 190 |
localResult.addRow(cr); |
| 191 |
} |
| 192 |
Query right = union.getRight(); |
| 193 |
right.setNeverLazy(true); |
| 194 |
resultInterface.reset(); |
| 195 |
view.setRecursiveResult(resultInterface); |
| 196 |
// to ensure the last result is not closed |
| 197 |
right.disableCache(); |
| 198 |
while (true) { |
| 199 |
resultInterface = right.query(0); |
| 200 |
if (!resultInterface.hasNext()) { |
| 201 |
break; |
| 202 |
} |
| 203 |
while (resultInterface.next()) { |
| 204 |
Value[] cr = resultInterface.currentRow(); |
| 205 |
localResult.addRow(cr); |
| 206 |
} |
| 207 |
resultInterface.reset(); |
| 208 |
view.setRecursiveResult(resultInterface); |
| 209 |
} |
| 210 |
view.setRecursiveResult(null); |
| 211 |
localResult.done(); |
| 212 |
return new QueryExpressionCursor(this, localResult, first, last); |
| 213 |
} |
| 214 |
|
| 215 |
/** |
| 216 |
* Set the query parameters. |
| 217 |
* |
| 218 |
* @param session the session |
| 219 |
* @param first the lower bound |
| 220 |
* @param last the upper bound |
| 221 |
* @param intersection the intersection |
| 222 |
*/ |
| 223 |
public void setupQueryParameters(SessionLocal session, SearchRow first, SearchRow last, |
| 224 |
SearchRow intersection) { |
| 225 |
ArrayList<Parameter> paramList = query.getParameters(); |
| 226 |
if (originalParameters != null) { |
| 227 |
for (Parameter orig : originalParameters) { |
| 228 |
if (orig != null) { |
| 229 |
int idx = orig.getIndex(); |
| 230 |
Value value = orig.getValue(session); |
| 231 |
setParameter(paramList, idx, value); |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
int len; |
| 236 |
if (first != null) { |
| 237 |
len = first.getColumnCount(); |
| 238 |
} else if (last != null) { |
| 239 |
len = last.getColumnCount(); |
| 240 |
} else if (intersection != null) { |
| 241 |
len = intersection.getColumnCount(); |
| 242 |
} else { |
| 243 |
len = 0; |
| 244 |
} |
| 245 |
int idx = table.getParameterOffset(originalParameters); |
| 246 |
for (int i = 0; i < len; i++) { |
| 247 |
int mask = indexMasks[i]; |
| 248 |
if ((mask & IndexCondition.EQUALITY) != 0) { |
| 249 |
setParameter(paramList, idx++, first.getValue(i)); |
| 250 |
} |
| 251 |
if ((mask & IndexCondition.START) != 0) { |
| 252 |
setParameter(paramList, idx++, first.getValue(i)); |
| 253 |
} |
| 254 |
if ((mask & IndexCondition.END) != 0) { |
| 255 |
setParameter(paramList, idx++, last.getValue(i)); |
| 256 |
} |
| 257 |
if ((mask & IndexCondition.SPATIAL_INTERSECTS) != 0) { |
| 258 |
setParameter(paramList, idx++, intersection.getValue(i)); |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
private Cursor find(SessionLocal session, SearchRow first, SearchRow last, |
| 264 |
SearchRow intersection) { |
| 265 |
if (recursive) { |
| 266 |
return findRecursive(first, last); |
| 267 |
} |
| 268 |
setupQueryParameters(session, first, last, intersection); |
| 269 |
ResultInterface result = query.query(0); |
| 270 |
return new QueryExpressionCursor(this, result, first, last); |
| 271 |
} |
| 272 |
|
| 273 |
private static void setParameter(ArrayList<Parameter> paramList, int x, |
| 274 |
Value v) { |
| 275 |
if (x >= paramList.size()) { |
| 276 |
// the parameter may be optimized away as in |
| 277 |
// select * from (select null as x) where x=1; |
| 278 |
return; |
| 279 |
} |
| 280 |
Parameter param = paramList.get(x); |
| 281 |
param.setValue(v); |
| 282 |
} |
| 283 |
|
| 284 |
public Query getQuery() { |
| 285 |
return query; |
| 286 |
} |
| 287 |
|
| 288 |
private Query getQuery(SessionLocal session, int[] masks) { |
| 289 |
Query q = session.prepareQueryExpression(querySQL); |
| 290 |
if (masks == null || !q.allowGlobalConditions()) { |
| 291 |
q.preparePlan(); |
| 292 |
return q; |
| 293 |
} |
| 294 |
int firstIndexParam = table.getParameterOffset(originalParameters); |
| 295 |
// the column index of each parameter |
| 296 |
// (for example: paramColumnIndex {0, 0} mean |
| 297 |
// param[0] is column 0, and param[1] is also column 0) |
| 298 |
IntArray paramColumnIndex = new IntArray(); |
| 299 |
int indexColumnCount = 0; |
| 300 |
for (int i = 0; i < masks.length; i++) { |
| 301 |
int mask = masks[i]; |
| 302 |
if (mask == 0) { |
| 303 |
continue; |
| 304 |
} |
| 305 |
indexColumnCount++; |
| 306 |
// the number of parameters depends on the mask; |
| 307 |
// for range queries it is 2: >= x AND <= y |
| 308 |
// but bitMask could also be 7 (=, and <=, and >=) |
| 309 |
int bitCount = Integer.bitCount(mask); |
| 310 |
for (int j = 0; j < bitCount; j++) { |
| 311 |
paramColumnIndex.add(i); |
| 312 |
} |
| 313 |
} |
| 314 |
int len = paramColumnIndex.size(); |
| 315 |
ArrayList<Column> columnList = new ArrayList<>(len); |
| 316 |
for (int i = 0; i < len;) { |
| 317 |
int idx = paramColumnIndex.get(i); |
| 318 |
columnList.add(table.getColumn(idx)); |
| 319 |
int mask = masks[idx]; |
| 320 |
if ((mask & IndexCondition.EQUALITY) != 0) { |
| 321 |
Parameter param = new Parameter(firstIndexParam + i); |
| 322 |
q.addGlobalCondition(param, idx, Comparison.EQUAL_NULL_SAFE); |
| 323 |
i++; |
| 324 |
} |
| 325 |
if ((mask & IndexCondition.START) != 0) { |
| 326 |
Parameter param = new Parameter(firstIndexParam + i); |
| 327 |
q.addGlobalCondition(param, idx, Comparison.BIGGER_EQUAL); |
| 328 |
i++; |
| 329 |
} |
| 330 |
if ((mask & IndexCondition.END) != 0) { |
| 331 |
Parameter param = new Parameter(firstIndexParam + i); |
| 332 |
q.addGlobalCondition(param, idx, Comparison.SMALLER_EQUAL); |
| 333 |
i++; |
| 334 |
} |
| 335 |
if ((mask & IndexCondition.SPATIAL_INTERSECTS) != 0) { |
| 336 |
Parameter param = new Parameter(firstIndexParam + i); |
| 337 |
q.addGlobalCondition(param, idx, Comparison.SPATIAL_INTERSECTS); |
| 338 |
i++; |
| 339 |
} |
| 340 |
} |
| 341 |
columns = columnList.toArray(new Column[0]); |
| 342 |
|
| 343 |
// reconstruct the index columns from the masks |
| 344 |
this.indexColumns = new IndexColumn[indexColumnCount]; |
| 345 |
this.columnIds = new int[indexColumnCount]; |
| 346 |
for (int type = 0, indexColumnId = 0; type < 2; type++) { |
| 347 |
for (int i = 0; i < masks.length; i++) { |
| 348 |
int mask = masks[i]; |
| 349 |
if (mask == 0) { |
| 350 |
continue; |
| 351 |
} |
| 352 |
if (type == 0) { |
| 353 |
if ((mask & IndexCondition.EQUALITY) == 0) { |
| 354 |
// the first columns need to be equality conditions |
| 355 |
continue; |
| 356 |
} |
| 357 |
} else { |
| 358 |
if ((mask & IndexCondition.EQUALITY) != 0) { |
| 359 |
// after that only range conditions |
| 360 |
continue; |
| 361 |
} |
| 362 |
} |
| 363 |
Column column = table.getColumn(i); |
| 364 |
indexColumns[indexColumnId] = new IndexColumn(column); |
| 365 |
columnIds[indexColumnId] = column.getColumnId(); |
| 366 |
indexColumnId++; |
| 367 |
} |
| 368 |
} |
| 369 |
String sql = q.getPlanSQL(DEFAULT_SQL_FLAGS); |
| 370 |
if (!sql.equals(querySQL)) { |
| 371 |
q = session.prepareQueryExpression(sql); |
| 372 |
} |
| 373 |
q.preparePlan(); |
| 374 |
return q; |
| 375 |
} |
| 376 |
|
| 377 |
@Override |
| 378 |
public void remove(SessionLocal session) { |
| 379 |
throw DbException.getUnsupportedException("VIEW"); |
| 380 |
} |
| 381 |
|
| 382 |
@Override |
| 383 |
public void truncate(SessionLocal session) { |
| 384 |
throw DbException.getUnsupportedException("VIEW"); |
| 385 |
} |
| 386 |
|
| 387 |
@Override |
| 388 |
public void checkRename() { |
| 389 |
throw DbException.getUnsupportedException("VIEW"); |
| 390 |
} |
| 391 |
|
| 392 |
@Override |
| 393 |
public boolean needRebuild() { |
| 394 |
return false; |
| 395 |
} |
| 396 |
|
| 397 |
public void setRecursive(boolean value) { |
| 398 |
this.recursive = value; |
| 399 |
} |
| 400 |
|
| 401 |
@Override |
| 402 |
public long getRowCount(SessionLocal session) { |
| 403 |
return 0; |
| 404 |
} |
| 405 |
|
| 406 |
@Override |
| 407 |
public long getRowCountApproximation(SessionLocal session) { |
| 408 |
return 0; |
| 409 |
} |
| 410 |
|
| 411 |
public boolean isRecursive() { |
| 412 |
return recursive; |
| 413 |
} |
| 414 |
} |