Debian Codegraph @

src/main/org/h2/command/Command.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.command;
7
8 import java.sql.SQLException;
9 import java.util.ArrayList;
10 import java.util.Set;
11 import org.h2.api.ErrorCode;
12 import org.h2.engine.Constants;
13 import org.h2.engine.Database;
14 import org.h2.engine.DbObject;
15 import org.h2.engine.Mode.CharPadding;
16 import org.h2.engine.Session;
17 import org.h2.engine.SessionLocal;
18 import org.h2.expression.ParameterInterface;
19 import org.h2.message.DbException;
20 import org.h2.message.Trace;
21 import org.h2.result.ResultInterface;
22 import org.h2.result.ResultWithGeneratedKeys;
23 import org.h2.result.ResultWithPaddedStrings;
24 import org.h2.util.Utils;
25
26 /**
27 * Represents a SQL statement. This object is only used on the server side.
28 */
29 public abstract class Command implements CommandInterface {
30
31 /**
32 * The session.
33 */
34 protected final SessionLocal session;
35
36 /**
37 * The last start time.
38 */
39 protected long startTimeNanos;
40
41 /**
42 * The trace module.
43 */
44 private final Trace trace;
45
46 /**
47 * If this query was canceled.
48 */
49 private volatile boolean cancel;
50
51 private final String sql;
52
53 private boolean canReuse;
54
55 Command(SessionLocal session, String sql) {
56 this.session = session;
57 this.sql = sql;
58 trace = getDatabase().getTrace(Trace.COMMAND);
59 }
60
61 /**
62 * Check if this command is transactional.
63 * If it is not, then it forces the current transaction to commit.
64 *
65 * @return true if it is
66 */
67 public abstract boolean isTransactional();
68
69 /**
70 * Check if this command is a query.
71 *
72 * @return true if it is
73 */
74 @Override
75 public abstract boolean isQuery();
76
77 /**
78 * Get the list of parameters.
79 *
80 * @return the list of parameters
81 */
82 @Override
83 public abstract ArrayList<? extends ParameterInterface> getParameters();
84
85 /**
86 * Check if this command is read only.
87 *
88 * @return true if it is
89 */
90 public abstract boolean isReadOnly();
91
92 /**
93 * Get an empty result set containing the meta data.
94 *
95 * @return an empty result set
96 */
97 public abstract ResultInterface queryMeta();
98
99 /**
100 * Execute an updating statement (for example insert, delete, or update), if
101 * this is possible.
102 *
103 * @param generatedKeysRequest
104 * {@code false} if generated keys are not needed, {@code true} if
105 * generated keys should be configured automatically, {@code int[]}
106 * to specify column indices to return generated keys from, or
107 * {@code String[]} to specify column names to return generated keys
108 * from
109 * @return the update count and generated keys, if any
110 * @throws DbException if the command is not an updating statement
111 */
112 public abstract ResultWithGeneratedKeys update(Object generatedKeysRequest);
113
114 /**
115 * Execute a query statement, if this is possible.
116 *
117 * @param maxrows the maximum number of rows returned
118 * @return the local result set
119 * @throws DbException if the command is not a query
120 */
121 public abstract ResultInterface query(long maxrows);
122
123 @Override
124 public final ResultInterface getMetaData() {
125 return queryMeta();
126 }
127
128 /**
129 * Start the stopwatch.
130 */
131 void start() {
132 if (trace.isInfoEnabled() || getDatabase().getQueryStatistics()) {
133 startTimeNanos = Utils.currentNanoTime();
134 }
135 }
136
137 void setProgress(Database database, int state) {
138 database.setProgress(state, sql, 0, 0);
139 }
140
141 /**
142 * Check if this command has been canceled, and throw an exception if yes.
143 *
144 * @throws DbException if the statement has been canceled
145 */
146 protected void checkCanceled() {
147 if (cancel) {
148 cancel = false;
149 throw DbException.get(ErrorCode.STATEMENT_WAS_CANCELED);
150 }
151 }
152
153 @Override
154 public void stop() {
155 if (session.isOpen()) {
156 commitIfNonTransactional();
157 if (isTransactional() && session.getAutoCommit()) {
158 session.commit(false);
159 }
160 }
161 if (trace.isInfoEnabled() && startTimeNanos != 0L) {
162 long timeMillis = (System.nanoTime() - startTimeNanos) / 1_000_000L;
163 if (timeMillis > Constants.SLOW_QUERY_LIMIT_MS) {
164 trace.info("slow query: {0} ms", timeMillis);
165 }
166 }
167 }
168
169 /**
170 * Execute a query and return the result.
171 * This method prepares everything and calls {@link #query(long)} finally.
172 *
173 * @param maxrows the maximum number of rows to return
174 * @param scrollable if the result set must be scrollable (ignored)
175 * @return the result set
176 */
177 @Override
178 public ResultInterface executeQuery(long maxrows, boolean scrollable) {
179 startTimeNanos = 0L;
180 long start = 0L;
181 Database database = getDatabase();
182 session.waitIfExclusiveModeEnabled();
183 boolean callStop = true;
184 synchronized (session) {
185 session.startStatementWithinTransaction(this);
186 Session oldSession = session.setThreadLocalSession();
187 try {
188 while (true) {
189 database.checkPowerOff();
190 try {
191 ResultInterface result = query(maxrows);
192 callStop = !result.isLazy();
193 if (database.getMode().charPadding == CharPadding.IN_RESULT_SETS) {
194 return ResultWithPaddedStrings.get(result);
195 }
196 return result;
197 } catch (DbException e) {
198 // cannot retry some commands
199 if (!isRetryable()) {
200 throw e;
201 }
202 start = filterConcurrentUpdate(e, start);
203 } catch (OutOfMemoryError e) {
204 callStop = false;
205 // there is a serious problem:
206 // the transaction may be applied partially
207 // in this case we need to panic:
208 // close the database
209 database.shutdownImmediately();
210 throw DbException.convert(e);
211 } catch (Throwable e) {
212 throw DbException.convert(e);
213 }
214 }
215 } catch (DbException e) {
216 e = e.addSQL(sql);
217 SQLException s = e.getSQLException();
218 database.exceptionThrown(s, sql);
219 if (s.getErrorCode() == ErrorCode.OUT_OF_MEMORY) {
220 callStop = false;
221 database.shutdownImmediately();
222 throw e;
223 }
224 database.checkPowerOff();
225 throw e;
226 } finally {
227 session.resetThreadLocalSession(oldSession);
228 session.endStatement();
229 if (callStop) {
230 stop();
231 }
232 }
233 }
234 }
235
236 @Override
237 public ResultWithGeneratedKeys executeUpdate(Object generatedKeysRequest) {
238 long start = 0;
239 boolean callStop = true;
240 synchronized (session) {
241 Database database = getDatabase();
242 session.waitIfExclusiveModeEnabled();
243 commitIfNonTransactional();
244 SessionLocal.Savepoint rollback = session.setSavepoint();
245 session.startStatementWithinTransaction(this);
246 DbException ex = null;
247 Session oldSession = session.setThreadLocalSession();
248 try {
249 while (true) {
250 database.checkPowerOff();
251 try {
252 return update(generatedKeysRequest);
253 } catch (DbException e) {
254 // cannot retry some commands
255 if (!isRetryable()) {
256 throw e;
257 }
258 start = filterConcurrentUpdate(e, start);
259 } catch (OutOfMemoryError e) {
260 callStop = false;
261 database.shutdownImmediately();
262 throw DbException.convert(e);
263 } catch (Throwable e) {
264 throw DbException.convert(e);
265 }
266 }
267 } catch (DbException e) {
268 e = e.addSQL(sql);
269 SQLException s = e.getSQLException();
270 database.exceptionThrown(s, sql);
271 if (s.getErrorCode() == ErrorCode.OUT_OF_MEMORY) {
272 callStop = false;
273 database.shutdownImmediately();
274 throw e;
275 }
276 try {
277 database.checkPowerOff();
278 if (s.getErrorCode() == ErrorCode.DEADLOCK_1) {
279 session.rollback();
280 } else {
281 session.rollbackTo(rollback);
282 }
283 } catch (Throwable nested) {
284 e.addSuppressed(nested);
285 }
286 ex = e;
287 throw e;
288 } finally {
289 session.resetThreadLocalSession(oldSession);
290 try {
291 session.endStatement();
292 if (callStop) {
293 stop();
294 }
295 } catch (Throwable nested) {
296 if (ex == null) {
297 throw nested;
298 } else {
299 ex.addSuppressed(nested);
300 }
301 }
302 }
303 }
304 }
305
306 private void commitIfNonTransactional() {
307 if (!isTransactional()) {
308 boolean autoCommit = session.getAutoCommit();
309 session.commit(true);
310 if (!autoCommit && session.getAutoCommit()) {
311 session.begin();
312 }
313 }
314 }
315
316 private long filterConcurrentUpdate(DbException e, long start) {
317 int errorCode = e.getErrorCode();
318 if (errorCode != ErrorCode.CONCURRENT_UPDATE_1 && errorCode != ErrorCode.ROW_NOT_FOUND_IN_PRIMARY_INDEX
319 && errorCode != ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1) {
320 throw e;
321 }
322 long now = Utils.currentNanoTime();
323 if (start != 0L && now - start > session.getLockTimeout() * 1_000_000L) {
324 throw DbException.get(ErrorCode.LOCK_TIMEOUT_1, e);
325 }
326 return start == 0L ? now : start;
327 }
328
329 @Override
330 public void close() {
331 canReuse = true;
332 }
333
334 @Override
335 public void cancel() {
336 cancel = true;
337 }
338
339 @Override
340 public String toString() {
341 return sql + Trace.formatParams(getParameters());
342 }
343
344 public boolean isCacheable() {
345 return false;
346 }
347
348 /**
349 * Whether the command is already closed (in which case it can be re-used).
350 *
351 * @return true if it can be re-used
352 */
353 public boolean canReuse() {
354 return canReuse;
355 }
356
357 /**
358 * The command is now re-used, therefore reset the canReuse flag, and the
359 * parameter values.
360 */
361 public void reuse() {
362 canReuse = false;
363 ArrayList<? extends ParameterInterface> parameters = getParameters();
364 for (ParameterInterface param : parameters) {
365 param.setValue(null, true);
366 }
367 }
368
369 public void setCanReuse(boolean canReuse) {
370 this.canReuse = canReuse;
371 }
372
373 public abstract Set<DbObject> getDependencies();
374
375 /**
376 * Returns is this command can be repeated again on locking failure.
377 *
378 * @return is this command can be repeated again on locking failure
379 */
380 protected abstract boolean isRetryable();
381
382 protected final Database getDatabase() {
383 return session.getDatabase();
384 }
385 }