Debian Codegraph @

src/main/org/h2/jdbc/JdbcStatement.java

raw
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.jdbc;
7
8 import java.sql.Connection;
9 import java.sql.ResultSet;
10 import java.sql.SQLException;
11 import java.sql.SQLWarning;
12 import java.sql.Statement;
13 import java.util.ArrayList;
14 import org.h2.api.ErrorCode;
15 import org.h2.command.CommandInterface;
16 import org.h2.engine.Session;
17 import org.h2.engine.SysProperties;
18 import org.h2.message.DbException;
19 import org.h2.message.TraceObject;
20 import org.h2.result.ResultInterface;
21 import org.h2.result.ResultWithGeneratedKeys;
22 import org.h2.result.SimpleResult;
23 import org.h2.util.ParserUtil;
24 import org.h2.util.StringUtils;
25 import org.h2.util.Utils;
26
27 /**
28 * Represents a statement.
29 * <p>
30 * Thread safety: the statement is not thread-safe. If the same statement is
31 * used by multiple threads access to it must be synchronized. The single
32 * synchronized block must include execution of the command and all operations
33 * with its result.
34 * </p>
35 * <pre>
36 * synchronized (stat) {
37 * try (ResultSet rs = stat.executeQuery(queryString)) {
38 * while (rs.next) {
39 * // Do something
40 * }
41 * }
42 * }
43 * synchronized (stat) {
44 * updateCount = stat.executeUpdate(commandString);
45 * }
46 * </pre>
47 */
48 public class JdbcStatement extends TraceObject implements Statement, JdbcStatementBackwardsCompat {
49
50 protected JdbcConnection conn;
51 protected Session session;
52 protected JdbcResultSet resultSet;
53 protected long maxRows;
54 protected int fetchSize = SysProperties.SERVER_RESULT_SET_FETCH_SIZE;
55 protected long updateCount;
56 protected JdbcResultSet generatedKeys;
57 protected final int resultSetType;
58 protected final int resultSetConcurrency;
59 private volatile CommandInterface executingCommand;
60 private ArrayList<String> batchCommands;
61 private boolean escapeProcessing = true;
62 private volatile boolean cancelled;
63 private boolean closeOnCompletion;
64
65 JdbcStatement(JdbcConnection conn, int id, int resultSetType, int resultSetConcurrency) {
66 this.conn = conn;
67 this.session = conn.getSession();
68 setTrace(session.getTrace(), TraceObject.STATEMENT, id);
69 this.resultSetType = resultSetType;
70 this.resultSetConcurrency = resultSetConcurrency;
71 }
72
73 /**
74 * Executes a query (select statement) and returns the result set.
75 * If another result set exists for this statement, this will be closed
76 * (even if this statement fails).
77 *
78 * @param sql the SQL statement to execute
79 * @return the result set
80 */
81 @Override
82 public ResultSet executeQuery(String sql) throws SQLException {
83 try {
84 int id = getNextId(TraceObject.RESULT_SET);
85 if (isDebugEnabled()) {
86 debugCodeAssign("ResultSet", TraceObject.RESULT_SET, id, "executeQuery(" + quote(sql) + ')');
87 }
88 synchronized (session) {
89 checkClosed();
90 closeOldResultSet();
91 sql = JdbcConnection.translateSQL(sql, escapeProcessing);
92 CommandInterface command = conn.prepareCommand(sql, fetchSize);
93 ResultInterface result;
94 boolean lazy = false;
95 boolean scrollable = resultSetType != ResultSet.TYPE_FORWARD_ONLY;
96 boolean updatable = resultSetConcurrency == ResultSet.CONCUR_UPDATABLE;
97 setExecutingStatement(command);
98 try {
99 result = command.executeQuery(maxRows, scrollable);
100 lazy = result.isLazy();
101 } finally {
102 if (!lazy) {
103 setExecutingStatement(null);
104 }
105 }
106 if (!lazy) {
107 command.close();
108 }
109 resultSet = new JdbcResultSet(conn, this, command, result, id, scrollable, updatable, false);
110 }
111 return resultSet;
112 } catch (Exception e) {
113 throw logAndConvert(e);
114 }
115 }
116
117 /**
118 * Executes a statement (insert, update, delete, create, drop)
119 * and returns the update count. This method is not
120 * allowed for prepared statements.
121 * If another result set exists for this statement, this will be closed
122 * (even if this statement fails).
123 *
124 * If auto commit is on, this statement will be committed.
125 * If the statement is a DDL statement (create, drop, alter) and does not
126 * throw an exception, the current transaction (if any) is committed after
127 * executing the statement.
128 *
129 * @param sql the SQL statement
130 * @return the update count (number of affected rows by a DML statement or
131 * other statement able to return number of rows, or 0 if no rows
132 * were affected or the statement returned nothing, or
133 * {@link #SUCCESS_NO_INFO} if number of rows is too large for the
134 * {@code int} data type)
135 * @throws SQLException if a database error occurred or a
136 * select statement was executed
137 * @see #executeLargeUpdate(String)
138 */
139 @Override
140 public final int executeUpdate(String sql) throws SQLException {
141 try {
142 debugCodeCall("executeUpdate", sql);
143 long updateCount = executeUpdateInternal(sql, null);
144 return updateCount <= Integer.MAX_VALUE ? (int) updateCount : SUCCESS_NO_INFO;
145 } catch (Exception e) {
146 throw logAndConvert(e);
147 }
148 }
149
150 /**
151 * Executes a statement (insert, update, delete, create, drop)
152 * and returns the update count. This method is not
153 * allowed for prepared statements.
154 * If another result set exists for this statement, this will be closed
155 * (even if this statement fails).
156 *
157 * If auto commit is on, this statement will be committed.
158 * If the statement is a DDL statement (create, drop, alter) and does not
159 * throw an exception, the current transaction (if any) is committed after
160 * executing the statement.
161 *
162 * @param sql the SQL statement
163 * @return the update count (number of affected rows by a DML statement or
164 * other statement able to return number of rows, or 0 if no rows
165 * were affected or the statement returned nothing)
166 * @throws SQLException if a database error occurred or a
167 * select statement was executed
168 */
169 @Override
170 public final long executeLargeUpdate(String sql) throws SQLException {
171 try {
172 debugCodeCall("executeLargeUpdate", sql);
173 return executeUpdateInternal(sql, null);
174 } catch (Exception e) {
175 throw logAndConvert(e);
176 }
177 }
178
179 private long executeUpdateInternal(String sql, Object generatedKeysRequest) {
180 if (getClass() != JdbcStatement.class) {
181 throw DbException.get(ErrorCode.METHOD_NOT_ALLOWED_FOR_PREPARED_STATEMENT);
182 }
183 checkClosed();
184 closeOldResultSet();
185 sql = JdbcConnection.translateSQL(sql, escapeProcessing);
186 CommandInterface command = conn.prepareCommand(sql, fetchSize);
187 synchronized (session) {
188 setExecutingStatement(command);
189 try {
190 ResultWithGeneratedKeys result = command.executeUpdate(generatedKeysRequest);
191 updateCount = result.getUpdateCount();
192 ResultInterface gk = result.getGeneratedKeys();
193 if (gk != null) {
194 int id = getNextId(TraceObject.RESULT_SET);
195 generatedKeys = new JdbcResultSet(conn, this, command, gk, id, true, false, false);
196 }
197 } finally {
198 setExecutingStatement(null);
199 }
200 }
201 command.close();
202 return updateCount;
203 }
204
205 /**
206 * Executes a statement and returns type of its result. This method is not
207 * allowed for prepared statements.
208 * If another result set exists for this
209 * statement, this will be closed (even if this statement fails).
210 *
211 * If the statement is a create or drop and does not throw an exception, the
212 * current transaction (if any) is committed after executing the statement.
213 * If auto commit is on, and the statement is not a select, this statement
214 * will be committed.
215 *
216 * @param sql the SQL statement to execute
217 * @return true if result is a result set, false otherwise
218 */
219 @Override
220 public final boolean execute(String sql) throws SQLException {
221 try {
222 debugCodeCall("execute", sql);
223 return executeInternal(sql, false);
224 } catch (Exception e) {
225 throw logAndConvert(e);
226 }
227 }
228
229 private boolean executeInternal(String sql, Object generatedKeysRequest) {
230 if (getClass() != JdbcStatement.class) {
231 throw DbException.get(ErrorCode.METHOD_NOT_ALLOWED_FOR_PREPARED_STATEMENT);
232 }
233 int id = getNextId(TraceObject.RESULT_SET);
234 checkClosed();
235 closeOldResultSet();
236 sql = JdbcConnection.translateSQL(sql, escapeProcessing);
237 CommandInterface command = conn.prepareCommand(sql, fetchSize);
238 boolean lazy = false;
239 boolean returnsResultSet;
240 synchronized (session) {
241 setExecutingStatement(command);
242 try {
243 if (command.isQuery()) {
244 returnsResultSet = true;
245 boolean scrollable = resultSetType != ResultSet.TYPE_FORWARD_ONLY;
246 boolean updatable = resultSetConcurrency == ResultSet.CONCUR_UPDATABLE;
247 ResultInterface result = command.executeQuery(maxRows, scrollable);
248 lazy = result.isLazy();
249 resultSet = new JdbcResultSet(conn, this, command, result, id, scrollable, updatable, false);
250 } else {
251 returnsResultSet = false;
252 ResultWithGeneratedKeys result = command.executeUpdate(generatedKeysRequest);
253 updateCount = result.getUpdateCount();
254 ResultInterface gk = result.getGeneratedKeys();
255 if (gk != null) {
256 generatedKeys = new JdbcResultSet(conn, this, command, gk, id, true, false, false);
257 }
258 }
259 } finally {
260 if (!lazy) {
261 setExecutingStatement(null);
262 }
263 }
264 }
265 if (!lazy) {
266 command.close();
267 }
268 return returnsResultSet;
269 }
270
271 /**
272 * Returns the last result set produces by this statement.
273 *
274 * @return the result set
275 */
276 @Override
277 public ResultSet getResultSet() throws SQLException {
278 try {
279 checkClosed();
280 if (resultSet != null) {
281 int id = resultSet.getTraceId();
282 debugCodeAssign("ResultSet", TraceObject.RESULT_SET, id, "getResultSet()");
283 } else {
284 debugCodeCall("getResultSet");
285 }
286 return resultSet;
287 } catch (Exception e) {
288 throw logAndConvert(e);
289 }
290 }
291
292 /**
293 * Returns the last update count of this statement.
294 *
295 * @return the update count (number of affected rows by a DML statement or
296 * other statement able to return number of rows, or 0 if no rows
297 * were affected or the statement returned nothing, or -1 if
298 * statement was a query, or {@link #SUCCESS_NO_INFO} if number of
299 * rows is too large for the {@code int} data type)
300 * @throws SQLException if this object is closed or invalid
301 * @see #getLargeUpdateCount()
302 */
303 @Override
304 public final int getUpdateCount() throws SQLException {
305 try {
306 debugCodeCall("getUpdateCount");
307 checkClosed();
308 return updateCount <= Integer.MAX_VALUE ? (int) updateCount : SUCCESS_NO_INFO;
309 } catch (Exception e) {
310 throw logAndConvert(e);
311 }
312 }
313
314 /**
315 * Returns the last update count of this statement.
316 *
317 * @return the update count (number of affected rows by a DML statement or
318 * other statement able to return number of rows, or 0 if no rows
319 * were affected or the statement returned nothing, or -1 if
320 * statement was a query)
321 * @throws SQLException if this object is closed or invalid
322 */
323 @Override
324 public final long getLargeUpdateCount() throws SQLException {
325 try {
326 debugCodeCall("getLargeUpdateCount");
327 checkClosed();
328 return updateCount;
329 } catch (Exception e) {
330 throw logAndConvert(e);
331 }
332 }
333
334 /**
335 * Closes this statement.
336 * All result sets that where created by this statement
337 * become invalid after calling this method.
338 */
339 @Override
340 public void close() throws SQLException {
341 try {
342 debugCodeCall("close");
343 closeInternal();
344 } catch (Exception e) {
345 throw logAndConvert(e);
346 }
347 }
348
349 private void closeInternal() {
350 synchronized (session) {
351 closeOldResultSet();
352 if (conn != null) {
353 conn = null;
354 }
355 }
356 }
357
358 /**
359 * Returns the connection that created this object.
360 *
361 * @return the connection
362 */
363 @Override
364 public Connection getConnection() {
365 debugCodeCall("getConnection");
366 return conn;
367 }
368
369 /**
370 * Gets the first warning reported by calls on this object.
371 * This driver does not support warnings, and will always return null.
372 *
373 * @return null
374 */
375 @Override
376 public SQLWarning getWarnings() throws SQLException {
377 try {
378 debugCodeCall("getWarnings");
379 checkClosed();
380 return null;
381 } catch (Exception e) {
382 throw logAndConvert(e);
383 }
384 }
385
386 /**
387 * Clears all warnings. As this driver does not support warnings,
388 * this call is ignored.
389 */
390 @Override
391 public void clearWarnings() throws SQLException {
392 try {
393 debugCodeCall("clearWarnings");
394 checkClosed();
395 } catch (Exception e) {
396 throw logAndConvert(e);
397 }
398 }
399
400 /**
401 * Sets the name of the cursor. This call is ignored.
402 *
403 * @param name ignored
404 * @throws SQLException if this object is closed
405 */
406 @Override
407 public void setCursorName(String name) throws SQLException {
408 try {
409 debugCodeCall("setCursorName", name);
410 checkClosed();
411 } catch (Exception e) {
412 throw logAndConvert(e);
413 }
414 }
415
416 /**
417 * Sets the fetch direction.
418 * This call is ignored by this driver.
419 *
420 * @param direction ignored
421 * @throws SQLException if this object is closed
422 */
423 @Override
424 public void setFetchDirection(int direction) throws SQLException {
425 try {
426 debugCodeCall("setFetchDirection", direction);
427 checkClosed();
428 } catch (Exception e) {
429 throw logAndConvert(e);
430 }
431 }
432
433 /**
434 * Gets the fetch direction.
435 *
436 * @return FETCH_FORWARD
437 * @throws SQLException if this object is closed
438 */
439 @Override
440 public int getFetchDirection() throws SQLException {
441 try {
442 debugCodeCall("getFetchDirection");
443 checkClosed();
444 return ResultSet.FETCH_FORWARD;
445 } catch (Exception e) {
446 throw logAndConvert(e);
447 }
448 }
449
450 /**
451 * Gets the maximum number of rows for a ResultSet.
452 *
453 * @return the number of rows where 0 means no limit
454 * @throws SQLException if this object is closed
455 */
456 @Override
457 public int getMaxRows() throws SQLException {
458 try {
459 debugCodeCall("getMaxRows");
460 checkClosed();
461 return maxRows <= Integer.MAX_VALUE ? (int) maxRows : 0;
462 } catch (Exception e) {
463 throw logAndConvert(e);
464 }
465 }
466
467 /**
468 * Gets the maximum number of rows for a ResultSet.
469 *
470 * @return the number of rows where 0 means no limit
471 * @throws SQLException if this object is closed
472 */
473 @Override
474 public long getLargeMaxRows() throws SQLException {
475 try {
476 debugCodeCall("getLargeMaxRows");
477 checkClosed();
478 return maxRows;
479 } catch (Exception e) {
480 throw logAndConvert(e);
481 }
482 }
483
484 /**
485 * Gets the maximum number of rows for a ResultSet.
486 *
487 * @param maxRows the number of rows where 0 means no limit
488 * @throws SQLException if this object is closed
489 */
490 @Override
491 public void setMaxRows(int maxRows) throws SQLException {
492 try {
493 debugCodeCall("setMaxRows", maxRows);
494 checkClosed();
495 if (maxRows < 0) {
496 throw DbException.getInvalidValueException("maxRows", maxRows);
497 }
498 this.maxRows = maxRows;
499 } catch (Exception e) {
500 throw logAndConvert(e);
501 }
502 }
503
504 /**
505 * Gets the maximum number of rows for a ResultSet.
506 *
507 * @param maxRows the number of rows where 0 means no limit
508 * @throws SQLException if this object is closed
509 */
510 @Override
511 public void setLargeMaxRows(long maxRows) throws SQLException {
512 try {
513 debugCodeCall("setLargeMaxRows", maxRows);
514 checkClosed();
515 if (maxRows < 0) {
516 throw DbException.getInvalidValueException("maxRows", maxRows);
517 }
518 this.maxRows = maxRows;
519 } catch (Exception e) {
520 throw logAndConvert(e);
521 }
522 }
523
524 /**
525 * Sets the number of rows suggested to read in one step.
526 * This value cannot be higher than the maximum rows (setMaxRows)
527 * set by the statement or prepared statement, otherwise an exception
528 * is throws. Setting the value to 0 will set the default value.
529 * The default value can be changed using the system property
530 * h2.serverResultSetFetchSize.
531 *
532 * @param rows the number of rows
533 * @throws SQLException if this object is closed
534 */
535 @Override
536 public void setFetchSize(int rows) throws SQLException {
537 try {
538 debugCodeCall("setFetchSize", rows);
539 checkClosed();
540 if (rows < 0 || (rows > 0 && maxRows > 0 && rows > maxRows)) {
541 throw DbException.getInvalidValueException("rows", rows);
542 }
543 if (rows == 0) {
544 rows = SysProperties.SERVER_RESULT_SET_FETCH_SIZE;
545 }
546 fetchSize = rows;
547 } catch (Exception e) {
548 throw logAndConvert(e);
549 }
550 }
551
552 /**
553 * Gets the number of rows suggested to read in one step.
554 *
555 * @return the current fetch size
556 * @throws SQLException if this object is closed
557 */
558 @Override
559 public int getFetchSize() throws SQLException {
560 try {
561 debugCodeCall("getFetchSize");
562 checkClosed();
563 return fetchSize;
564 } catch (Exception e) {
565 throw logAndConvert(e);
566 }
567 }
568
569 /**
570 * Gets the result set concurrency created by this object.
571 *
572 * @return the concurrency
573 */
574 @Override
575 public int getResultSetConcurrency() throws SQLException {
576 try {
577 debugCodeCall("getResultSetConcurrency");
578 checkClosed();
579 return resultSetConcurrency;
580 } catch (Exception e) {
581 throw logAndConvert(e);
582 }
583 }
584
585 /**
586 * Gets the result set type.
587 *
588 * @return the type
589 * @throws SQLException if this object is closed
590 */
591 @Override
592 public int getResultSetType() throws SQLException {
593 try {
594 debugCodeCall("getResultSetType");
595 checkClosed();
596 return resultSetType;
597 } catch (Exception e) {
598 throw logAndConvert(e);
599 }
600 }
601
602 /**
603 * Gets the maximum number of bytes for a result set column.
604 *
605 * @return always 0 for no limit
606 * @throws SQLException if this object is closed
607 */
608 @Override
609 public int getMaxFieldSize() throws SQLException {
610 try {
611 debugCodeCall("getMaxFieldSize");
612 checkClosed();
613 return 0;
614 } catch (Exception e) {
615 throw logAndConvert(e);
616 }
617 }
618
619 /**
620 * Sets the maximum number of bytes for a result set column.
621 * This method does currently do nothing for this driver.
622 *
623 * @param max the maximum size - ignored
624 * @throws SQLException if this object is closed
625 */
626 @Override
627 public void setMaxFieldSize(int max) throws SQLException {
628 try {
629 debugCodeCall("setMaxFieldSize", max);
630 checkClosed();
631 } catch (Exception e) {
632 throw logAndConvert(e);
633 }
634 }
635
636 /**
637 * Enables or disables processing or JDBC escape syntax.
638 * See also Connection.nativeSQL.
639 *
640 * @param enable - true (default) or false (no conversion is attempted)
641 * @throws SQLException if this object is closed
642 */
643 @Override
644 public void setEscapeProcessing(boolean enable) throws SQLException {
645 try {
646 if (isDebugEnabled()) {
647 debugCode("setEscapeProcessing(" + enable + ')');
648 }
649 checkClosed();
650 escapeProcessing = enable;
651 } catch (Exception e) {
652 throw logAndConvert(e);
653 }
654 }
655
656 /**
657 * Cancels a currently running statement.
658 * This method must be called from within another
659 * thread than the execute method.
660 * Operations on large objects are not interrupted,
661 * only operations that process many rows.
662 *
663 * @throws SQLException if this object is closed
664 */
665 @Override
666 public void cancel() throws SQLException {
667 try {
668 debugCodeCall("cancel");
669 checkClosed();
670 // executingCommand can be reset by another thread
671 CommandInterface c = executingCommand;
672 try {
673 if (c != null) {
674 c.cancel();
675 cancelled = true;
676 }
677 } finally {
678 setExecutingStatement(null);
679 }
680 } catch (Exception e) {
681 throw logAndConvert(e);
682 }
683 }
684
685 /**
686 * Check whether the statement was cancelled.
687 *
688 * @return true if yes
689 */
690 public boolean isCancelled() {
691 return cancelled;
692 }
693
694 /**
695 * Gets the current query timeout in seconds.
696 * This method will return 0 if no query timeout is set.
697 * The result is rounded to the next second.
698 * For performance reasons, only the first call to this method
699 * will query the database. If the query timeout was changed in another
700 * way than calling setQueryTimeout, this method will always return
701 * the last value.
702 *
703 * @return the timeout in seconds
704 * @throws SQLException if this object is closed
705 */
706 @Override
707 public int getQueryTimeout() throws SQLException {
708 try {
709 debugCodeCall("getQueryTimeout");
710 checkClosed();
711 return conn.getQueryTimeout();
712 } catch (Exception e) {
713 throw logAndConvert(e);
714 }
715 }
716
717 /**
718 * Sets the current query timeout in seconds.
719 * Changing the value will affect all statements of this connection.
720 * This method does not commit a transaction,
721 * and rolling back a transaction does not affect this setting.
722 *
723 * @param seconds the timeout in seconds - 0 means no timeout, values
724 * smaller 0 will throw an exception
725 * @throws SQLException if this object is closed
726 */
727 @Override
728 public void setQueryTimeout(int seconds) throws SQLException {
729 try {
730 debugCodeCall("setQueryTimeout", seconds);
731 checkClosed();
732 if (seconds < 0) {
733 throw DbException.getInvalidValueException("seconds", seconds);
734 }
735 conn.setQueryTimeout(seconds);
736 } catch (Exception e) {
737 throw logAndConvert(e);
738 }
739 }
740
741 /**
742 * Adds a statement to the batch.
743 *
744 * @param sql the SQL statement
745 */
746 @Override
747 public void addBatch(String sql) throws SQLException {
748 try {
749 debugCodeCall("addBatch", sql);
750 checkClosed();
751 sql = JdbcConnection.translateSQL(sql, escapeProcessing);
752 if (batchCommands == null) {
753 batchCommands = Utils.newSmallArrayList();
754 }
755 batchCommands.add(sql);
756 } catch (Exception e) {
757 throw logAndConvert(e);
758 }
759 }
760
761 /**
762 * Clears the batch.
763 */
764 @Override
765 public void clearBatch() throws SQLException {
766 try {
767 debugCodeCall("clearBatch");
768 checkClosed();
769 batchCommands = null;
770 } catch (Exception e) {
771 throw logAndConvert(e);
772 }
773 }
774
775 /**
776 * Executes the batch.
777 * If one of the batched statements fails, this database will continue.
778 *
779 * @return the array of update counts
780 * @see #executeLargeBatch()
781 */
782 @Override
783 public int[] executeBatch() throws SQLException {
784 try {
785 debugCodeCall("executeBatch");
786 checkClosed();
787 if (batchCommands == null) {
788 batchCommands = new ArrayList<>();
789 }
790 int size = batchCommands.size();
791 int[] result = new int[size];
792 SQLException exception = new SQLException();
793 for (int i = 0; i < size; i++) {
794 long updateCount = executeBatchElement(batchCommands.get(i), exception);
795 result[i] = updateCount <= Integer.MAX_VALUE ? (int) updateCount : SUCCESS_NO_INFO;
796 }
797 batchCommands = null;
798 exception = exception.getNextException();
799 if (exception != null) {
800 throw new JdbcBatchUpdateException(exception, result);
801 }
802 return result;
803 } catch (Exception e) {
804 throw logAndConvert(e);
805 }
806 }
807
808 /**
809 * Executes the batch.
810 * If one of the batched statements fails, this database will continue.
811 *
812 * @return the array of update counts
813 */
814 @Override
815 public long[] executeLargeBatch() throws SQLException {
816 try {
817 debugCodeCall("executeLargeBatch");
818 checkClosed();
819 if (batchCommands == null) {
820 batchCommands = new ArrayList<>();
821 }
822 int size = batchCommands.size();
823 long[] result = new long[size];
824 SQLException exception = new SQLException();
825 for (int i = 0; i < size; i++) {
826 result[i] = executeBatchElement(batchCommands.get(i), exception);
827 }
828 batchCommands = null;
829 exception = exception.getNextException();
830 if (exception != null) {
831 throw new JdbcBatchUpdateException(exception, result);
832 }
833 return result;
834 } catch (Exception e) {
835 throw logAndConvert(e);
836 }
837 }
838
839 private long executeBatchElement(String sql, SQLException exception) {
840 long updateCount;
841 try {
842 updateCount = executeUpdateInternal(sql, null);
843 } catch (Exception e) {
844 exception.setNextException(logAndConvert(e));
845 updateCount = Statement.EXECUTE_FAILED;
846 }
847 return updateCount;
848 }
849
850 /**
851 * Return a result set with generated keys from the latest executed command
852 * or an empty result set if keys were not generated or were not requested
853 * with {@link Statement#RETURN_GENERATED_KEYS}, column indexes, or column
854 * names.
855 * <p>
856 * Generated keys are only returned from from {@code INSERT},
857 * {@code UPDATE}, {@code MERGE INTO}, and {@code MERGE INTO ... USING}
858 * commands.
859 * </p>
860 * <p>
861 * If SQL command inserts or updates multiple rows with generated keys each
862 * such inserted or updated row is returned. Batch methods are also
863 * supported.
864 * </p>
865 * <p>
866 * When {@link Statement#RETURN_GENERATED_KEYS} is used H2 chooses columns
867 * to return automatically. The following columns are chosen:
868 * </p>
869 * <ul>
870 * <li>Columns with sequences including {@code IDENTITY} columns and columns
871 * with {@code AUTO_INCREMENT}.</li>
872 * <li>Columns with other default values that are not evaluated into
873 * constant expressions (like {@code DEFAULT RANDOM_UUID()}).</li>
874 * <li>Columns that are included into the PRIMARY KEY constraint.</li>
875 * </ul>
876 * <p>
877 * Exact required columns for the returning result set may be specified on
878 * execution of command with names or indexes of columns.
879 * </p>
880 *
881 * @return the possibly empty result set with generated keys
882 * @throws SQLException if this object is closed
883 */
884 @Override
885 public ResultSet getGeneratedKeys() throws SQLException {
886 try {
887 int id = generatedKeys != null ? generatedKeys.getTraceId() : getNextId(TraceObject.RESULT_SET);
888 if (isDebugEnabled()) {
889 debugCodeAssign("ResultSet", TraceObject.RESULT_SET, id, "getGeneratedKeys()");
890 }
891 checkClosed();
892 if (generatedKeys == null) {
893 generatedKeys = new JdbcResultSet(conn, this, null, new SimpleResult(), id, true, false, false);
894 }
895 return generatedKeys;
896 } catch (Exception e) {
897 throw logAndConvert(e);
898 }
899 }
900
901 /**
902 * Moves to the next result set - however there is always only one result
903 * set. This call also closes the current result set (if there is one).
904 * Returns true if there is a next result set (that means - it always
905 * returns false).
906 *
907 * @return false
908 * @throws SQLException if this object is closed.
909 */
910 @Override
911 public boolean getMoreResults() throws SQLException {
912 try {
913 debugCodeCall("getMoreResults");
914 checkClosed();
915 closeOldResultSet();
916 return false;
917 } catch (Exception e) {
918 throw logAndConvert(e);
919 }
920 }
921
922 /**
923 * Move to the next result set.
924 * This method always returns false.
925 *
926 * @param current Statement.CLOSE_CURRENT_RESULT,
927 * Statement.KEEP_CURRENT_RESULT,
928 * or Statement.CLOSE_ALL_RESULTS
929 * @return false
930 */
931 @Override
932 public boolean getMoreResults(int current) throws SQLException {
933 try {
934 debugCodeCall("getMoreResults", current);
935 switch (current) {
936 case Statement.CLOSE_CURRENT_RESULT:
937 case Statement.CLOSE_ALL_RESULTS:
938 checkClosed();
939 closeOldResultSet();
940 break;
941 case Statement.KEEP_CURRENT_RESULT:
942 // nothing to do
943 break;
944 default:
945 throw DbException.getInvalidValueException("current", current);
946 }
947 return false;
948 } catch (Exception e) {
949 throw logAndConvert(e);
950 }
951 }
952
953 /**
954 * Executes a statement and returns the update count. This method is not
955 * allowed for prepared statements.
956 *
957 * @param sql the SQL statement
958 * @param autoGeneratedKeys
959 * {@link Statement#RETURN_GENERATED_KEYS} if generated keys should
960 * be available for retrieval, {@link Statement#NO_GENERATED_KEYS} if
961 * generated keys should not be available
962 * @return the update count (number of affected rows by a DML statement or
963 * other statement able to return number of rows, or 0 if no rows
964 * were affected or the statement returned nothing, or
965 * {@link #SUCCESS_NO_INFO} if number of rows is too large for the
966 * {@code int} data type)
967 * @throws SQLException if a database error occurred or a
968 * select statement was executed
969 * @see #executeLargeUpdate(String, int)
970 */
971 @Override
972 public final int executeUpdate(String sql, int autoGeneratedKeys)
973 throws SQLException {
974 try {
975 if (isDebugEnabled()) {
976 debugCode("executeUpdate(" + quote(sql) + ", " + autoGeneratedKeys + ')');
977 }
978 long updateCount = executeUpdateInternal(sql, autoGeneratedKeys == RETURN_GENERATED_KEYS);
979 return updateCount <= Integer.MAX_VALUE ? (int) updateCount : SUCCESS_NO_INFO;
980 } catch (Exception e) {
981 throw logAndConvert(e);
982 }
983 }
984
985 /**
986 * Executes a statement and returns the update count. This method is not
987 * allowed for prepared statements.
988 *
989 * @param sql the SQL statement
990 * @param autoGeneratedKeys
991 * {@link Statement#RETURN_GENERATED_KEYS} if generated keys should
992 * be available for retrieval, {@link Statement#NO_GENERATED_KEYS} if
993 * generated keys should not be available
994 * @return the update count (number of affected rows by a DML statement or
995 * other statement able to return number of rows, or 0 if no rows
996 * were affected or the statement returned nothing)
997 * @throws SQLException if a database error occurred or a
998 * select statement was executed
999 */
1000 @Override
1001 public final long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
1002 try {
1003 if (isDebugEnabled()) {
1004 debugCode("executeLargeUpdate(" + quote(sql) + ", " + autoGeneratedKeys + ')');
1005 }
1006 return executeUpdateInternal(sql, autoGeneratedKeys == RETURN_GENERATED_KEYS);
1007 } catch (Exception e) {
1008 throw logAndConvert(e);
1009 }
1010 }
1011
1012 /**
1013 * Executes a statement and returns the update count. This method is not
1014 * allowed for prepared statements.
1015 *
1016 * @param sql the SQL statement
1017 * @param columnIndexes
1018 * an array of column indexes indicating the columns with generated
1019 * keys that should be returned from the inserted row
1020 * @return the update count (number of affected rows by a DML statement or
1021 * other statement able to return number of rows, or 0 if no rows
1022 * were affected or the statement returned nothing, or
1023 * {@link #SUCCESS_NO_INFO} if number of rows is too large for the
1024 * {@code int} data type)
1025 * @throws SQLException if a database error occurred or a
1026 * select statement was executed
1027 * @see #executeLargeUpdate(String, int[])
1028 */
1029 @Override
1030 public final int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
1031 try {
1032 if (isDebugEnabled()) {
1033 debugCode("executeUpdate(" + quote(sql) + ", " + quoteIntArray(columnIndexes) + ')');
1034 }
1035 long updateCount = executeUpdateInternal(sql, columnIndexes);
1036 return updateCount <= Integer.MAX_VALUE ? (int) updateCount : SUCCESS_NO_INFO;
1037 } catch (Exception e) {
1038 throw logAndConvert(e);
1039 }
1040 }
1041
1042 /**
1043 * Executes a statement and returns the update count. This method is not
1044 * allowed for prepared statements.
1045 *
1046 * @param sql the SQL statement
1047 * @param columnIndexes
1048 * an array of column indexes indicating the columns with generated
1049 * keys that should be returned from the inserted row
1050 * @return the update count (number of affected rows by a DML statement or
1051 * other statement able to return number of rows, or 0 if no rows
1052 * were affected or the statement returned nothing)
1053 * @throws SQLException if a database error occurred or a
1054 * select statement was executed
1055 */
1056 @Override
1057 public final long executeLargeUpdate(String sql, int columnIndexes[]) throws SQLException {
1058 try {
1059 if (isDebugEnabled()) {
1060 debugCode("executeLargeUpdate(" + quote(sql) + ", " + quoteIntArray(columnIndexes) + ')');
1061 }
1062 return executeUpdateInternal(sql, columnIndexes);
1063 } catch (Exception e) {
1064 throw logAndConvert(e);
1065 }
1066 }
1067
1068 /**
1069 * Executes a statement and returns the update count. This method is not
1070 * allowed for prepared statements.
1071 *
1072 * @param sql the SQL statement
1073 * @param columnNames
1074 * an array of column names indicating the columns with generated
1075 * keys that should be returned from the inserted row
1076 * @return the update count (number of affected rows by a DML statement or
1077 * other statement able to return number of rows, or 0 if no rows
1078 * were affected or the statement returned nothing, or
1079 * {@link #SUCCESS_NO_INFO} if number of rows is too large for the
1080 * {@code int} data type)
1081 * @throws SQLException if a database error occurred or a
1082 * select statement was executed
1083 * @see #executeLargeUpdate(String, String[])
1084 */
1085 @Override
1086 public final int executeUpdate(String sql, String[] columnNames) throws SQLException {
1087 try {
1088 if (isDebugEnabled()) {
1089 debugCode("executeUpdate(" + quote(sql) + ", " + quoteArray(columnNames) + ')');
1090 }
1091 long updateCount = executeUpdateInternal(sql, columnNames);
1092 return updateCount <= Integer.MAX_VALUE ? (int) updateCount : SUCCESS_NO_INFO;
1093 } catch (Exception e) {
1094 throw logAndConvert(e);
1095 }
1096 }
1097
1098 /**
1099 * Executes a statement and returns the update count. This method is not
1100 * allowed for prepared statements.
1101 *
1102 * @param sql the SQL statement
1103 * @param columnNames
1104 * an array of column names indicating the columns with generated
1105 * keys that should be returned from the inserted row
1106 * @return the update count (number of row affected by an insert,
1107 * update or delete, or 0 if no rows or the statement was a
1108 * create, drop, commit or rollback)
1109 * @throws SQLException if a database error occurred or a
1110 * select statement was executed
1111 */
1112 @Override
1113 public final long executeLargeUpdate(String sql, String columnNames[]) throws SQLException {
1114 try {
1115 if (isDebugEnabled()) {
1116 debugCode("executeLargeUpdate(" + quote(sql) + ", " + quoteArray(columnNames) + ')');
1117 }
1118 return executeUpdateInternal(sql, columnNames);
1119 } catch (Exception e) {
1120 throw logAndConvert(e);
1121 }
1122 }
1123
1124 /**
1125 * Executes a statement and returns type of its result. This method is not
1126 * allowed for prepared statements.
1127 *
1128 * @param sql the SQL statement
1129 * @param autoGeneratedKeys
1130 * {@link Statement#RETURN_GENERATED_KEYS} if generated keys should
1131 * be available for retrieval, {@link Statement#NO_GENERATED_KEYS} if
1132 * generated keys should not be available
1133 * @return true if result is a result set, false otherwise
1134 * @throws SQLException if a database error occurred or a
1135 * select statement was executed
1136 */
1137 @Override
1138 public final boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
1139 try {
1140 if (isDebugEnabled()) {
1141 debugCode("execute(" + quote(sql) + ", " + autoGeneratedKeys + ')');
1142 }
1143 return executeInternal(sql, autoGeneratedKeys == RETURN_GENERATED_KEYS);
1144 } catch (Exception e) {
1145 throw logAndConvert(e);
1146 }
1147 }
1148
1149 /**
1150 * Executes a statement and returns type of its result. This method is not
1151 * allowed for prepared statements.
1152 *
1153 * @param sql the SQL statement
1154 * @param columnIndexes
1155 * an array of column indexes indicating the columns with generated
1156 * keys that should be returned from the inserted row
1157 * @return true if result is a result set, false otherwise
1158 * @throws SQLException if a database error occurred or a
1159 * select statement was executed
1160 */
1161 @Override
1162 public final boolean execute(String sql, int[] columnIndexes) throws SQLException {
1163 try {
1164 if (isDebugEnabled()) {
1165 debugCode("execute(" + quote(sql) + ", " + quoteIntArray(columnIndexes) + ')');
1166 }
1167 return executeInternal(sql, columnIndexes);
1168 } catch (Exception e) {
1169 throw logAndConvert(e);
1170 }
1171 }
1172
1173 /**
1174 * Executes a statement and returns type of its result. This method is not
1175 * allowed for prepared statements.
1176 *
1177 * @param sql the SQL statement
1178 * @param columnNames
1179 * an array of column names indicating the columns with generated
1180 * keys that should be returned from the inserted row
1181 * @return true if result is a result set, false otherwise
1182 * @throws SQLException if a database error occurred or a
1183 * select statement was executed
1184 */
1185 @Override
1186 public final boolean execute(String sql, String[] columnNames) throws SQLException {
1187 try {
1188 if (isDebugEnabled()) {
1189 debugCode("execute(" + quote(sql) + ", " + quoteArray(columnNames) + ')');
1190 }
1191 return executeInternal(sql, columnNames);
1192 } catch (Exception e) {
1193 throw logAndConvert(e);
1194 }
1195 }
1196
1197 /**
1198 * Gets the result set holdability.
1199 *
1200 * @return the holdability
1201 */
1202 @Override
1203 public int getResultSetHoldability() throws SQLException {
1204 try {
1205 debugCodeCall("getResultSetHoldability");
1206 checkClosed();
1207 return ResultSet.HOLD_CURSORS_OVER_COMMIT;
1208 } catch (Exception e) {
1209 throw logAndConvert(e);
1210 }
1211 }
1212
1213 /**
1214 * Specifies that this statement will be closed when its dependent result
1215 * set is closed.
1216 *
1217 * @throws SQLException
1218 * if this statement is closed
1219 */
1220 @Override
1221 public void closeOnCompletion() throws SQLException {
1222 try {
1223 debugCodeCall("closeOnCompletion");
1224 checkClosed();
1225 closeOnCompletion = true;
1226 } catch (Exception e) {
1227 throw logAndConvert(e);
1228 }
1229 }
1230
1231 /**
1232 * Returns whether this statement will be closed when its dependent result
1233 * set is closed.
1234 *
1235 * @return {@code true} if this statement will be closed when its dependent
1236 * result set is closed
1237 * @throws SQLException
1238 * if this statement is closed
1239 */
1240 @Override
1241 public boolean isCloseOnCompletion() throws SQLException {
1242 try {
1243 debugCodeCall("isCloseOnCompletion");
1244 checkClosed();
1245 return closeOnCompletion;
1246 } catch (Exception e) {
1247 throw logAndConvert(e);
1248 }
1249 }
1250
1251 void closeIfCloseOnCompletion() {
1252 if (closeOnCompletion) {
1253 try {
1254 closeInternal();
1255 } catch (Exception e) {
1256 // Don't re-throw
1257 logAndConvert(e);
1258 }
1259 }
1260 }
1261
1262 // =============================================================
1263
1264 /**
1265 * Check if this connection is closed.
1266 *
1267 * @throws DbException if the connection or session is closed
1268 */
1269 void checkClosed() {
1270 if (conn == null) {
1271 throw DbException.get(ErrorCode.OBJECT_CLOSED);
1272 }
1273 conn.checkClosed();
1274 }
1275
1276 /**
1277 * INTERNAL.
1278 * Close and old result set if there is still one open.
1279 */
1280 protected void closeOldResultSet() {
1281 try {
1282 if (resultSet != null) {
1283 resultSet.closeInternal(true);
1284 }
1285 if (generatedKeys != null) {
1286 generatedKeys.closeInternal(true);
1287 }
1288 } finally {
1289 cancelled = false;
1290 resultSet = null;
1291 updateCount = -1;
1292 generatedKeys = null;
1293 }
1294 }
1295
1296 /**
1297 * INTERNAL.
1298 * Set the statement that is currently running.
1299 *
1300 * @param c the command
1301 */
1302 void setExecutingStatement(CommandInterface c) {
1303 if (c == null) {
1304 conn.setExecutingStatement(null);
1305 } else {
1306 conn.setExecutingStatement(this);
1307 }
1308 executingCommand = c;
1309 }
1310
1311 /**
1312 * Called when the result set is closed.
1313 *
1314 * @param command the command
1315 * @param closeCommand whether to close the command
1316 */
1317 void onLazyResultSetClose(CommandInterface command, boolean closeCommand) {
1318 setExecutingStatement(null);
1319 command.stop();
1320 if (closeCommand) {
1321 command.close();
1322 }
1323 }
1324
1325 /**
1326 * Returns whether this statement is closed.
1327 *
1328 * @return true if the statement is closed
1329 */
1330 @Override
1331 public boolean isClosed() throws SQLException {
1332 try {
1333 debugCodeCall("isClosed");
1334 return conn == null;
1335 } catch (Exception e) {
1336 throw logAndConvert(e);
1337 }
1338 }
1339
1340 /**
1341 * Return an object of this class if possible.
1342 *
1343 * @param iface the class
1344 * @return this
1345 */
1346 @Override
1347 @SuppressWarnings("unchecked")
1348 public <T> T unwrap(Class<T> iface) throws SQLException {
1349 try {
1350 if (isWrapperFor(iface)) {
1351 return (T) this;
1352 }
1353 throw DbException.getInvalidValueException("iface", iface);
1354 } catch (Exception e) {
1355 throw logAndConvert(e);
1356 }
1357 }
1358
1359 /**
1360 * Checks if unwrap can return an object of this class.
1361 *
1362 * @param iface the class
1363 * @return whether or not the interface is assignable from this class
1364 */
1365 @Override
1366 public boolean isWrapperFor(Class<?> iface) throws SQLException {
1367 return iface != null && iface.isAssignableFrom(getClass());
1368 }
1369
1370 /**
1371 * Returns whether this object is poolable.
1372 * @return false
1373 */
1374 @Override
1375 public boolean isPoolable() {
1376 debugCodeCall("isPoolable");
1377 return false;
1378 }
1379
1380 /**
1381 * Requests that this object should be pooled or not.
1382 * This call is ignored.
1383 *
1384 * @param poolable the requested value
1385 */
1386 @Override
1387 public void setPoolable(boolean poolable) {
1388 if (isDebugEnabled()) {
1389 debugCode("setPoolable(" + poolable + ')');
1390 }
1391 }
1392
1393 /**
1394 * @param identifier
1395 * identifier to quote if required, may be quoted or unquoted
1396 * @param alwaysQuote
1397 * if {@code true} identifier will be quoted unconditionally
1398 * @return specified identifier quoted if required, explicitly requested, or
1399 * if it was already quoted
1400 * @throws NullPointerException
1401 * if identifier is {@code null}
1402 * @throws SQLException
1403 * if identifier is not a valid identifier
1404 */
1405 @Override
1406 public String enquoteIdentifier(String identifier, boolean alwaysQuote) throws SQLException {
1407 if (isSimpleIdentifier(identifier)) {
1408 return alwaysQuote ? '"' + identifier + '"': identifier;
1409 }
1410 try {
1411 int length = identifier.length();
1412 if (length > 0) {
1413 if (identifier.charAt(0) == '"') {
1414 checkQuotes(identifier, 1, length);
1415 return identifier;
1416 } else if (identifier.startsWith("U&\"") || identifier.startsWith("u&\"")) {
1417 // Check validity of double quotes
1418 checkQuotes(identifier, 3, length);
1419 // Check validity of escape sequences
1420 StringUtils.decodeUnicodeStringSQL(identifier, '\\');
1421 return identifier;
1422 }
1423 }
1424 return StringUtils.quoteIdentifier(identifier);
1425 } catch (Exception e) {
1426 throw logAndConvert(e);
1427 }
1428 }
1429
1430 private static void checkQuotes(String identifier, int offset, int length) {
1431 boolean quoted = true;
1432 for (int i = offset; i < length; i++) {
1433 if (identifier.charAt(i) == '"') {
1434 quoted = !quoted;
1435 } else if (!quoted) {
1436 throw DbException.get(ErrorCode.INVALID_NAME_1, identifier);
1437 }
1438 }
1439 if (quoted) {
1440 throw DbException.get(ErrorCode.INVALID_NAME_1, identifier);
1441 }
1442 }
1443
1444 /**
1445 * @param identifier
1446 * identifier to check
1447 * @return is specified identifier may be used without quotes
1448 * @throws NullPointerException
1449 * if identifier is {@code null}
1450 */
1451 @Override
1452 public boolean isSimpleIdentifier(String identifier) throws SQLException {
1453 Session.StaticSettings settings;
1454 try {
1455 checkClosed();
1456 settings = conn.getStaticSettings();
1457 } catch (Exception e) {
1458 throw logAndConvert(e);
1459 }
1460 return ParserUtil.isSimpleIdentifier(identifier, settings.databaseToUpper, settings.databaseToLower);
1461 }
1462
1463 /**
1464 * INTERNAL
1465 */
1466 @Override
1467 public String toString() {
1468 return getTraceObjectName();
1469 }
1470
1471 }
1472