| 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.command.query; |
| 7 |
|
| 8 |
import static org.h2.expression.Expression.WITHOUT_PARENTHESES; |
| 9 |
import static org.h2.util.HasSQL.DEFAULT_SQL_FLAGS; |
| 10 |
|
| 11 |
import java.util.ArrayList; |
| 12 |
import java.util.HashSet; |
| 13 |
import java.util.Iterator; |
| 14 |
|
| 15 |
import org.h2.api.ErrorCode; |
| 16 |
import org.h2.command.CommandInterface; |
| 17 |
import org.h2.command.Prepared; |
| 18 |
import org.h2.engine.Database; |
| 19 |
import org.h2.engine.DbObject; |
| 20 |
import org.h2.engine.SessionLocal; |
| 21 |
import org.h2.expression.Alias; |
| 22 |
import org.h2.expression.Expression; |
| 23 |
import org.h2.expression.ExpressionColumn; |
| 24 |
import org.h2.expression.ExpressionVisitor; |
| 25 |
import org.h2.expression.Parameter; |
| 26 |
import org.h2.expression.ValueExpression; |
| 27 |
import org.h2.message.DbException; |
| 28 |
import org.h2.result.LocalResult; |
| 29 |
import org.h2.result.ResultInterface; |
| 30 |
import org.h2.result.ResultTarget; |
| 31 |
import org.h2.result.SortOrder; |
| 32 |
import org.h2.table.Column; |
| 33 |
import org.h2.table.ColumnResolver; |
| 34 |
import org.h2.table.DerivedTable; |
| 35 |
import org.h2.table.Table; |
| 36 |
import org.h2.table.TableFilter; |
| 37 |
import org.h2.util.Utils; |
| 38 |
import org.h2.value.ExtTypeInfoRow; |
| 39 |
import org.h2.value.TypeInfo; |
| 40 |
import org.h2.value.Value; |
| 41 |
import org.h2.value.ValueInteger; |
| 42 |
import org.h2.value.ValueNull; |
| 43 |
|
| 44 |
/** |
| 45 |
* Represents a SELECT statement (simple, or union). |
| 46 |
*/ |
| 47 |
public abstract class Query extends Prepared { |
| 48 |
|
| 49 |
/** |
| 50 |
* Evaluated values of OFFSET and FETCH clauses. |
| 51 |
*/ |
| 52 |
static final class OffsetFetch { |
| 53 |
|
| 54 |
/** |
| 55 |
* OFFSET value. |
| 56 |
*/ |
| 57 |
final long offset; |
| 58 |
|
| 59 |
/** |
| 60 |
* FETCH value. |
| 61 |
*/ |
| 62 |
final long fetch; |
| 63 |
|
| 64 |
/** |
| 65 |
* Whether FETCH value is a PERCENT value. |
| 66 |
*/ |
| 67 |
final boolean fetchPercent; |
| 68 |
|
| 69 |
OffsetFetch(long offset, long fetch, boolean fetchPercent) { |
| 70 |
this.offset = offset; |
| 71 |
this.fetch = fetch; |
| 72 |
this.fetchPercent = fetchPercent; |
| 73 |
} |
| 74 |
|
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* The column list, including invisible expressions such as order by expressions. |
| 79 |
*/ |
| 80 |
ArrayList<Expression> expressions; |
| 81 |
|
| 82 |
/** |
| 83 |
* Array of expressions. |
| 84 |
* |
| 85 |
* @see #expressions |
| 86 |
*/ |
| 87 |
Expression[] expressionArray; |
| 88 |
|
| 89 |
/** |
| 90 |
* Describes elements of the ORDER BY clause of a query. |
| 91 |
*/ |
| 92 |
ArrayList<QueryOrderBy> orderList; |
| 93 |
|
| 94 |
/** |
| 95 |
* A sort order represents an ORDER BY clause in a query. |
| 96 |
*/ |
| 97 |
SortOrder sort; |
| 98 |
|
| 99 |
/** |
| 100 |
* The fetch expression as specified in the FETCH, LIMIT, or TOP clause. |
| 101 |
*/ |
| 102 |
Expression fetchExpr; |
| 103 |
|
| 104 |
/** |
| 105 |
* Whether limit expression specifies percentage of rows. |
| 106 |
*/ |
| 107 |
boolean fetchPercent; |
| 108 |
|
| 109 |
/** |
| 110 |
* Whether tied rows should be included in result too. |
| 111 |
*/ |
| 112 |
boolean withTies; |
| 113 |
|
| 114 |
/** |
| 115 |
* The offset expression as specified in the OFFSET clause. |
| 116 |
*/ |
| 117 |
Expression offsetExpr; |
| 118 |
|
| 119 |
/** |
| 120 |
* Whether the result must only contain distinct rows. |
| 121 |
*/ |
| 122 |
boolean distinct; |
| 123 |
|
| 124 |
/** |
| 125 |
* Whether the result needs to support random access. |
| 126 |
*/ |
| 127 |
boolean randomAccessResult; |
| 128 |
|
| 129 |
/** |
| 130 |
* The visible columns (the ones required in the result). |
| 131 |
*/ |
| 132 |
int visibleColumnCount; |
| 133 |
|
| 134 |
/** |
| 135 |
* Number of columns including visible columns and additional virtual |
| 136 |
* columns for ORDER BY and DISTINCT ON clauses. This number does not |
| 137 |
* include virtual columns for HAVING and QUALIFY. |
| 138 |
*/ |
| 139 |
int resultColumnCount; |
| 140 |
|
| 141 |
private boolean noCache; |
| 142 |
private long lastLimit; |
| 143 |
private long lastEvaluated; |
| 144 |
private ResultInterface lastResult; |
| 145 |
private Boolean lastExists; |
| 146 |
private Value[] lastParameters; |
| 147 |
private boolean cacheableChecked; |
| 148 |
private boolean neverLazy; |
| 149 |
|
| 150 |
boolean checkInit; |
| 151 |
|
| 152 |
boolean isPrepared; |
| 153 |
|
| 154 |
Query(SessionLocal session) { |
| 155 |
super(session); |
| 156 |
} |
| 157 |
|
| 158 |
public void setNeverLazy(boolean b) { |
| 159 |
this.neverLazy = b; |
| 160 |
} |
| 161 |
|
| 162 |
public boolean isNeverLazy() { |
| 163 |
return neverLazy; |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* Check if this is a UNION query. |
| 168 |
* |
| 169 |
* @return {@code true} if this is a UNION query |
| 170 |
*/ |
| 171 |
public abstract boolean isUnion(); |
| 172 |
|
| 173 |
@Override |
| 174 |
public ResultInterface queryMeta() { |
| 175 |
LocalResult result = new LocalResult(session, expressionArray, visibleColumnCount, resultColumnCount); |
| 176 |
result.done(); |
| 177 |
return result; |
| 178 |
} |
| 179 |
|
| 180 |
/** |
| 181 |
* Execute the query without checking the cache. If a target is specified, |
| 182 |
* the results are written to it, and the method returns null. If no target |
| 183 |
* is specified, a new LocalResult is created and returned. |
| 184 |
* |
| 185 |
* @param limit the limit as specified in the JDBC method call |
| 186 |
* @param target the target to write results to |
| 187 |
* @return the result |
| 188 |
*/ |
| 189 |
protected abstract ResultInterface queryWithoutCache(long limit, ResultTarget target); |
| 190 |
|
| 191 |
private ResultInterface queryWithoutCacheLazyCheck(long limit, ResultTarget target) { |
| 192 |
boolean disableLazy = neverLazy && session.isLazyQueryExecution(); |
| 193 |
if (disableLazy) { |
| 194 |
session.setLazyQueryExecution(false); |
| 195 |
} |
| 196 |
try { |
| 197 |
return queryWithoutCache(limit, target); |
| 198 |
} finally { |
| 199 |
if (disableLazy) { |
| 200 |
session.setLazyQueryExecution(true); |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
/** |
| 206 |
* Initialize the query. |
| 207 |
*/ |
| 208 |
public abstract void init(); |
| 209 |
|
| 210 |
@Override |
| 211 |
public final void prepare() { |
| 212 |
if (!checkInit) { |
| 213 |
throw DbException.getInternalError("not initialized"); |
| 214 |
} |
| 215 |
if (isPrepared) { |
| 216 |
return; |
| 217 |
} |
| 218 |
prepareExpressions(); |
| 219 |
preparePlan(); |
| 220 |
} |
| 221 |
|
| 222 |
public abstract void prepareExpressions(); |
| 223 |
|
| 224 |
public abstract void preparePlan(); |
| 225 |
|
| 226 |
/** |
| 227 |
* The the list of select expressions. |
| 228 |
* This may include invisible expressions such as order by expressions. |
| 229 |
* |
| 230 |
* @return the list of expressions |
| 231 |
*/ |
| 232 |
public ArrayList<Expression> getExpressions() { |
| 233 |
return expressions; |
| 234 |
} |
| 235 |
|
| 236 |
/** |
| 237 |
* Calculate the cost to execute this query. |
| 238 |
* |
| 239 |
* @return the cost |
| 240 |
*/ |
| 241 |
public abstract double getCost(); |
| 242 |
|
| 243 |
/** |
| 244 |
* Calculate the cost when used as a subquery. |
| 245 |
* This method returns a value between 10 and 1000000, |
| 246 |
* to ensure adding other values can't result in an integer overflow. |
| 247 |
* |
| 248 |
* @return the estimated cost as an integer |
| 249 |
*/ |
| 250 |
public int getCostAsExpression() { |
| 251 |
// ensure the cost is not larger than 1 million, |
| 252 |
// so that adding other values can't overflow |
| 253 |
return (int) Math.min(1_000_000d, 10d + 10d * getCost()); |
| 254 |
} |
| 255 |
|
| 256 |
/** |
| 257 |
* Get all tables that are involved in this query. |
| 258 |
* |
| 259 |
* @return the set of tables |
| 260 |
*/ |
| 261 |
public abstract HashSet<Table> getTables(); |
| 262 |
|
| 263 |
/** |
| 264 |
* Set the order by list. |
| 265 |
* |
| 266 |
* @param order the order by list |
| 267 |
*/ |
| 268 |
public void setOrder(ArrayList<QueryOrderBy> order) { |
| 269 |
orderList = order; |
| 270 |
} |
| 271 |
|
| 272 |
/** |
| 273 |
* Whether the query has an order. |
| 274 |
* |
| 275 |
* @return true if it has |
| 276 |
*/ |
| 277 |
public boolean hasOrder() { |
| 278 |
return orderList != null || sort != null; |
| 279 |
} |
| 280 |
|
| 281 |
/** |
| 282 |
* Returns FOR UPDATE clause, if any. |
| 283 |
* @return FOR UPDATE clause or {@code null} |
| 284 |
*/ |
| 285 |
public ForUpdate getForUpdate() { |
| 286 |
return null; |
| 287 |
} |
| 288 |
|
| 289 |
/** |
| 290 |
* Set the FOR UPDATE clause. |
| 291 |
* |
| 292 |
* @param forUpdate the new FOR UPDATE clause |
| 293 |
*/ |
| 294 |
public abstract void setForUpdate(ForUpdate forUpdate); |
| 295 |
|
| 296 |
/** |
| 297 |
* Get the column count of this query. |
| 298 |
* |
| 299 |
* @return the column count |
| 300 |
*/ |
| 301 |
public int getColumnCount() { |
| 302 |
return visibleColumnCount; |
| 303 |
} |
| 304 |
|
| 305 |
/** |
| 306 |
* Returns data type of rows. |
| 307 |
* |
| 308 |
* @return data type of rows |
| 309 |
*/ |
| 310 |
public TypeInfo getRowDataType() { |
| 311 |
if (visibleColumnCount == 1) { |
| 312 |
return expressionArray[0].getType(); |
| 313 |
} |
| 314 |
return TypeInfo.getTypeInfo(Value.ROW, -1L, -1, new ExtTypeInfoRow(expressionArray, visibleColumnCount)); |
| 315 |
} |
| 316 |
|
| 317 |
/** |
| 318 |
* Map the columns to the given column resolver. |
| 319 |
* |
| 320 |
* @param resolver |
| 321 |
* the resolver |
| 322 |
* @param level |
| 323 |
* the subquery level (0 is the top level query, 1 is the first |
| 324 |
* subquery level) |
| 325 |
*/ |
| 326 |
public abstract void mapColumns(ColumnResolver resolver, int level); |
| 327 |
|
| 328 |
/** |
| 329 |
* Change the evaluatable flag. This is used when building the execution |
| 330 |
* plan. |
| 331 |
* |
| 332 |
* @param tableFilter the table filter |
| 333 |
* @param b the new value |
| 334 |
*/ |
| 335 |
public abstract void setEvaluatable(TableFilter tableFilter, boolean b); |
| 336 |
|
| 337 |
/** |
| 338 |
* Add a condition to the query. This is used for views. |
| 339 |
* |
| 340 |
* @param param the parameter |
| 341 |
* @param columnId the column index (0 meaning the first column) |
| 342 |
* @param comparisonType the comparison type |
| 343 |
*/ |
| 344 |
public abstract void addGlobalCondition(Parameter param, int columnId, |
| 345 |
int comparisonType); |
| 346 |
|
| 347 |
/** |
| 348 |
* Check whether adding condition to the query is allowed. This is not |
| 349 |
* allowed for views that have an order by and a limit, as it would affect |
| 350 |
* the returned results. |
| 351 |
* |
| 352 |
* @return true if adding global conditions is allowed |
| 353 |
*/ |
| 354 |
public abstract boolean allowGlobalConditions(); |
| 355 |
|
| 356 |
/** |
| 357 |
* Check if this expression and all sub-expressions can fulfill a criteria. |
| 358 |
* If any part returns false, the result is false. |
| 359 |
* |
| 360 |
* @param visitor the visitor |
| 361 |
* @return if the criteria can be fulfilled |
| 362 |
*/ |
| 363 |
public abstract boolean isEverything(ExpressionVisitor visitor); |
| 364 |
|
| 365 |
@Override |
| 366 |
public boolean isReadOnly() { |
| 367 |
return isEverything(ExpressionVisitor.READONLY_VISITOR); |
| 368 |
} |
| 369 |
|
| 370 |
/** |
| 371 |
* Update all aggregate function values. |
| 372 |
* |
| 373 |
* @param s the session |
| 374 |
* @param stage select stage |
| 375 |
*/ |
| 376 |
public abstract void updateAggregate(SessionLocal s, int stage); |
| 377 |
|
| 378 |
/** |
| 379 |
* Call the before triggers on all tables. |
| 380 |
*/ |
| 381 |
public abstract void fireBeforeSelectTriggers(); |
| 382 |
|
| 383 |
/** |
| 384 |
* Set the distinct flag only if it is possible, may be used as a possible |
| 385 |
* optimization only. |
| 386 |
*/ |
| 387 |
public void setDistinctIfPossible() { |
| 388 |
if (!isAnyDistinct() && offsetExpr == null && fetchExpr == null) { |
| 389 |
distinct = true; |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
/** |
| 394 |
* @return whether this query is a plain {@code DISTINCT} query |
| 395 |
*/ |
| 396 |
public boolean isStandardDistinct() { |
| 397 |
return distinct; |
| 398 |
} |
| 399 |
|
| 400 |
/** |
| 401 |
* @return whether this query is a {@code DISTINCT} or |
| 402 |
* {@code DISTINCT ON (...)} query |
| 403 |
*/ |
| 404 |
public boolean isAnyDistinct() { |
| 405 |
return distinct; |
| 406 |
} |
| 407 |
|
| 408 |
/** |
| 409 |
* Returns whether results support random access. |
| 410 |
* |
| 411 |
* @return whether results support random access |
| 412 |
*/ |
| 413 |
public boolean isRandomAccessResult() { |
| 414 |
return randomAccessResult; |
| 415 |
} |
| 416 |
|
| 417 |
/** |
| 418 |
* Whether results need to support random access. |
| 419 |
* |
| 420 |
* @param b the new value |
| 421 |
*/ |
| 422 |
public void setRandomAccessResult(boolean b) { |
| 423 |
randomAccessResult = b; |
| 424 |
} |
| 425 |
|
| 426 |
@Override |
| 427 |
public boolean isQuery() { |
| 428 |
return true; |
| 429 |
} |
| 430 |
|
| 431 |
@Override |
| 432 |
public boolean isTransactional() { |
| 433 |
return true; |
| 434 |
} |
| 435 |
|
| 436 |
/** |
| 437 |
* Disable caching of result sets. |
| 438 |
*/ |
| 439 |
public void disableCache() { |
| 440 |
this.noCache = true; |
| 441 |
} |
| 442 |
|
| 443 |
private boolean sameResultAsLast(Value[] params, Value[] lastParams, long lastEval) { |
| 444 |
if (!cacheableChecked) { |
| 445 |
long max = getMaxDataModificationId(); |
| 446 |
noCache = max == Long.MAX_VALUE; |
| 447 |
if (!isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR) || |
| 448 |
!isEverything(ExpressionVisitor.INDEPENDENT_VISITOR)) { |
| 449 |
noCache = true; |
| 450 |
} |
| 451 |
cacheableChecked = true; |
| 452 |
} |
| 453 |
if (noCache) { |
| 454 |
return false; |
| 455 |
} |
| 456 |
for (int i = 0; i < params.length; i++) { |
| 457 |
Value a = lastParams[i], b = params[i]; |
| 458 |
// Derived tables can have gaps in parameters |
| 459 |
if (a != null && !a.equals(b)) { |
| 460 |
return false; |
| 461 |
} |
| 462 |
} |
| 463 |
return getMaxDataModificationId() <= lastEval; |
| 464 |
} |
| 465 |
|
| 466 |
private Value[] getParameterValues() { |
| 467 |
ArrayList<Parameter> list = getParameters(); |
| 468 |
if (list == null) { |
| 469 |
return Value.EMPTY_VALUES; |
| 470 |
} |
| 471 |
int size = list.size(); |
| 472 |
Value[] params = new Value[size]; |
| 473 |
for (int i = 0; i < size; i++) { |
| 474 |
Parameter parameter = list.get(i); |
| 475 |
// Derived tables can have gaps in parameters |
| 476 |
params[i] = parameter != null ? parameter.getParamValue() : null; |
| 477 |
} |
| 478 |
return params; |
| 479 |
} |
| 480 |
|
| 481 |
@Override |
| 482 |
public final ResultInterface query(long maxrows) { |
| 483 |
return query(maxrows, null); |
| 484 |
} |
| 485 |
|
| 486 |
/** |
| 487 |
* Execute the query, writing the result to the target result. |
| 488 |
* |
| 489 |
* @param limit the maximum number of rows to return |
| 490 |
* @param target the target result (null will return the result) |
| 491 |
* @return the result set (if the target is not set). |
| 492 |
*/ |
| 493 |
public final ResultInterface query(long limit, ResultTarget target) { |
| 494 |
if (isUnion()) { |
| 495 |
// union doesn't always know the parameter list of the left and |
| 496 |
// right queries |
| 497 |
return queryWithoutCacheLazyCheck(limit, target); |
| 498 |
} |
| 499 |
fireBeforeSelectTriggers(); |
| 500 |
if (noCache || !getDatabase().getOptimizeReuseResults() || |
| 501 |
(session.isLazyQueryExecution() && !neverLazy)) { |
| 502 |
return queryWithoutCacheLazyCheck(limit, target); |
| 503 |
} |
| 504 |
Value[] params = getParameterValues(); |
| 505 |
long now = getDatabase().getModificationDataId(); |
| 506 |
if (isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) { |
| 507 |
if (lastResult != null && !lastResult.isClosed() && |
| 508 |
limit == lastLimit) { |
| 509 |
if (sameResultAsLast(params, lastParameters, lastEvaluated)) { |
| 510 |
lastResult = lastResult.createShallowCopy(session); |
| 511 |
if (lastResult != null) { |
| 512 |
lastResult.reset(); |
| 513 |
return lastResult; |
| 514 |
} |
| 515 |
} |
| 516 |
} |
| 517 |
} |
| 518 |
lastParameters = params; |
| 519 |
closeLastResult(); |
| 520 |
ResultInterface r = queryWithoutCacheLazyCheck(limit, target); |
| 521 |
lastResult = r; |
| 522 |
lastExists = null; |
| 523 |
lastEvaluated = now; |
| 524 |
lastLimit = limit; |
| 525 |
return r; |
| 526 |
} |
| 527 |
|
| 528 |
private void closeLastResult() { |
| 529 |
if (lastResult != null) { |
| 530 |
lastResult.close(); |
| 531 |
} |
| 532 |
} |
| 533 |
|
| 534 |
/** |
| 535 |
* Execute the EXISTS predicate over the query. |
| 536 |
* |
| 537 |
* @return EXISTS predicate result |
| 538 |
*/ |
| 539 |
public final boolean exists() { |
| 540 |
if (isUnion()) { |
| 541 |
// union doesn't always know the parameter list of the left and |
| 542 |
// right queries |
| 543 |
return executeExists(); |
| 544 |
} |
| 545 |
fireBeforeSelectTriggers(); |
| 546 |
if (noCache || !getDatabase().getOptimizeReuseResults()) { |
| 547 |
return executeExists(); |
| 548 |
} |
| 549 |
Value[] params = getParameterValues(); |
| 550 |
long now = getDatabase().getModificationDataId(); |
| 551 |
if (isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) { |
| 552 |
if (lastExists != null) { |
| 553 |
if (sameResultAsLast(params, lastParameters, lastEvaluated)) { |
| 554 |
return lastExists; |
| 555 |
} |
| 556 |
} |
| 557 |
} |
| 558 |
lastParameters = params; |
| 559 |
boolean exists = executeExists(); |
| 560 |
lastExists = exists; |
| 561 |
lastResult = null; |
| 562 |
lastEvaluated = now; |
| 563 |
return exists; |
| 564 |
} |
| 565 |
|
| 566 |
private boolean executeExists() { |
| 567 |
ResultInterface r = queryWithoutCacheLazyCheck(1L, null); |
| 568 |
boolean exists = r.hasNext(); |
| 569 |
r.close(); |
| 570 |
return exists; |
| 571 |
} |
| 572 |
|
| 573 |
/** |
| 574 |
* Initialize the order by list. This call may extend the expressions list. |
| 575 |
* |
| 576 |
* @param expressionSQL the select list SQL snippets |
| 577 |
* @param mustBeInResult all order by expressions must be in the select list |
| 578 |
* @param filters the table filters |
| 579 |
* @return {@code true} if ORDER BY clause is preserved, {@code false} |
| 580 |
* otherwise |
| 581 |
*/ |
| 582 |
boolean initOrder(ArrayList<String> expressionSQL, boolean mustBeInResult, ArrayList<TableFilter> filters) { |
| 583 |
for (Iterator<QueryOrderBy> i = orderList.iterator(); i.hasNext();) { |
| 584 |
QueryOrderBy o = i.next(); |
| 585 |
Expression e = o.expression; |
| 586 |
if (e == null) { |
| 587 |
continue; |
| 588 |
} |
| 589 |
if (e.isConstant()) { |
| 590 |
i.remove(); |
| 591 |
continue; |
| 592 |
} |
| 593 |
int idx = initExpression(expressionSQL, e, mustBeInResult, filters); |
| 594 |
o.columnIndexExpr = ValueExpression.get(ValueInteger.get(idx + 1)); |
| 595 |
o.expression = expressions.get(idx).getNonAliasExpression(); |
| 596 |
} |
| 597 |
if (orderList.isEmpty()) { |
| 598 |
orderList = null; |
| 599 |
return false; |
| 600 |
} |
| 601 |
return true; |
| 602 |
} |
| 603 |
|
| 604 |
/** |
| 605 |
* Initialize the 'ORDER BY' or 'DISTINCT' expressions. |
| 606 |
* |
| 607 |
* @param expressionSQL the select list SQL snippets |
| 608 |
* @param e the expression. |
| 609 |
* @param mustBeInResult all order by expressions must be in the select list |
| 610 |
* @param filters the table filters. |
| 611 |
* @return index on the expression in the {@link #expressions} list. |
| 612 |
*/ |
| 613 |
int initExpression(ArrayList<String> expressionSQL, Expression e, boolean mustBeInResult, |
| 614 |
ArrayList<TableFilter> filters) { |
| 615 |
Database db = getDatabase(); |
| 616 |
// special case: SELECT 1 AS A FROM DUAL ORDER BY A |
| 617 |
// (oracle supports it, but only in order by, not in group by and |
| 618 |
// not in having): |
| 619 |
// SELECT 1 AS A FROM DUAL ORDER BY -A |
| 620 |
if (e instanceof ExpressionColumn) { |
| 621 |
// order by expression |
| 622 |
ExpressionColumn exprCol = (ExpressionColumn) e; |
| 623 |
String tableAlias = exprCol.getOriginalTableAliasName(); |
| 624 |
String col = exprCol.getOriginalColumnName(); |
| 625 |
for (int j = 0, visible = getColumnCount(); j < visible; j++) { |
| 626 |
Expression ec = expressions.get(j); |
| 627 |
if (ec instanceof ExpressionColumn) { |
| 628 |
// select expression |
| 629 |
ExpressionColumn c = (ExpressionColumn) ec; |
| 630 |
if (!db.equalsIdentifiers(col, c.getColumnName(session, j))) { |
| 631 |
continue; |
| 632 |
} |
| 633 |
if (tableAlias == null) { |
| 634 |
return j; |
| 635 |
} |
| 636 |
String ca = c.getOriginalTableAliasName(); |
| 637 |
if (ca != null) { |
| 638 |
if (db.equalsIdentifiers(ca, tableAlias)) { |
| 639 |
return j; |
| 640 |
} |
| 641 |
} else if (filters != null) { |
| 642 |
// select id from test order by test.id |
| 643 |
for (TableFilter f : filters) { |
| 644 |
if (db.equalsIdentifiers(f.getTableAlias(), tableAlias)) { |
| 645 |
return j; |
| 646 |
} |
| 647 |
} |
| 648 |
} |
| 649 |
} else if (ec instanceof Alias) { |
| 650 |
if (tableAlias == null && db.equalsIdentifiers(col, ec.getAlias(session, j))) { |
| 651 |
return j; |
| 652 |
} |
| 653 |
Expression ec2 = ec.getNonAliasExpression(); |
| 654 |
if (ec2 instanceof ExpressionColumn) { |
| 655 |
ExpressionColumn c2 = (ExpressionColumn) ec2; |
| 656 |
String ta = exprCol.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES); |
| 657 |
String tb = c2.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES); |
| 658 |
String s2 = c2.getColumnName(session, j); |
| 659 |
if (db.equalsIdentifiers(col, s2) && db.equalsIdentifiers(ta, tb)) { |
| 660 |
return j; |
| 661 |
} |
| 662 |
} |
| 663 |
} |
| 664 |
} |
| 665 |
} else if (expressionSQL != null) { |
| 666 |
String s = e.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES); |
| 667 |
for (int j = 0, size = expressionSQL.size(); j < size; j++) { |
| 668 |
if (db.equalsIdentifiers(expressionSQL.get(j), s)) { |
| 669 |
return j; |
| 670 |
} |
| 671 |
} |
| 672 |
} |
| 673 |
if (expressionSQL == null |
| 674 |
|| mustBeInResult && !db.getMode().allowUnrelatedOrderByExpressionsInDistinctQueries |
| 675 |
&& !checkOrderOther(session, e, expressionSQL)) { |
| 676 |
throw DbException.get(ErrorCode.ORDER_BY_NOT_IN_RESULT, e.getTraceSQL()); |
| 677 |
} |
| 678 |
int idx = expressions.size(); |
| 679 |
expressions.add(e); |
| 680 |
expressionSQL.add(e.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES)); |
| 681 |
return idx; |
| 682 |
} |
| 683 |
|
| 684 |
/** |
| 685 |
* An additional check for expression in ORDER BY list for DISTINCT selects |
| 686 |
* that was not matched with selected expressions in regular way. This |
| 687 |
* method allows expressions based only on selected expressions in different |
| 688 |
* complicated ways with functions, comparisons, or operators. |
| 689 |
* |
| 690 |
* @param session session |
| 691 |
* @param expr expression to check |
| 692 |
* @param expressionSQL SQL of allowed expressions |
| 693 |
* @return whether the specified expression should be allowed in ORDER BY |
| 694 |
* list of DISTINCT select |
| 695 |
*/ |
| 696 |
private static boolean checkOrderOther(SessionLocal session, Expression expr, ArrayList<String> expressionSQL) { |
| 697 |
if (expr == null || expr.isConstant()) { |
| 698 |
// ValueExpression, null expression in CASE, or other |
| 699 |
return true; |
| 700 |
} |
| 701 |
String exprSQL = expr.getSQL(DEFAULT_SQL_FLAGS, WITHOUT_PARENTHESES); |
| 702 |
for (String sql: expressionSQL) { |
| 703 |
if (session.getDatabase().equalsIdentifiers(exprSQL, sql)) { |
| 704 |
return true; |
| 705 |
} |
| 706 |
} |
| 707 |
int count = expr.getSubexpressionCount(); |
| 708 |
if (!expr.isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) { |
| 709 |
return false; |
| 710 |
} else if (count <= 0) { |
| 711 |
// Expression is an ExpressionColumn, Parameter, SequenceValue or |
| 712 |
// has other unsupported type without subexpressions |
| 713 |
return false; |
| 714 |
} |
| 715 |
for (int i = 0; i < count; i++) { |
| 716 |
if (!checkOrderOther(session, expr.getSubexpression(i), expressionSQL)) { |
| 717 |
return false; |
| 718 |
} |
| 719 |
} |
| 720 |
return true; |
| 721 |
} |
| 722 |
|
| 723 |
/** |
| 724 |
* Create a {@link SortOrder} object given the list of {@link QueryOrderBy} |
| 725 |
* objects. |
| 726 |
* |
| 727 |
* @param orderList a list of {@link QueryOrderBy} elements |
| 728 |
* @param expressionCount the number of columns in the query |
| 729 |
*/ |
| 730 |
void prepareOrder(ArrayList<QueryOrderBy> orderList, int expressionCount) { |
| 731 |
int size = orderList.size(); |
| 732 |
int[] index = new int[size]; |
| 733 |
int[] sortType = new int[size]; |
| 734 |
for (int i = 0; i < size; i++) { |
| 735 |
QueryOrderBy o = orderList.get(i); |
| 736 |
int idx; |
| 737 |
boolean reverse = false; |
| 738 |
Value v = o.columnIndexExpr.getValue(null); |
| 739 |
if (v == ValueNull.INSTANCE) { |
| 740 |
// parameter not yet set - order by first column |
| 741 |
idx = 0; |
| 742 |
} else { |
| 743 |
idx = v.getInt(); |
| 744 |
if (idx < 0) { |
| 745 |
reverse = true; |
| 746 |
idx = -idx; |
| 747 |
} |
| 748 |
idx -= 1; |
| 749 |
if (idx < 0 || idx >= expressionCount) { |
| 750 |
throw DbException.get(ErrorCode.ORDER_BY_NOT_IN_RESULT, Integer.toString(idx + 1)); |
| 751 |
} |
| 752 |
} |
| 753 |
index[i] = idx; |
| 754 |
int type = o.sortType; |
| 755 |
if (reverse) { |
| 756 |
// TODO NULLS FIRST / LAST should be inverted too? |
| 757 |
type ^= SortOrder.DESCENDING; |
| 758 |
} |
| 759 |
sortType[i] = type; |
| 760 |
} |
| 761 |
sort = new SortOrder(session, index, sortType, orderList); |
| 762 |
this.orderList = null; |
| 763 |
} |
| 764 |
|
| 765 |
/** |
| 766 |
* Removes constant expressions from the sort order. |
| 767 |
* |
| 768 |
* Some constants are detected only after optimization of expressions, this |
| 769 |
* method removes them from the sort order only. They are currently |
| 770 |
* preserved in the list of expressions. |
| 771 |
*/ |
| 772 |
void cleanupOrder() { |
| 773 |
int sourceIndexes[] = sort.getQueryColumnIndexes(); |
| 774 |
int count = sourceIndexes.length; |
| 775 |
int constants = 0; |
| 776 |
for (int i = 0; i < count; i++) { |
| 777 |
if (expressions.get(sourceIndexes[i]).isConstant()) { |
| 778 |
constants++; |
| 779 |
} |
| 780 |
} |
| 781 |
if (constants == 0) { |
| 782 |
return; |
| 783 |
} |
| 784 |
if (constants == count) { |
| 785 |
sort = null; |
| 786 |
return; |
| 787 |
} |
| 788 |
int size = count - constants; |
| 789 |
int[] indexes = new int[size]; |
| 790 |
int[] sortTypes = new int[size]; |
| 791 |
int[] sourceSortTypes = sort.getSortTypes(); |
| 792 |
ArrayList<QueryOrderBy> orderList = sort.getOrderList(); |
| 793 |
for (int i = 0, j = 0; j < size; i++) { |
| 794 |
if (!expressions.get(sourceIndexes[i]).isConstant()) { |
| 795 |
indexes[j] = sourceIndexes[i]; |
| 796 |
sortTypes[j] = sourceSortTypes[i]; |
| 797 |
j++; |
| 798 |
} else { |
| 799 |
orderList.remove(j); |
| 800 |
} |
| 801 |
} |
| 802 |
sort = new SortOrder(session, indexes, sortTypes, orderList); |
| 803 |
} |
| 804 |
|
| 805 |
@Override |
| 806 |
public int getType() { |
| 807 |
return CommandInterface.SELECT; |
| 808 |
} |
| 809 |
|
| 810 |
public void setOffset(Expression offset) { |
| 811 |
this.offsetExpr = offset; |
| 812 |
} |
| 813 |
|
| 814 |
public Expression getOffset() { |
| 815 |
return offsetExpr; |
| 816 |
} |
| 817 |
|
| 818 |
public void setFetch(Expression fetch) { |
| 819 |
this.fetchExpr = fetch; |
| 820 |
} |
| 821 |
|
| 822 |
public Expression getFetch() { |
| 823 |
return fetchExpr; |
| 824 |
} |
| 825 |
|
| 826 |
public void setFetchPercent(boolean fetchPercent) { |
| 827 |
this.fetchPercent = fetchPercent; |
| 828 |
} |
| 829 |
|
| 830 |
public boolean isFetchPercent() { |
| 831 |
return fetchPercent; |
| 832 |
} |
| 833 |
|
| 834 |
public void setWithTies(boolean withTies) { |
| 835 |
this.withTies = withTies; |
| 836 |
} |
| 837 |
|
| 838 |
public boolean isWithTies() { |
| 839 |
return withTies; |
| 840 |
} |
| 841 |
|
| 842 |
/** |
| 843 |
* Add a parameter to the parameter list. |
| 844 |
* |
| 845 |
* @param param the parameter to add |
| 846 |
*/ |
| 847 |
void addParameter(Parameter param) { |
| 848 |
if (parameters == null) { |
| 849 |
parameters = Utils.newSmallArrayList(); |
| 850 |
} |
| 851 |
parameters.add(param); |
| 852 |
} |
| 853 |
|
| 854 |
public final long getMaxDataModificationId() { |
| 855 |
ExpressionVisitor visitor = ExpressionVisitor.getMaxModificationIdVisitor(); |
| 856 |
isEverything(visitor); |
| 857 |
return Math.max(visitor.getMaxDataModificationId(), session.getSnapshotDataModificationId()); |
| 858 |
} |
| 859 |
|
| 860 |
/** |
| 861 |
* Appends ORDER BY, OFFSET, and FETCH clauses to the plan. |
| 862 |
* |
| 863 |
* @param builder query plan string builder. |
| 864 |
* @param sqlFlags formatting flags |
| 865 |
* @param expressions the array of expressions |
| 866 |
*/ |
| 867 |
void appendEndOfQueryToSQL(StringBuilder builder, int sqlFlags, Expression[] expressions) { |
| 868 |
if (sort != null) { |
| 869 |
sort.getSQL(builder.append("\nORDER BY "), expressions, visibleColumnCount, sqlFlags); |
| 870 |
} else if (orderList != null) { |
| 871 |
builder.append("\nORDER BY "); |
| 872 |
for (int i = 0, l = orderList.size(); i < l; i++) { |
| 873 |
if (i > 0) { |
| 874 |
builder.append(", "); |
| 875 |
} |
| 876 |
orderList.get(i).getSQL(builder, sqlFlags); |
| 877 |
} |
| 878 |
} |
| 879 |
if (offsetExpr != null) { |
| 880 |
String count = offsetExpr.getSQL(sqlFlags, WITHOUT_PARENTHESES); |
| 881 |
builder.append("\nOFFSET ").append(count).append("1".equals(count) ? " ROW" : " ROWS"); |
| 882 |
} |
| 883 |
if (fetchExpr != null) { |
| 884 |
builder.append("\nFETCH ").append(offsetExpr != null ? "NEXT" : "FIRST"); |
| 885 |
String count = fetchExpr.getSQL(sqlFlags, WITHOUT_PARENTHESES); |
| 886 |
boolean withCount = fetchPercent || !"1".equals(count); |
| 887 |
if (withCount) { |
| 888 |
builder.append(' ').append(count); |
| 889 |
if (fetchPercent) { |
| 890 |
builder.append(" PERCENT"); |
| 891 |
} |
| 892 |
} |
| 893 |
builder.append(!withCount ? " ROW" : " ROWS") |
| 894 |
.append(withTies ? " WITH TIES" : " ONLY"); |
| 895 |
} |
| 896 |
} |
| 897 |
|
| 898 |
/** |
| 899 |
* Evaluates OFFSET and FETCH expressions. |
| 900 |
* |
| 901 |
* @param maxRows |
| 902 |
* additional limit |
| 903 |
* @return the evaluated values |
| 904 |
*/ |
| 905 |
OffsetFetch getOffsetFetch(long maxRows) { |
| 906 |
long offset; |
| 907 |
if (offsetExpr != null) { |
| 908 |
Value v = offsetExpr.getValue(session); |
| 909 |
if (v == ValueNull.INSTANCE || (offset = v.getLong()) < 0) { |
| 910 |
throw DbException.getInvalidValueException("result OFFSET", v); |
| 911 |
} |
| 912 |
} else { |
| 913 |
offset = 0; |
| 914 |
} |
| 915 |
long fetch = maxRows == 0 ? -1 : maxRows; |
| 916 |
if (fetchExpr != null) { |
| 917 |
Value v = fetchExpr.getValue(session); |
| 918 |
long l; |
| 919 |
if (v == ValueNull.INSTANCE || (l = v.getLong()) < 0) { |
| 920 |
throw DbException.getInvalidValueException("result FETCH", v); |
| 921 |
} |
| 922 |
fetch = fetch < 0 ? l : Math.min(l, fetch); |
| 923 |
} |
| 924 |
boolean fetchPercent = this.fetchPercent; |
| 925 |
if (fetchPercent) { |
| 926 |
if (fetch > 100) { |
| 927 |
throw DbException.getInvalidValueException("result FETCH PERCENT", fetch); |
| 928 |
} |
| 929 |
// 0 PERCENT means 0 |
| 930 |
if (fetch == 0) { |
| 931 |
fetchPercent = false; |
| 932 |
} |
| 933 |
} |
| 934 |
return new OffsetFetch(offset, fetch, fetchPercent); |
| 935 |
} |
| 936 |
|
| 937 |
/** |
| 938 |
* Applies limits, if any, to a result and makes it ready for value |
| 939 |
* retrieval. |
| 940 |
* |
| 941 |
* @param result |
| 942 |
* the result |
| 943 |
* @param offset |
| 944 |
* OFFSET value |
| 945 |
* @param fetch |
| 946 |
* FETCH value |
| 947 |
* @param fetchPercent |
| 948 |
* whether FETCH value is a PERCENT value |
| 949 |
* @param target |
| 950 |
* target result or null |
| 951 |
* @return the result or null |
| 952 |
*/ |
| 953 |
LocalResult finishResult(LocalResult result, long offset, long fetch, boolean fetchPercent, ResultTarget target) { |
| 954 |
if (offset != 0) { |
| 955 |
result.setOffset(offset); |
| 956 |
} |
| 957 |
if (fetch >= 0) { |
| 958 |
result.setLimit(fetch); |
| 959 |
result.setFetchPercent(fetchPercent); |
| 960 |
if (withTies) { |
| 961 |
result.setWithTies(sort); |
| 962 |
} |
| 963 |
} |
| 964 |
result.done(); |
| 965 |
if (randomAccessResult && !distinct) { |
| 966 |
result = convertToDistinct(result); |
| 967 |
} |
| 968 |
if (target != null) { |
| 969 |
while (result.next()) { |
| 970 |
target.addRow(result.currentRow()); |
| 971 |
} |
| 972 |
result.close(); |
| 973 |
return null; |
| 974 |
} |
| 975 |
return result; |
| 976 |
} |
| 977 |
|
| 978 |
/** |
| 979 |
* Convert a result into a distinct result, using the current columns. |
| 980 |
* |
| 981 |
* @param result the source |
| 982 |
* @return the distinct result |
| 983 |
*/ |
| 984 |
LocalResult convertToDistinct(ResultInterface result) { |
| 985 |
LocalResult distinctResult = new LocalResult(session, expressionArray, visibleColumnCount, resultColumnCount); |
| 986 |
distinctResult.setDistinct(); |
| 987 |
result.reset(); |
| 988 |
while (result.next()) { |
| 989 |
distinctResult.addRow(result.currentRow()); |
| 990 |
} |
| 991 |
result.close(); |
| 992 |
distinctResult.done(); |
| 993 |
return distinctResult; |
| 994 |
} |
| 995 |
|
| 996 |
/** |
| 997 |
* Converts this query to a table or a view. |
| 998 |
* |
| 999 |
* @param alias alias name for the view |
| 1000 |
* @param columnTemplates column templates, or {@code null} |
| 1001 |
* @param parameters the parameters |
| 1002 |
* @param forCreateView if true, a system session will be used for the view |
| 1003 |
* @param topQuery the top level query |
| 1004 |
* @return the table or the view |
| 1005 |
*/ |
| 1006 |
public Table toTable(String alias, Column[] columnTemplates, ArrayList<Parameter> parameters, |
| 1007 |
boolean forCreateView, Query topQuery) { |
| 1008 |
setParameterList(new ArrayList<>(parameters)); |
| 1009 |
if (!checkInit) { |
| 1010 |
init(); |
| 1011 |
} |
| 1012 |
return new DerivedTable(forCreateView ? getDatabase().getSystemSession() : session, alias, |
| 1013 |
columnTemplates, this, topQuery); |
| 1014 |
} |
| 1015 |
|
| 1016 |
@Override |
| 1017 |
public void collectDependencies(HashSet<DbObject> dependencies) { |
| 1018 |
ExpressionVisitor visitor = ExpressionVisitor.getDependenciesVisitor(dependencies); |
| 1019 |
isEverything(visitor); |
| 1020 |
} |
| 1021 |
|
| 1022 |
/** |
| 1023 |
* Check if this query will always return the same value and has no side |
| 1024 |
* effects. |
| 1025 |
* |
| 1026 |
* @return if this query will always return the same value and has no side |
| 1027 |
* effects. |
| 1028 |
*/ |
| 1029 |
public boolean isConstantQuery() { |
| 1030 |
return !hasOrder() && (offsetExpr == null || offsetExpr.isConstant()) |
| 1031 |
&& (fetchExpr == null || fetchExpr.isConstant()); |
| 1032 |
} |
| 1033 |
|
| 1034 |
/** |
| 1035 |
* If this query is determined as a single-row query, returns a replacement |
| 1036 |
* expression. |
| 1037 |
* |
| 1038 |
* @return the expression, or {@code null} |
| 1039 |
*/ |
| 1040 |
public Expression getIfSingleRow() { |
| 1041 |
return null; |
| 1042 |
} |
| 1043 |
|
| 1044 |
@Override |
| 1045 |
public boolean isRetryable() { |
| 1046 |
ForUpdate forUpdate = getForUpdate(); |
| 1047 |
return forUpdate == null || forUpdate.getType() == ForUpdate.Type.SKIP_LOCKED; |
| 1048 |
} |
| 1049 |
|
| 1050 |
} |