| 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; |
| 7 |
|
| 8 |
import java.util.ArrayList; |
| 9 |
import java.util.HashSet; |
| 10 |
import java.util.List; |
| 11 |
import org.h2.api.DatabaseEventListener; |
| 12 |
import org.h2.api.ErrorCode; |
| 13 |
import org.h2.engine.Database; |
| 14 |
import org.h2.engine.DbObject; |
| 15 |
import org.h2.engine.SessionLocal; |
| 16 |
import org.h2.expression.Expression; |
| 17 |
import org.h2.expression.Parameter; |
| 18 |
import org.h2.message.DbException; |
| 19 |
import org.h2.message.Trace; |
| 20 |
import org.h2.result.ResultInterface; |
| 21 |
import org.h2.table.TableView; |
| 22 |
import org.h2.util.HasSQL; |
| 23 |
|
| 24 |
/** |
| 25 |
* A prepared statement. |
| 26 |
*/ |
| 27 |
public abstract class Prepared { |
| 28 |
|
| 29 |
/** |
| 30 |
* The session. |
| 31 |
*/ |
| 32 |
protected SessionLocal session; |
| 33 |
|
| 34 |
/** |
| 35 |
* The SQL string. |
| 36 |
*/ |
| 37 |
protected String sqlStatement; |
| 38 |
|
| 39 |
/** |
| 40 |
* The SQL tokens. |
| 41 |
*/ |
| 42 |
protected ArrayList<Token> sqlTokens; |
| 43 |
|
| 44 |
/** |
| 45 |
* Whether to create a new object (for indexes). |
| 46 |
*/ |
| 47 |
protected boolean create = true; |
| 48 |
|
| 49 |
/** |
| 50 |
* The list of parameters. |
| 51 |
*/ |
| 52 |
protected ArrayList<Parameter> parameters; |
| 53 |
|
| 54 |
private boolean withParamValues; |
| 55 |
|
| 56 |
/** |
| 57 |
* If the query should be prepared before each execution. This is set for |
| 58 |
* queries with LIKE ?, because the query plan depends on the parameter |
| 59 |
* value. |
| 60 |
*/ |
| 61 |
protected boolean prepareAlways; |
| 62 |
|
| 63 |
private long modificationMetaId; |
| 64 |
private Command command; |
| 65 |
/** |
| 66 |
* Used to preserve object identities on database startup. {@code 0} if |
| 67 |
* object is not stored, {@code -1} if object is stored and its ID is |
| 68 |
* already read, {@code >0} if object is stored and its id is not yet read. |
| 69 |
*/ |
| 70 |
private int persistedObjectId; |
| 71 |
private long currentRowNumber; |
| 72 |
private int rowScanCount; |
| 73 |
/** |
| 74 |
* Common table expressions (CTE) in queries require us to create temporary views, |
| 75 |
* which need to be cleaned up once a command is done executing. |
| 76 |
*/ |
| 77 |
private List<TableView> cteCleanups; |
| 78 |
|
| 79 |
/** |
| 80 |
* Create a new object. |
| 81 |
* |
| 82 |
* @param session the session |
| 83 |
*/ |
| 84 |
public Prepared(SessionLocal session) { |
| 85 |
this.session = session; |
| 86 |
modificationMetaId = getDatabase().getModificationMetaId(); |
| 87 |
} |
| 88 |
|
| 89 |
/** |
| 90 |
* Check if this command is transactional. |
| 91 |
* If it is not, then it forces the current transaction to commit. |
| 92 |
* |
| 93 |
* @return true if it is |
| 94 |
*/ |
| 95 |
public abstract boolean isTransactional(); |
| 96 |
|
| 97 |
/** |
| 98 |
* Get an empty result set containing the meta data. |
| 99 |
* |
| 100 |
* @return the result set |
| 101 |
*/ |
| 102 |
public abstract ResultInterface queryMeta(); |
| 103 |
|
| 104 |
|
| 105 |
/** |
| 106 |
* Get the command type as defined in CommandInterface |
| 107 |
* |
| 108 |
* @return the statement type |
| 109 |
*/ |
| 110 |
public abstract int getType(); |
| 111 |
|
| 112 |
/** |
| 113 |
* Check if this command is read only. |
| 114 |
* |
| 115 |
* @return true if it is |
| 116 |
*/ |
| 117 |
public boolean isReadOnly() { |
| 118 |
return false; |
| 119 |
} |
| 120 |
|
| 121 |
/** |
| 122 |
* Check if the statement needs to be re-compiled. |
| 123 |
* |
| 124 |
* @return true if it must |
| 125 |
*/ |
| 126 |
public boolean needRecompile() { |
| 127 |
Database db = getDatabase(); |
| 128 |
if (db == null) { |
| 129 |
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "database closed"); |
| 130 |
} |
| 131 |
// parser: currently, compiling every create/drop/... twice |
| 132 |
// because needRecompile return true even for the first execution |
| 133 |
return prepareAlways || |
| 134 |
modificationMetaId < db.getModificationMetaId() || |
| 135 |
db.getSettings().recompileAlways; |
| 136 |
} |
| 137 |
|
| 138 |
/** |
| 139 |
* Get the meta data modification id of the database when this statement was |
| 140 |
* compiled. |
| 141 |
* |
| 142 |
* @return the meta data modification id |
| 143 |
*/ |
| 144 |
long getModificationMetaId() { |
| 145 |
return modificationMetaId; |
| 146 |
} |
| 147 |
|
| 148 |
/** |
| 149 |
* Set the meta data modification id of this statement. |
| 150 |
* |
| 151 |
* @param id the new id |
| 152 |
*/ |
| 153 |
void setModificationMetaId(long id) { |
| 154 |
this.modificationMetaId = id; |
| 155 |
} |
| 156 |
|
| 157 |
/** |
| 158 |
* Set the parameter list of this statement. |
| 159 |
* |
| 160 |
* @param parameters the parameter list |
| 161 |
*/ |
| 162 |
public void setParameterList(ArrayList<Parameter> parameters) { |
| 163 |
this.parameters = parameters; |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* Get the parameter list. |
| 168 |
* |
| 169 |
* @return the parameter list |
| 170 |
*/ |
| 171 |
public ArrayList<Parameter> getParameters() { |
| 172 |
return parameters; |
| 173 |
} |
| 174 |
|
| 175 |
/** |
| 176 |
* Returns whether values of parameters were specified in SQL. |
| 177 |
* |
| 178 |
* @return are values of parameters were specified in SQL |
| 179 |
*/ |
| 180 |
public boolean isWithParamValues() { |
| 181 |
return withParamValues; |
| 182 |
} |
| 183 |
|
| 184 |
/** |
| 185 |
* Sets whether values of parameters were specified in SQL. |
| 186 |
* |
| 187 |
* @param withParamValues |
| 188 |
* are values of parameters were specified in SQL |
| 189 |
*/ |
| 190 |
public void setWithParamValues(boolean withParamValues) { |
| 191 |
this.withParamValues = withParamValues; |
| 192 |
} |
| 193 |
|
| 194 |
/** |
| 195 |
* Check if all parameters have been set. |
| 196 |
* |
| 197 |
* @throws DbException if any parameter has not been set |
| 198 |
*/ |
| 199 |
protected void checkParameters() { |
| 200 |
if (persistedObjectId < 0) { |
| 201 |
// restore original persistedObjectId on Command re-run |
| 202 |
// i.e. due to concurrent update |
| 203 |
persistedObjectId = ~persistedObjectId; |
| 204 |
} |
| 205 |
if (parameters != null) { |
| 206 |
for (Parameter param : parameters) { |
| 207 |
param.checkSet(); |
| 208 |
} |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
/** |
| 213 |
* Set the command. |
| 214 |
* |
| 215 |
* @param command the new command |
| 216 |
*/ |
| 217 |
public void setCommand(Command command) { |
| 218 |
this.command = command; |
| 219 |
} |
| 220 |
|
| 221 |
/** |
| 222 |
* Check if this object is a query. |
| 223 |
* |
| 224 |
* @return true if it is |
| 225 |
*/ |
| 226 |
public boolean isQuery() { |
| 227 |
return false; |
| 228 |
} |
| 229 |
|
| 230 |
/** |
| 231 |
* Prepare this statement. |
| 232 |
*/ |
| 233 |
public void prepare() { |
| 234 |
// nothing to do |
| 235 |
} |
| 236 |
|
| 237 |
/** |
| 238 |
* Execute the statement. |
| 239 |
* |
| 240 |
* @return the update count |
| 241 |
* @throws DbException if it is a query |
| 242 |
*/ |
| 243 |
public long update() { |
| 244 |
throw DbException.get(ErrorCode.METHOD_NOT_ALLOWED_FOR_QUERY); |
| 245 |
} |
| 246 |
|
| 247 |
/** |
| 248 |
* Execute the query. |
| 249 |
* |
| 250 |
* @param maxrows the maximum number of rows to return |
| 251 |
* @return the result set |
| 252 |
* @throws DbException if it is not a query |
| 253 |
*/ |
| 254 |
@SuppressWarnings("unused") |
| 255 |
public ResultInterface query(long maxrows) { |
| 256 |
throw DbException.get(ErrorCode.METHOD_ONLY_ALLOWED_FOR_QUERY); |
| 257 |
} |
| 258 |
|
| 259 |
/** |
| 260 |
* Set the SQL statement. |
| 261 |
* |
| 262 |
* @param sql the SQL statement |
| 263 |
* @param sqlTokens the SQL tokens |
| 264 |
*/ |
| 265 |
public final void setSQL(String sql, ArrayList<Token> sqlTokens) { |
| 266 |
this.sqlStatement = sql; |
| 267 |
this.sqlTokens = sqlTokens; |
| 268 |
} |
| 269 |
|
| 270 |
/** |
| 271 |
* Get the SQL statement. |
| 272 |
* |
| 273 |
* @return the SQL statement |
| 274 |
*/ |
| 275 |
public final String getSQL() { |
| 276 |
return sqlStatement; |
| 277 |
} |
| 278 |
|
| 279 |
/** |
| 280 |
* Get the SQL tokens. |
| 281 |
* |
| 282 |
* @return the SQL tokens |
| 283 |
*/ |
| 284 |
public final ArrayList<Token> getSQLTokens() { |
| 285 |
return sqlTokens; |
| 286 |
} |
| 287 |
|
| 288 |
/** |
| 289 |
* Get the object id to use for the database object that is created in this |
| 290 |
* statement. This id is only set when the object is already persisted. |
| 291 |
* If not set, this method returns 0. |
| 292 |
* |
| 293 |
* @return the object id or 0 if not set |
| 294 |
*/ |
| 295 |
public int getPersistedObjectId() { |
| 296 |
int id = persistedObjectId; |
| 297 |
return id >= 0 ? id : 0; |
| 298 |
} |
| 299 |
|
| 300 |
/** |
| 301 |
* Get the current object id, or get a new id from the database. The object |
| 302 |
* id is used when creating new database object (CREATE statement). This |
| 303 |
* method may be called only once. |
| 304 |
* |
| 305 |
* @return the object id |
| 306 |
*/ |
| 307 |
protected int getObjectId() { |
| 308 |
int id = persistedObjectId; |
| 309 |
if (id == 0) { |
| 310 |
id = getDatabase().allocateObjectId(); |
| 311 |
} else if (id < 0) { |
| 312 |
throw DbException.getInternalError("Prepared.getObjectId() was called before"); |
| 313 |
} |
| 314 |
persistedObjectId = ~persistedObjectId; // while negative, it can be restored later |
| 315 |
return id; |
| 316 |
} |
| 317 |
|
| 318 |
/** |
| 319 |
* Get the SQL statement with the execution plan. |
| 320 |
* |
| 321 |
* @param sqlFlags formatting flags |
| 322 |
* @return the execution plan |
| 323 |
*/ |
| 324 |
public String getPlanSQL(int sqlFlags) { |
| 325 |
return null; |
| 326 |
} |
| 327 |
|
| 328 |
/** |
| 329 |
* Check if this statement was canceled. |
| 330 |
* |
| 331 |
* @throws DbException if it was canceled |
| 332 |
*/ |
| 333 |
public void checkCanceled() { |
| 334 |
session.checkCanceled(); |
| 335 |
Command c = command != null ? command : session.getCurrentCommand(); |
| 336 |
if (c != null) { |
| 337 |
c.checkCanceled(); |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
/** |
| 342 |
* Set the persisted object id for this statement. |
| 343 |
* |
| 344 |
* @param i the object id |
| 345 |
*/ |
| 346 |
public void setPersistedObjectId(int i) { |
| 347 |
this.persistedObjectId = i; |
| 348 |
this.create = false; |
| 349 |
} |
| 350 |
|
| 351 |
/** |
| 352 |
* Set the session for this statement. |
| 353 |
* |
| 354 |
* @param currentSession the new session |
| 355 |
*/ |
| 356 |
public void setSession(SessionLocal currentSession) { |
| 357 |
this.session = currentSession; |
| 358 |
} |
| 359 |
|
| 360 |
/** |
| 361 |
* Print information about the statement executed if info trace level is |
| 362 |
* enabled. |
| 363 |
* @param database to update statistics |
| 364 |
* @param startTimeNanos when the statement was started |
| 365 |
* @param rowCount the query or update row count |
| 366 |
*/ |
| 367 |
void trace(Database database, long startTimeNanos, long rowCount) { |
| 368 |
if (session.getTrace().isInfoEnabled() && startTimeNanos > 0) { |
| 369 |
long deltaTimeNanos = System.nanoTime() - startTimeNanos; |
| 370 |
String params = Trace.formatParams(parameters); |
| 371 |
session.getTrace().infoSQL(sqlStatement, params, rowCount, deltaTimeNanos / 1_000_000L); |
| 372 |
} |
| 373 |
// startTime_nanos can be zero for the command that actually turns on |
| 374 |
// statistics |
| 375 |
if (database != null && database.getQueryStatistics() && startTimeNanos != 0) { |
| 376 |
long deltaTimeNanos = System.nanoTime() - startTimeNanos; |
| 377 |
database.getQueryStatisticsData().update(toString(), deltaTimeNanos, rowCount); |
| 378 |
} |
| 379 |
} |
| 380 |
|
| 381 |
/** |
| 382 |
* Set the prepare always flag. |
| 383 |
* If set, the statement is re-compiled whenever it is executed. |
| 384 |
* |
| 385 |
* @param prepareAlways the new value |
| 386 |
*/ |
| 387 |
public void setPrepareAlways(boolean prepareAlways) { |
| 388 |
this.prepareAlways = prepareAlways; |
| 389 |
} |
| 390 |
|
| 391 |
/** |
| 392 |
* Set the current row number. |
| 393 |
* |
| 394 |
* @param rowNumber the row number |
| 395 |
*/ |
| 396 |
public void setCurrentRowNumber(long rowNumber) { |
| 397 |
if ((++rowScanCount & 127) == 0) { |
| 398 |
checkCanceled(); |
| 399 |
} |
| 400 |
this.currentRowNumber = rowNumber; |
| 401 |
setProgress(); |
| 402 |
} |
| 403 |
|
| 404 |
/** |
| 405 |
* Get the current row number. |
| 406 |
* |
| 407 |
* @return the row number |
| 408 |
*/ |
| 409 |
public long getCurrentRowNumber() { |
| 410 |
return currentRowNumber; |
| 411 |
} |
| 412 |
|
| 413 |
/** |
| 414 |
* Notifies query progress via the DatabaseEventListener |
| 415 |
*/ |
| 416 |
private void setProgress() { |
| 417 |
if ((currentRowNumber & 127) == 0) { |
| 418 |
getDatabase().setProgress(DatabaseEventListener.STATE_STATEMENT_PROGRESS, sqlStatement, |
| 419 |
currentRowNumber, 0L); |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
/** |
| 424 |
* Convert the statement to a String. |
| 425 |
* |
| 426 |
* @return the SQL statement |
| 427 |
*/ |
| 428 |
@Override |
| 429 |
public String toString() { |
| 430 |
return sqlStatement; |
| 431 |
} |
| 432 |
|
| 433 |
/** |
| 434 |
* Get the SQL snippet of the expression list. |
| 435 |
* |
| 436 |
* @param list the expression list |
| 437 |
* @return the SQL snippet |
| 438 |
*/ |
| 439 |
public static String getSimpleSQL(Expression[] list) { |
| 440 |
return Expression.writeExpressions(new StringBuilder(), list, HasSQL.TRACE_SQL_FLAGS).toString(); |
| 441 |
} |
| 442 |
|
| 443 |
/** |
| 444 |
* Set the SQL statement of the exception to the given row. |
| 445 |
* |
| 446 |
* @param e the exception |
| 447 |
* @param rowId the row number |
| 448 |
* @param values the values of the row |
| 449 |
* @return the exception |
| 450 |
*/ |
| 451 |
protected final DbException setRow(DbException e, long rowId, String values) { |
| 452 |
StringBuilder buff = new StringBuilder(); |
| 453 |
if (sqlStatement != null) { |
| 454 |
buff.append(sqlStatement); |
| 455 |
} |
| 456 |
buff.append(" -- "); |
| 457 |
if (rowId > 0) { |
| 458 |
buff.append("row #").append(rowId + 1).append(' '); |
| 459 |
} |
| 460 |
buff.append('(').append(values).append(')'); |
| 461 |
return e.addSQL(buff.toString()); |
| 462 |
} |
| 463 |
|
| 464 |
public boolean isCacheable() { |
| 465 |
return false; |
| 466 |
} |
| 467 |
|
| 468 |
/** |
| 469 |
* @return the temporary views created for CTE's. |
| 470 |
*/ |
| 471 |
public List<TableView> getCteCleanups() { |
| 472 |
return cteCleanups; |
| 473 |
} |
| 474 |
|
| 475 |
/** |
| 476 |
* Set the temporary views created for CTE's. |
| 477 |
* |
| 478 |
* @param cteCleanups the temporary views |
| 479 |
*/ |
| 480 |
public void setCteCleanups(List<TableView> cteCleanups) { |
| 481 |
this.cteCleanups = cteCleanups; |
| 482 |
} |
| 483 |
|
| 484 |
public final SessionLocal getSession() { |
| 485 |
return session; |
| 486 |
} |
| 487 |
|
| 488 |
/** |
| 489 |
* Find and collect all DbObjects, this Prepared depends on. |
| 490 |
* |
| 491 |
* @param dependencies collection of dependencies to populate |
| 492 |
*/ |
| 493 |
public void collectDependencies(HashSet<DbObject> dependencies) {} |
| 494 |
|
| 495 |
protected final Database getDatabase() { |
| 496 |
return session.getDatabase(); |
| 497 |
} |
| 498 |
|
| 499 |
/** |
| 500 |
* Returns is this command can be repeated again on locking failure. |
| 501 |
* |
| 502 |
* @return is this command can be repeated again on locking failure |
| 503 |
*/ |
| 504 |
public boolean isRetryable() { |
| 505 |
return true; |
| 506 |
} |
| 507 |
|
| 508 |
} |