Debian Codegraph @

src/main/org/h2/engine/SessionLocal.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.engine;
7
8 import java.time.Instant;
9 import java.util.ArrayList;
10 import java.util.BitSet;
11 import java.util.Collections;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.Iterator;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Random;
19 import java.util.Set;
20 import java.util.WeakHashMap;
21 import java.util.concurrent.atomic.AtomicReference;
22 import org.h2.api.ErrorCode;
23 import org.h2.api.JavaObjectSerializer;
24 import org.h2.command.Command;
25 import org.h2.command.CommandInterface;
26 import org.h2.command.Parser;
27 import org.h2.command.Prepared;
28 import org.h2.command.ddl.Analyze;
29 import org.h2.command.query.Query;
30 import org.h2.constraint.Constraint;
31 import org.h2.index.Index;
32 import org.h2.index.QueryExpressionIndex;
33 import org.h2.jdbc.JdbcConnection;
34 import org.h2.jdbc.meta.DatabaseMeta;
35 import org.h2.jdbc.meta.DatabaseMetaLocal;
36 import org.h2.message.DbException;
37 import org.h2.message.Trace;
38 import org.h2.message.TraceSystem;
39 import org.h2.mvstore.MVMap;
40 import org.h2.mvstore.db.MVIndex;
41 import org.h2.mvstore.db.MVTable;
42 import org.h2.mvstore.db.Store;
43 import org.h2.mvstore.tx.Transaction;
44 import org.h2.mvstore.tx.TransactionStore;
45 import org.h2.result.Row;
46 import org.h2.schema.Schema;
47 import org.h2.schema.Sequence;
48 import org.h2.store.DataHandler;
49 import org.h2.store.InDoubtTransaction;
50 import org.h2.store.LobStorageFrontend;
51 import org.h2.table.Table;
52 import org.h2.util.DateTimeUtils;
53 import org.h2.util.HasSQL;
54 import org.h2.util.NetworkConnectionInfo;
55 import org.h2.util.SmallLRUCache;
56 import org.h2.util.TimeZoneProvider;
57 import org.h2.util.Utils;
58 import org.h2.value.CompareMode;
59 import org.h2.value.Value;
60 import org.h2.value.ValueLob;
61 import org.h2.value.ValueNull;
62 import org.h2.value.ValueTimestampTimeZone;
63 import org.h2.value.ValueVarchar;
64 import org.h2.value.VersionedValue;
65 import org.h2.value.lob.LobData;
66 import org.h2.value.lob.LobDataDatabase;
67 import org.h2.value.lob.LobDataInMemory;
68
69 /**
70 * A session represents an embedded database connection. When using the server
71 * mode, this object resides on the server side and communicates with a
72 * SessionRemote object on the client side.
73 */
74 public final class SessionLocal extends Session implements TransactionStore.RollbackListener {
75
76 public enum State { INIT, RUNNING, BLOCKED, SLEEP, THROTTLED, SUSPENDED, CLOSED }
77
78 private static final class SequenceAndPrepared {
79
80 private final Sequence sequence;
81
82 private final Prepared prepared;
83
84 SequenceAndPrepared(Sequence sequence, Prepared prepared) {
85 this.sequence = sequence;
86 this.prepared = prepared;
87 }
88
89 @Override
90 public int hashCode() {
91 return 31 * (31 + prepared.hashCode()) + sequence.hashCode();
92 }
93
94 @Override
95 public boolean equals(Object obj) {
96 if (this == obj) {
97 return true;
98 }
99 if (obj == null || obj.getClass() != SequenceAndPrepared.class) {
100 return false;
101 }
102 SequenceAndPrepared other = (SequenceAndPrepared) obj;
103 return sequence == other.sequence && prepared == other.prepared;
104 }
105
106 }
107
108 private static final class RowNumberAndValue {
109
110 long rowNumber;
111
112 Value nextValue;
113
114 RowNumberAndValue(long rowNumber, Value nextValue) {
115 this.rowNumber = rowNumber;
116 this.nextValue = nextValue;
117 }
118
119 }
120
121 /**
122 * The prefix of generated identifiers. It may not have letters, because
123 * they are case sensitive.
124 */
125 private static final String SYSTEM_IDENTIFIER_PREFIX = "_";
126 private static int nextSerialId;
127
128 /**
129 * Thread local session for comparison operations between different data types.
130 */
131 private static final ThreadLocal<Session> THREAD_LOCAL_SESSION = new ThreadLocal<>();
132
133 static Session getThreadLocalSession() {
134 Session session = THREAD_LOCAL_SESSION.get();
135 if (session == null) {
136 THREAD_LOCAL_SESSION.remove();
137 }
138 return session;
139 }
140
141 private final int serialId = nextSerialId++;
142 private Database database;
143 private User user;
144 private final int id;
145
146 private NetworkConnectionInfo networkConnectionInfo;
147
148 private final ArrayList<Table> locks = Utils.newSmallArrayList();
149 private boolean autoCommit = true;
150 private Random random;
151 private int lockTimeout;
152
153 private HashMap<SequenceAndPrepared, RowNumberAndValue> nextValueFor;
154 private WeakHashMap<Sequence, Value> currentValueFor;
155 private Value lastIdentity = ValueNull.INSTANCE;
156
157 private HashMap<String, Savepoint> savepoints;
158 private HashMap<String, Table> localTempTables;
159 private HashMap<String, Index> localTempTableIndexes;
160 private HashMap<String, Constraint> localTempTableConstraints;
161 private int throttleMs;
162 private long lastThrottleNs;
163 private Command currentCommand;
164 private boolean allowLiterals;
165 private String currentSchemaName;
166 private String[] schemaSearchPath;
167 private Trace trace;
168 private HashMap<String, ValueLob> removeLobMap;
169 private int systemIdentifier;
170 private HashMap<String, Procedure> procedures;
171 private boolean autoCommitAtTransactionEnd;
172 private String currentTransactionName;
173 private volatile long cancelAtNs;
174 private final ValueTimestampTimeZone sessionStart;
175 private Instant commandStartOrEnd;
176 private ValueTimestampTimeZone currentTimestamp;
177 private HashMap<String, Value> variables;
178 private int queryTimeout;
179 private boolean commitOrRollbackDisabled;
180 private Table waitForLock;
181 private Thread waitForLockThread;
182 private int modificationId;
183 private int objectId;
184 private final int queryCacheSize;
185 private SmallLRUCache<String, Command> queryCache;
186 private long modificationMetaID = -1;
187 private int createViewLevel;
188 private volatile SmallLRUCache<Object, QueryExpressionIndex> viewIndexCache;
189 private HashMap<Object, QueryExpressionIndex> derivedTableIndexCache;
190 private boolean lazyQueryExecution;
191
192 private BitSet nonKeywords;
193
194 private TimeZoneProvider timeZone;
195
196 /**
197 * Tables marked for ANALYZE after the current transaction is committed.
198 * Prevents us calling ANALYZE repeatedly in large transactions.
199 */
200 private HashSet<Table> tablesToAnalyze;
201
202 /**
203 * Temporary LOBs from result sets. Those are kept for some time. The
204 * problem is that transactions are committed before the result is returned,
205 * and in some cases the next transaction is already started before the
206 * result is read (for example when using the server mode, when accessing
207 * metadata methods). We can't simply free those values up when starting the
208 * next transaction, because they would be removed too early.
209 */
210 private LinkedList<TimeoutValue> temporaryResultLobs;
211
212 /**
213 * The temporary LOBs that need to be removed on commit.
214 */
215 private ArrayList<ValueLob> temporaryLobs;
216
217 private Transaction transaction;
218 private final AtomicReference<State> state = new AtomicReference<>(State.INIT);
219 private long startStatement = -1;
220
221 /**
222 * Isolation level.
223 */
224 private IsolationLevel isolationLevel = IsolationLevel.READ_COMMITTED;
225
226 /**
227 * The snapshot data modification id. If isolation level doesn't allow
228 * non-repeatable reads the session uses a snapshot versions of data. After
229 * commit or rollback these snapshots are discarded and cached results of
230 * queries may became invalid. Commit and rollback allocate a new data
231 * modification id and store it here to forbid usage of older results.
232 */
233 private long snapshotDataModificationId;
234
235 /**
236 * Set of database object ids to be released at the end of transaction
237 */
238 private BitSet idsToRelease;
239
240 /**
241 * Whether length in definitions of data types is truncated.
242 */
243 private boolean truncateLargeLength;
244
245 /**
246 * Whether BINARY is parsed as VARBINARY.
247 */
248 private boolean variableBinary;
249
250 /**
251 * Whether INFORMATION_SCHEMA contains old-style tables.
252 */
253 private boolean oldInformationSchema;
254
255 /**
256 * Whether commands are executed in quirks mode to support scripts from older versions of H2.
257 */
258 private boolean quirksMode;
259
260 public SessionLocal(Database database, User user, int id) {
261 this.database = database;
262 this.queryTimeout = database.getSettings().maxQueryTimeout;
263 this.queryCacheSize = database.getSettings().queryCacheSize;
264 this.user = user;
265 this.id = id;
266 this.lockTimeout = database.getLockTimeout();
267 Schema mainSchema = database.getMainSchema();
268 this.currentSchemaName = mainSchema != null ? mainSchema.getName()
269 : database.sysIdentifier(Constants.SCHEMA_MAIN);
270 timeZone = DateTimeUtils.getTimeZone();
271 sessionStart = DateTimeUtils.currentTimestamp(timeZone, commandStartOrEnd = Instant.now());
272 }
273
274 public void setLazyQueryExecution(boolean lazyQueryExecution) {
275 this.lazyQueryExecution = lazyQueryExecution;
276 }
277
278 public boolean isLazyQueryExecution() {
279 return lazyQueryExecution;
280 }
281
282 /**
283 * This method is called before and after parsing of view definition and may
284 * be called recursively.
285 *
286 * @param parsingView
287 * {@code true} if this method is called before parsing of view
288 * definition, {@code false} if it is called after it.
289 */
290 public void setParsingCreateView(boolean parsingView) {
291 createViewLevel += parsingView ? 1 : -1;
292 }
293
294 public boolean isParsingCreateView() {
295 return createViewLevel != 0;
296 }
297
298 @Override
299 public ArrayList<String> getClusterServers() {
300 return new ArrayList<>();
301 }
302
303 public boolean setCommitOrRollbackDisabled(boolean x) {
304 boolean old = commitOrRollbackDisabled;
305 commitOrRollbackDisabled = x;
306 return old;
307 }
308
309 private void initVariables() {
310 if (variables == null) {
311 variables = newStringsMap();
312 }
313 }
314
315 /**
316 * Set the value of the given variable for this session.
317 *
318 * @param name the name of the variable (may not be null)
319 * @param value the new value (may not be null)
320 */
321 public void setVariable(String name, Value value) {
322 initVariables();
323 modificationId++;
324 Value old;
325 if (value == ValueNull.INSTANCE) {
326 old = variables.remove(name);
327 } else {
328 if (value instanceof ValueLob) {
329 // link LOB values, to make sure we have our own object
330 value = ((ValueLob) value).copy(getDatabase(), LobStorageFrontend.TABLE_ID_SESSION_VARIABLE);
331 }
332 old = variables.put(name, value);
333 }
334 if (old instanceof ValueLob) {
335 ((ValueLob) old).remove();
336 }
337 }
338
339 /**
340 * Get the value of the specified user defined variable. This method always
341 * returns a value; it returns ValueNull.INSTANCE if the variable doesn't
342 * exist.
343 *
344 * @param name the variable name
345 * @return the value, or NULL
346 */
347 public Value getVariable(String name) {
348 initVariables();
349 Value v = variables.get(name);
350 return v == null ? ValueNull.INSTANCE : v;
351 }
352
353 /**
354 * Get the list of variable names that are set for this session.
355 *
356 * @return the list of names
357 */
358 public String[] getVariableNames() {
359 if (variables == null) {
360 return new String[0];
361 }
362 return variables.keySet().toArray(new String[0]);
363 }
364
365 /**
366 * Get the local temporary table if one exists with that name, or null if
367 * not.
368 *
369 * @param name the table name
370 * @return the table, or null
371 */
372 public Table findLocalTempTable(String name) {
373 if (localTempTables == null) {
374 return null;
375 }
376 return localTempTables.get(name);
377 }
378
379 public List<Table> getLocalTempTables() {
380 if (localTempTables == null) {
381 return Collections.emptyList();
382 }
383 return new ArrayList<>(localTempTables.values());
384 }
385
386 /**
387 * Add a local temporary table to this session.
388 *
389 * @param table the table to add
390 * @throws DbException if a table with this name already exists
391 */
392 public void addLocalTempTable(Table table) {
393 if (localTempTables == null) {
394 localTempTables = newStringsMap();
395 }
396 if (localTempTables.putIfAbsent(table.getName(), table) != null) {
397 StringBuilder builder = new StringBuilder();
398 table.getSQL(builder, HasSQL.TRACE_SQL_FLAGS).append(" AS ");
399 Parser.quoteIdentifier(table.getName(), HasSQL.TRACE_SQL_FLAGS);
400 throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, builder.toString());
401 }
402 modificationId++;
403 }
404
405 /**
406 * Drop and remove the given local temporary table from this session.
407 *
408 * @param table the table
409 */
410 public void removeLocalTempTable(Table table) {
411 if (localTempTables != null && localTempTables.remove(table.getName()) != null) {
412 modificationId++;
413 Database db = database;
414 if (db != null) {
415 synchronized (db) {
416 table.removeChildrenAndResources(this);
417 }
418 }
419 }
420 }
421
422 /**
423 * Get the local temporary index if one exists with that name, or null if
424 * not.
425 *
426 * @param name the table name
427 * @return the table, or null
428 */
429 public Index findLocalTempTableIndex(String name) {
430 if (localTempTableIndexes == null) {
431 return null;
432 }
433 return localTempTableIndexes.get(name);
434 }
435
436 public HashMap<String, Index> getLocalTempTableIndexes() {
437 if (localTempTableIndexes == null) {
438 return new HashMap<>();
439 }
440 return localTempTableIndexes;
441 }
442
443 /**
444 * Add a local temporary index to this session.
445 *
446 * @param index the index to add
447 * @throws DbException if a index with this name already exists
448 */
449 public void addLocalTempTableIndex(Index index) {
450 if (localTempTableIndexes == null) {
451 localTempTableIndexes = newStringsMap();
452 }
453 if (localTempTableIndexes.putIfAbsent(index.getName(), index) != null) {
454 throw DbException.get(ErrorCode.INDEX_ALREADY_EXISTS_1, index.getTraceSQL());
455 }
456 }
457
458 /**
459 * Drop and remove the given local temporary index from this session.
460 *
461 * @param index the index
462 */
463 public void removeLocalTempTableIndex(Index index) {
464 if (localTempTableIndexes != null) {
465 localTempTableIndexes.remove(index.getName());
466 synchronized (database) {
467 index.removeChildrenAndResources(this);
468 }
469 }
470 }
471
472 /**
473 * Get the local temporary constraint if one exists with that name, or
474 * null if not.
475 *
476 * @param name the constraint name
477 * @return the constraint, or null
478 */
479 public Constraint findLocalTempTableConstraint(String name) {
480 if (localTempTableConstraints == null) {
481 return null;
482 }
483 return localTempTableConstraints.get(name);
484 }
485
486 /**
487 * Get the map of constraints for all constraints on local, temporary
488 * tables, if any. The map's keys are the constraints' names.
489 *
490 * @return the map of constraints, or null
491 */
492 public HashMap<String, Constraint> getLocalTempTableConstraints() {
493 if (localTempTableConstraints == null) {
494 return new HashMap<>();
495 }
496 return localTempTableConstraints;
497 }
498
499 /**
500 * Add a local temporary constraint to this session.
501 *
502 * @param constraint the constraint to add
503 * @throws DbException if a constraint with the same name already exists
504 */
505 public void addLocalTempTableConstraint(Constraint constraint) {
506 if (localTempTableConstraints == null) {
507 localTempTableConstraints = newStringsMap();
508 }
509 String name = constraint.getName();
510 if (localTempTableConstraints.putIfAbsent(name, constraint) != null) {
511 throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, constraint.getTraceSQL());
512 }
513 }
514
515 /**
516 * Drop and remove the given local temporary constraint from this session.
517 *
518 * @param constraint the constraint
519 */
520 void removeLocalTempTableConstraint(Constraint constraint) {
521 if (localTempTableConstraints != null) {
522 localTempTableConstraints.remove(constraint.getName());
523 synchronized (database) {
524 constraint.removeChildrenAndResources(this);
525 }
526 }
527 }
528
529 @Override
530 public boolean getAutoCommit() {
531 return autoCommit;
532 }
533
534 public User getUser() {
535 return user;
536 }
537
538 @Override
539 public void setAutoCommit(boolean b) {
540 autoCommit = b;
541 }
542
543 public int getLockTimeout() {
544 return lockTimeout;
545 }
546
547 public void setLockTimeout(int lockTimeout) {
548 this.lockTimeout = lockTimeout;
549 if (hasTransaction()) {
550 transaction.setTimeoutMillis(lockTimeout);
551 }
552 }
553
554 @Override
555 public synchronized CommandInterface prepareCommand(String sql,
556 int fetchSize) {
557 return prepareLocal(sql);
558 }
559
560 /**
561 * Parse and prepare the given SQL statement. This method also checks the
562 * rights.
563 *
564 * @param sql the SQL statement
565 * @return the prepared statement
566 */
567 public Prepared prepare(String sql) {
568 return prepare(sql, false, false);
569 }
570
571 /**
572 * Parse and prepare the given SQL statement.
573 *
574 * @param sql the SQL statement
575 * @param rightsChecked true if the rights have already been checked
576 * @param literalsChecked true if the sql string has already been checked
577 * for literals (only used if ALLOW_LITERALS NONE is set).
578 * @return the prepared statement
579 */
580 public Prepared prepare(String sql, boolean rightsChecked, boolean literalsChecked) {
581 Parser parser = new Parser(this);
582 parser.setRightsChecked(rightsChecked);
583 parser.setLiteralsChecked(literalsChecked);
584 return parser.prepare(sql);
585 }
586
587 /**
588 * Parse a query and prepare its expressions. Rights and literals must be
589 * already checked.
590 *
591 * @param sql the SQL statement
592 * @return the prepared statement
593 */
594 public Query prepareQueryExpression(String sql) {
595 Parser parser = new Parser(this);
596 parser.setRightsChecked(true);
597 parser.setLiteralsChecked(true);
598 return parser.prepareQueryExpression(sql);
599 }
600
601
602 /**
603 * Parse and prepare the given SQL statement.
604 * This method also checks if the connection has been closed.
605 *
606 * @param sql the SQL statement
607 * @return the prepared statement
608 */
609 public Command prepareLocal(String sql) {
610 if (isClosed()) {
611 throw DbException.get(ErrorCode.CONNECTION_BROKEN_1,
612 "session closed");
613 }
614 Command command;
615 if (queryCacheSize > 0) {
616 if (queryCache == null) {
617 queryCache = SmallLRUCache.newInstance(queryCacheSize);
618 modificationMetaID = getDatabase().getModificationMetaId();
619 } else {
620 long newModificationMetaID = getDatabase().getModificationMetaId();
621 if (newModificationMetaID != modificationMetaID) {
622 queryCache.clear();
623 modificationMetaID = newModificationMetaID;
624 }
625 command = queryCache.get(sql);
626 if (command != null && command.canReuse()) {
627 command.reuse();
628 return command;
629 }
630 }
631 }
632 Parser parser = new Parser(this);
633 try {
634 command = parser.prepareCommand(sql);
635 } finally {
636 // we can't reuse indexes of derived tables, so just drop the whole cache
637 derivedTableIndexCache = null;
638 }
639 if (queryCache != null) {
640 if (command.isCacheable()) {
641 queryCache.put(sql, command);
642 }
643 }
644 return command;
645 }
646
647 /**
648 * Arranges for the specified database object id to be released
649 * at the end of the current transaction.
650 * @param id to be scheduled
651 */
652 void scheduleDatabaseObjectIdForRelease(int id) {
653 if (idsToRelease == null) {
654 idsToRelease = new BitSet();
655 }
656 idsToRelease.set(id);
657 }
658
659 public Database getDatabase() {
660 if (database == null) {
661 throw DbException.get(ErrorCode.DATABASE_IS_CLOSED);
662 }
663 return database;
664 }
665
666 /**
667 * Commit the current transaction. If the statement was not a data
668 * definition statement, and if there are temporary tables that should be
669 * dropped or truncated at commit, this is done as well.
670 *
671 * @param ddl if the statement was a data definition statement
672 */
673 public void commit(boolean ddl) {
674 beforeCommitOrRollback();
675 if (hasTransaction()) {
676 try {
677 markUsedTablesAsUpdated();
678 transaction.commit();
679 removeTemporaryLobs(true);
680 endTransaction();
681 } finally {
682 transaction = null;
683 }
684 if (!ddl) {
685 // do not clean the temp tables if the last command was a
686 // create/drop
687 cleanTempTables(false);
688 if (autoCommitAtTransactionEnd) {
689 autoCommit = true;
690 autoCommitAtTransactionEnd = false;
691 }
692 }
693 analyzeTables();
694 }
695 }
696
697 private void markUsedTablesAsUpdated() {
698 // TODO should not rely on locking
699 if (!locks.isEmpty()) {
700 for (Table t : locks) {
701 if (t instanceof MVTable) {
702 ((MVTable) t).commit();
703 }
704 }
705 }
706 }
707
708 private void analyzeTables() {
709 // On rare occasions it can be called concurrently (i.e. from close())
710 // without proper locking, but instead of oversynchronizing
711 // we just skip this optional operation in such case
712 if (tablesToAnalyze != null &&
713 Thread.holdsLock(this)) {
714 // take a local copy and clear because in rare cases we can call
715 // back into markTableForAnalyze while iterating here
716 HashSet<Table> tablesToAnalyzeLocal = tablesToAnalyze;
717 tablesToAnalyze = null;
718 int rowCount = getDatabase().getSettings().analyzeSample / 10;
719 for (Table table : tablesToAnalyzeLocal) {
720 Analyze.analyzeTable(this, table, rowCount, false);
721 }
722 // analyze can lock the meta
723 getDatabase().unlockMeta(this);
724 // table analysis opens a new transaction(s),
725 // so we need to commit afterwards whatever leftovers might be
726 commit(true);
727 }
728 }
729
730 private void removeTemporaryLobs(boolean onTimeout) {
731 if (temporaryLobs != null) {
732 for (ValueLob v : temporaryLobs) {
733 if (!v.isLinkedToTable()) {
734 v.remove();
735 }
736 }
737 temporaryLobs.clear();
738 }
739 if (temporaryResultLobs != null && !temporaryResultLobs.isEmpty()) {
740 long keepYoungerThan = System.nanoTime() - getDatabase().getSettings().lobTimeout * 1_000_000L;
741 while (!temporaryResultLobs.isEmpty()) {
742 TimeoutValue tv = temporaryResultLobs.getFirst();
743 if (onTimeout && tv.created - keepYoungerThan >= 0) {
744 break;
745 }
746 ValueLob v = temporaryResultLobs.removeFirst().value;
747 if (!v.isLinkedToTable()) {
748 v.remove();
749 }
750 }
751 }
752 }
753
754 private void beforeCommitOrRollback() {
755 if (commitOrRollbackDisabled && !locks.isEmpty()) {
756 throw DbException.get(ErrorCode.COMMIT_ROLLBACK_NOT_ALLOWED);
757 }
758 currentTransactionName = null;
759 currentTimestamp = null;
760 getDatabase().throwLastBackgroundException();
761 }
762
763 private void endTransaction() {
764 if (removeLobMap != null && !removeLobMap.isEmpty()) {
765 for (ValueLob v : removeLobMap.values()) {
766 v.remove();
767 }
768 removeLobMap = null;
769 }
770 unlockAll();
771 if (idsToRelease != null) {
772 getDatabase().releaseDatabaseObjectIds(idsToRelease);
773 idsToRelease = null;
774 }
775 if (hasTransaction() && !transaction.allowNonRepeatableRead()) {
776 snapshotDataModificationId = getDatabase().getNextModificationDataId();
777 }
778 }
779
780 /**
781 * Returns the data modification id of transaction's snapshot, or 0 if
782 * isolation level doesn't use snapshots.
783 *
784 * @return the data modification id of transaction's snapshot, or 0
785 */
786 public long getSnapshotDataModificationId() {
787 return snapshotDataModificationId;
788 }
789
790 /**
791 * Fully roll back the current transaction.
792 */
793 public void rollback() {
794 beforeCommitOrRollback();
795 if (hasTransaction()) {
796 rollbackTo(null);
797 }
798 idsToRelease = null;
799 cleanTempTables(false);
800 if (autoCommitAtTransactionEnd) {
801 autoCommit = true;
802 autoCommitAtTransactionEnd = false;
803 }
804 endTransaction();
805 }
806
807 /**
808 * Partially roll back the current transaction.
809 *
810 * @param savepoint the savepoint to which should be rolled back
811 */
812 public void rollbackTo(Savepoint savepoint) {
813 int index = savepoint == null ? 0 : savepoint.logIndex;
814 if (hasTransaction()) {
815 markUsedTablesAsUpdated();
816 if (savepoint == null) {
817 transaction.rollback();
818 transaction = null;
819 } else {
820 transaction.rollbackToSavepoint(savepoint.transactionSavepoint);
821 }
822 }
823 if (savepoints != null) {
824 String[] names = savepoints.keySet().toArray(new String[0]);
825 for (String name : names) {
826 Savepoint sp = savepoints.get(name);
827 int savepointIndex = sp.logIndex;
828 if (savepointIndex > index) {
829 savepoints.remove(name);
830 }
831 }
832 }
833
834 // Because cache may have captured query result (in Query.lastResult),
835 // which is based on data from uncommitted transaction.,
836 // It is not valid after rollback, therefore cache has to be cleared.
837 if (queryCache != null) {
838 queryCache.clear();
839 }
840 }
841
842 @Override
843 public boolean hasPendingTransaction() {
844 return hasTransaction() && transaction.hasChanges() && transaction.getStatus() != Transaction.STATUS_PREPARED;
845 }
846
847 /**
848 * Create a savepoint to allow rolling back to this state.
849 *
850 * @return the savepoint
851 */
852 public Savepoint setSavepoint() {
853 Savepoint sp = new Savepoint();
854 sp.transactionSavepoint = getStatementSavepoint();
855 return sp;
856 }
857
858 public int getId() {
859 return id;
860 }
861
862 @Override
863 public void cancel() {
864 cancelAtNs = Utils.currentNanoTime();
865 }
866
867 /**
868 * Cancel the transaction and close the session if needed.
869 */
870 void suspend() {
871 cancel();
872 if (transitionToState(State.SUSPENDED, false) == State.SLEEP) {
873 close();
874 }
875 }
876
877 @Override
878 public void close() {
879 // this is the only operation that can be invoked concurrently
880 // so, we should prevent double-closure
881 if (state.getAndSet(State.CLOSED) != State.CLOSED) {
882 try {
883 if (queryCache != null) {
884 queryCache.clear();
885 }
886 database.throwLastBackgroundException();
887
888 database.checkPowerOff();
889
890 // release any open table locks
891 if (hasPreparedTransaction()) {
892 removeLobMap = null;
893 endTransaction();
894 } else {
895 rollback();
896 removeTemporaryLobs(false);
897 cleanTempTables(true);
898 commit(true); // temp table removal may have opened new transaction
899 }
900
901 // Table#removeChildrenAndResources can take the meta lock,
902 // and we need to unlock before we call removeSession(), which might
903 // want to take the meta lock using the system session.
904 database.unlockMeta(this);
905 } finally {
906 database.removeSession(this);
907 database = null;
908 user = null;
909 }
910 }
911 }
912
913 /**
914 * Register table as locked within current transaction.
915 * Table is unlocked on commit or rollback.
916 * It also assumes that table will be modified by transaction.
917 *
918 * @param table the table that is locked
919 */
920 public void registerTableAsLocked(Table table) {
921 if (SysProperties.CHECK) {
922 if (locks.contains(table)) {
923 throw DbException.getInternalError(table.toString());
924 }
925 }
926 locks.add(table);
927 }
928
929 /**
930 * Register table as updated within current transaction.
931 * This is used instead of table locking when lock mode is LOCK_MODE_OFF.
932 *
933 * @param table to register
934 */
935 public void registerTableAsUpdated(Table table) {
936 if (!locks.contains(table)) {
937 locks.add(table);
938 }
939 }
940
941 /**
942 * Unlock just this table.
943 *
944 * @param t the table to unlock
945 */
946 void unlock(Table t) {
947 locks.remove(t);
948 }
949
950
951 private boolean hasTransaction() {
952 return transaction != null;
953 }
954
955 private void unlockAll() {
956 if (!locks.isEmpty()) {
957 Table[] array = locks.toArray(new Table[0]);
958 for (Table t : array) {
959 if (t != null) {
960 t.unlock(this);
961 }
962 }
963 locks.clear();
964 }
965 Database.unlockMetaDebug(this);
966 savepoints = null;
967 sessionStateChanged = true;
968 }
969
970 private void cleanTempTables(boolean closeSession) {
971 if (localTempTables != null && !localTempTables.isEmpty()) {
972 Iterator<Table> it = localTempTables.values().iterator();
973 while (it.hasNext()) {
974 Table table = it.next();
975 if (closeSession || table.getOnCommitDrop()) {
976 modificationId++;
977 table.setModified();
978 it.remove();
979 // Exception thrown in org.h2.engine.Database.removeMeta
980 // if line below is missing with TestDeadlock
981 database.lockMeta(this);
982 table.removeChildrenAndResources(this);
983 if (closeSession) {
984 database.throwLastBackgroundException();
985 }
986 } else if (table.getOnCommitTruncate()) {
987 table.truncate(this);
988 }
989 }
990 }
991 }
992
993 public Random getRandom() {
994 if (random == null) {
995 random = new Random();
996 }
997 return random;
998 }
999
1000 @Override
1001 public Trace getTrace() {
1002 if (trace != null && !isClosed()) {
1003 return trace;
1004 }
1005 String traceModuleName = "jdbc[" + id + "]";
1006 Database db = database;
1007 if (isClosed() || db == null) {
1008 return new TraceSystem(null).getTrace(traceModuleName);
1009 }
1010 trace = db.getTraceSystem().getTrace(traceModuleName);
1011 return trace;
1012 }
1013
1014 /**
1015 * Returns the next value of the sequence in this session.
1016 *
1017 * @param sequence
1018 * the sequence
1019 * @param prepared
1020 * current prepared command, select, or {@code null}
1021 * @return the next value of the sequence in this session
1022 */
1023 public Value getNextValueFor(Sequence sequence, Prepared prepared) {
1024 Value value;
1025 Mode mode = getMode();
1026 if (mode.nextValueReturnsDifferentValues || prepared == null) {
1027 value = sequence.getNext(this);
1028 } else {
1029 if (nextValueFor == null) {
1030 nextValueFor = new HashMap<>();
1031 }
1032 SequenceAndPrepared key = new SequenceAndPrepared(sequence, prepared);
1033 RowNumberAndValue data = nextValueFor.get(key);
1034 long rowNumber = prepared.getCurrentRowNumber();
1035 if (data != null) {
1036 if (data.rowNumber == rowNumber) {
1037 value = data.nextValue;
1038 } else {
1039 data.nextValue = value = sequence.getNext(this);
1040 data.rowNumber = rowNumber;
1041 }
1042 } else {
1043 value = sequence.getNext(this);
1044 nextValueFor.put(key, new RowNumberAndValue(rowNumber, value));
1045 }
1046 }
1047 WeakHashMap<Sequence, Value> currentValueFor = this.currentValueFor;
1048 if (currentValueFor == null) {
1049 this.currentValueFor = currentValueFor = new WeakHashMap<>();
1050 }
1051 currentValueFor.put(sequence, value);
1052 if (mode.takeGeneratedSequenceValue) {
1053 lastIdentity = value;
1054 }
1055 return value;
1056 }
1057
1058 /**
1059 * Returns the current value of the sequence in this session.
1060 *
1061 * @param sequence
1062 * the sequence
1063 * @return the current value of the sequence in this session
1064 * @throws DbException
1065 * if current value is not defined
1066 */
1067 public Value getCurrentValueFor(Sequence sequence) {
1068 WeakHashMap<Sequence, Value> currentValueFor = this.currentValueFor;
1069 if (currentValueFor != null) {
1070 Value value = currentValueFor.get(sequence);
1071 if (value != null) {
1072 return value;
1073 }
1074 }
1075 throw DbException.get(ErrorCode.CURRENT_SEQUENCE_VALUE_IS_NOT_DEFINED_IN_SESSION_1, sequence.getTraceSQL());
1076 }
1077
1078 public void setLastIdentity(Value last) {
1079 this.lastIdentity = last;
1080 }
1081
1082 public Value getLastIdentity() {
1083 return lastIdentity;
1084 }
1085
1086 /**
1087 * Whether the session contains any uncommitted changes.
1088 *
1089 * @return true if yes
1090 */
1091 public boolean containsUncommitted() {
1092 return transaction != null && transaction.hasChanges();
1093 }
1094
1095 /**
1096 * Create a savepoint that is linked to the current log position.
1097 *
1098 * @param name the savepoint name
1099 */
1100 public void addSavepoint(String name) {
1101 if (savepoints == null) {
1102 savepoints = newStringsMap();
1103 }
1104 savepoints.put(name, setSavepoint());
1105 }
1106
1107 /**
1108 * Undo all operations back to the log position of the given savepoint.
1109 *
1110 * @param name the savepoint name
1111 */
1112 public void rollbackToSavepoint(String name) {
1113 beforeCommitOrRollback();
1114 Savepoint savepoint;
1115 if (savepoints == null || (savepoint = savepoints.get(name)) == null) {
1116 throw DbException.get(ErrorCode.SAVEPOINT_IS_INVALID_1, name);
1117 }
1118 rollbackTo(savepoint);
1119 }
1120
1121 /**
1122 * Prepare the given transaction.
1123 *
1124 * @param transactionName the name of the transaction
1125 */
1126 public void prepareCommit(String transactionName) {
1127 if (hasPendingTransaction()) {
1128 // need to commit even if rollback is not possible (create/drop
1129 // table and so on)
1130 getDatabase().prepareCommit(this, transactionName);
1131 }
1132 currentTransactionName = transactionName;
1133 }
1134
1135 /**
1136 * Checks presence of prepared transaction in this session.
1137 *
1138 * @return {@code true} if there is a prepared transaction,
1139 * {@code false} otherwise
1140 */
1141 public boolean hasPreparedTransaction() {
1142 return currentTransactionName != null;
1143 }
1144
1145 /**
1146 * Commit or roll back the given transaction.
1147 *
1148 * @param transactionName the name of the transaction
1149 * @param commit true for commit, false for rollback
1150 */
1151 public void setPreparedTransaction(String transactionName, boolean commit) {
1152 if (hasPreparedTransaction() && currentTransactionName.equals(transactionName)) {
1153 if (commit) {
1154 commit(false);
1155 } else {
1156 rollback();
1157 }
1158 } else {
1159 ArrayList<InDoubtTransaction> list = getDatabase().getInDoubtTransactions();
1160 int state = commit ? InDoubtTransaction.COMMIT : InDoubtTransaction.ROLLBACK;
1161 boolean found = false;
1162 for (InDoubtTransaction p: list) {
1163 if (p.getTransactionName().equals(transactionName)) {
1164 p.setState(state);
1165 found = true;
1166 break;
1167 }
1168 }
1169 if (!found) {
1170 throw DbException.get(ErrorCode.TRANSACTION_NOT_FOUND_1,
1171 transactionName);
1172 }
1173 }
1174 }
1175
1176 @Override
1177 public boolean isClosed() {
1178 return state.get() == State.CLOSED;
1179 }
1180
1181 public boolean isOpen() {
1182 State current = state.get();
1183 checkSuspended(current);
1184 return current != State.CLOSED;
1185 }
1186
1187 public void setThrottle(int throttle) {
1188 this.throttleMs = throttle;
1189 }
1190
1191 /**
1192 * Wait for some time if this session is throttled (slowed down).
1193 */
1194 public void throttle() {
1195 if (throttleMs == 0) {
1196 return;
1197 }
1198 long time = System.nanoTime();
1199 if (lastThrottleNs != 0L && time - lastThrottleNs < Constants.THROTTLE_DELAY * 1_000_000L) {
1200 return;
1201 }
1202 lastThrottleNs = Utils.nanoTimePlusMillis(time, throttleMs);
1203 State prevState = transitionToState(State.THROTTLED, false);
1204 try {
1205 Thread.sleep(throttleMs);
1206 } catch (InterruptedException ignore) {
1207 } finally {
1208 transitionToState(prevState, false);
1209 }
1210 }
1211
1212 /**
1213 * Set the current command of this session. This is done just before
1214 * executing the statement.
1215 *
1216 * @param command the command
1217 */
1218 private void setCurrentCommand(Command command) {
1219 State targetState = command == null ? State.SLEEP : State.RUNNING;
1220 transitionToState(targetState, true);
1221 if (isOpen()) {
1222 currentCommand = command;
1223 commandStartOrEnd = Instant.now();
1224 if (command != null) {
1225 if (queryTimeout > 0) {
1226 cancelAtNs = Utils.currentNanoTimePlusMillis(queryTimeout);
1227 }
1228 } else {
1229 if (currentTimestamp != null && !getMode().dateTimeValueWithinTransaction) {
1230 currentTimestamp = null;
1231 }
1232 if (nextValueFor != null) {
1233 nextValueFor.clear();
1234 }
1235 }
1236 }
1237 }
1238
1239 private State transitionToState(State targetState, boolean checkSuspended) {
1240 State currentState;
1241 while((currentState = state.get()) != State.CLOSED &&
1242 (!checkSuspended || checkSuspended(currentState)) &&
1243 !state.compareAndSet(currentState, targetState)) {/**/}
1244 return currentState;
1245 }
1246
1247 private boolean checkSuspended(State currentState) {
1248 if (currentState == State.SUSPENDED) {
1249 close();
1250 throw DbException.get(ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE);
1251 }
1252 return true;
1253 }
1254
1255 /**
1256 * Check if the current transaction is canceled by calling
1257 * Statement.cancel() or because a session timeout was set and expired.
1258 *
1259 * @throws DbException if the transaction is canceled
1260 */
1261 public void checkCanceled() {
1262 throttle();
1263 long cancel = cancelAtNs;
1264 if (cancel == 0L) {
1265 return;
1266 }
1267 if (System.nanoTime() - cancel >= 0L) {
1268 cancelAtNs = 0L;
1269 throw DbException.get(ErrorCode.STATEMENT_WAS_CANCELED);
1270 }
1271 }
1272
1273 /**
1274 * Get the cancel time.
1275 *
1276 * @return the time or 0 if not set
1277 */
1278 public long getCancel() {
1279 return cancelAtNs;
1280 }
1281
1282 public Command getCurrentCommand() {
1283 return currentCommand;
1284 }
1285
1286 public ValueTimestampTimeZone getCommandStartOrEnd() {
1287 return DateTimeUtils.currentTimestamp(timeZone, commandStartOrEnd);
1288 }
1289
1290 public boolean getAllowLiterals() {
1291 return allowLiterals;
1292 }
1293
1294 public void setAllowLiterals(boolean b) {
1295 this.allowLiterals = b;
1296 }
1297
1298 public void setCurrentSchema(Schema schema) {
1299 modificationId++;
1300 if (queryCache != null) {
1301 queryCache.clear();
1302 }
1303 this.currentSchemaName = schema.getName();
1304 }
1305
1306 @Override
1307 public String getCurrentSchemaName() {
1308 return currentSchemaName;
1309 }
1310
1311 @Override
1312 public void setCurrentSchemaName(String schemaName) {
1313 Schema schema = getDatabase().getSchema(schemaName);
1314 setCurrentSchema(schema);
1315 }
1316
1317 /**
1318 * Create an internal connection. This connection is used when initializing
1319 * triggers, and when calling user defined functions.
1320 *
1321 * @param columnList if the url should be 'jdbc:columnlist:connection'
1322 * @return the internal connection
1323 */
1324 public JdbcConnection createConnection(boolean columnList) {
1325 String url;
1326 if (columnList) {
1327 url = Constants.CONN_URL_COLUMNLIST;
1328 } else {
1329 url = Constants.CONN_URL_INTERNAL;
1330 }
1331 return new JdbcConnection(this, getUser().getName(), url);
1332 }
1333
1334 @Override
1335 public DataHandler getDataHandler() {
1336 return getDatabase();
1337 }
1338
1339 /**
1340 * Remember that the given LOB value must be removed at commit.
1341 *
1342 * @param v the value
1343 */
1344 public void removeAtCommit(ValueLob v) {
1345 if (v.isLinkedToTable()) {
1346 if (removeLobMap == null) {
1347 removeLobMap = new HashMap<>();
1348 }
1349 removeLobMap.put(v.toString(), v);
1350 }
1351 }
1352
1353 /**
1354 * Do not remove this LOB value at commit any longer.
1355 *
1356 * @param v the value
1357 */
1358 public void removeAtCommitStop(ValueLob v) {
1359 if (v.isLinkedToTable() && removeLobMap != null) {
1360 removeLobMap.remove(v.toString());
1361 }
1362 }
1363
1364 /**
1365 * Get the next system generated identifiers. The identifier returned does
1366 * not occur within the given SQL statement.
1367 *
1368 * @param sql the SQL statement
1369 * @return the new identifier
1370 */
1371 public String getNextSystemIdentifier(String sql) {
1372 String identifier;
1373 do {
1374 identifier = SYSTEM_IDENTIFIER_PREFIX + systemIdentifier++;
1375 } while (sql.contains(identifier));
1376 return identifier;
1377 }
1378
1379 /**
1380 * Add a procedure to this session.
1381 *
1382 * @param procedure the procedure to add
1383 */
1384 public void addProcedure(Procedure procedure) {
1385 if (procedures == null) {
1386 procedures = newStringsMap();
1387 }
1388 procedures.put(procedure.getName(), procedure);
1389 }
1390
1391 /**
1392 * Remove a procedure from this session.
1393 *
1394 * @param name the name of the procedure to remove
1395 */
1396 public void removeProcedure(String name) {
1397 if (procedures != null) {
1398 procedures.remove(name);
1399 }
1400 }
1401
1402 /**
1403 * Get the procedure with the given name, or null
1404 * if none exists.
1405 *
1406 * @param name the procedure name
1407 * @return the procedure or null
1408 */
1409 public Procedure getProcedure(String name) {
1410 if (procedures == null) {
1411 return null;
1412 }
1413 return procedures.get(name);
1414 }
1415
1416 public void setSchemaSearchPath(String[] schemas) {
1417 modificationId++;
1418 this.schemaSearchPath = schemas;
1419 }
1420
1421 public String[] getSchemaSearchPath() {
1422 return schemaSearchPath;
1423 }
1424
1425 @Override
1426 public int hashCode() {
1427 return serialId;
1428 }
1429
1430 @Override
1431 public String toString() {
1432 return "#" + serialId + " (user: " + (user == null ? "<null>" : user.getName()) + ", " + state.get() + ")";
1433 }
1434
1435 /**
1436 * Begin a transaction.
1437 */
1438 public void begin() {
1439 autoCommitAtTransactionEnd = true;
1440 autoCommit = false;
1441 }
1442
1443 public ValueTimestampTimeZone getSessionStart() {
1444 return sessionStart;
1445 }
1446
1447 public Set<Table> getLocks() {
1448 /*
1449 * This implementation needs to be lock-free.
1450 */
1451 if (getDatabase().getLockMode() == Constants.LOCK_MODE_OFF || locks.isEmpty()) {
1452 return Collections.emptySet();
1453 }
1454 /*
1455 * Do not use ArrayList.toArray(T[]) here, its implementation is not
1456 * thread-safe.
1457 */
1458 Object[] array = locks.toArray();
1459 /*
1460 * The returned array may contain null elements and may contain
1461 * duplicates due to concurrent remove().
1462 */
1463 switch (array.length) {
1464 case 1: {
1465 Object table = array[0];
1466 if (table != null) {
1467 return Collections.singleton((Table) table);
1468 }
1469 }
1470 //$FALL-THROUGH$
1471 case 0:
1472 return Collections.emptySet();
1473 default: {
1474 HashSet<Table> set = new HashSet<>();
1475 for (Object table : array) {
1476 if (table != null) {
1477 set.add((Table) table);
1478 }
1479 }
1480 return set;
1481 }
1482 }
1483 }
1484
1485 /**
1486 * Wait if the exclusive mode has been enabled for another session. This
1487 * method returns as soon as the exclusive mode has been disabled.
1488 */
1489 public void waitIfExclusiveModeEnabled() {
1490 transitionToState(State.RUNNING, true);
1491 // Even in exclusive mode, we have to let the LOB session proceed, or we
1492 // will get deadlocks.
1493 if (getDatabase().getLobSession() == this) {
1494 return;
1495 }
1496 while (isOpen()) {
1497 SessionLocal exclusive = getDatabase().getExclusiveSession();
1498 if (exclusive == null || exclusive == this) {
1499 break;
1500 }
1501 if (Thread.holdsLock(exclusive)) {
1502 // if another connection is used within the connection
1503 break;
1504 }
1505 try {
1506 Thread.sleep(100);
1507 } catch (InterruptedException e) {
1508 // ignore
1509 }
1510 }
1511 }
1512
1513 /**
1514 * Get the view cache for this session. There are two caches: the derived
1515 * table cache (which is only use for a single query, has no bounds, and is
1516 * cleared after use), and the cache for regular views.
1517 *
1518 * @param derivedTable
1519 * true to get the cache of derived tables
1520 * @return the view cache or derived table cache
1521 */
1522 public Map<Object, QueryExpressionIndex> getViewIndexCache(boolean derivedTable) {
1523 if (derivedTable) {
1524 // for derived tables we don't need to use LRU because the cache
1525 // should not grow too large for a single query (we drop the whole
1526 // cache in this cache is dropped at the end of prepareLocal)
1527 if (derivedTableIndexCache == null) {
1528 derivedTableIndexCache = new HashMap<>();
1529 }
1530 return derivedTableIndexCache;
1531 }
1532 SmallLRUCache<Object, QueryExpressionIndex> cache = viewIndexCache;
1533 if (cache == null) {
1534 viewIndexCache = cache = SmallLRUCache.newInstance(Constants.VIEW_INDEX_CACHE_SIZE);
1535 }
1536 return cache;
1537 }
1538
1539 public void setQueryTimeout(int queryTimeout) {
1540 int max = getDatabase().getSettings().maxQueryTimeout;
1541 if (max != 0 && (max < queryTimeout || queryTimeout == 0)) {
1542 // the value must be at most max
1543 queryTimeout = max;
1544 }
1545 this.queryTimeout = queryTimeout;
1546 // must reset the cancel at here,
1547 // otherwise it is still used
1548 cancelAtNs = 0L;
1549 }
1550
1551 public int getQueryTimeout() {
1552 return queryTimeout;
1553 }
1554
1555 /**
1556 * Set the table this session is waiting for, and the thread that is
1557 * waiting.
1558 *
1559 * @param waitForLock the table
1560 * @param waitForLockThread the current thread (the one that is waiting)
1561 */
1562 public void setWaitForLock(Table waitForLock, Thread waitForLockThread) {
1563 this.waitForLock = waitForLock;
1564 this.waitForLockThread = waitForLockThread;
1565 }
1566
1567 public Table getWaitForLock() {
1568 return waitForLock;
1569 }
1570
1571 public Thread getWaitForLockThread() {
1572 return waitForLockThread;
1573 }
1574
1575 public int getModificationId() {
1576 return modificationId;
1577 }
1578
1579 public Value getTransactionId() {
1580 if (transaction == null || !transaction.hasChanges()) {
1581 return ValueNull.INSTANCE;
1582 }
1583 return ValueVarchar.get(Long.toString(transaction.getSequenceNum()));
1584 }
1585
1586 /**
1587 * Get the next object id.
1588 *
1589 * @return the next object id
1590 */
1591 public int nextObjectId() {
1592 return objectId++;
1593 }
1594
1595 /**
1596 * Get the transaction to use for this session.
1597 *
1598 * @return the transaction
1599 */
1600 public Transaction getTransaction() {
1601 if (transaction == null) {
1602 Store store = getDatabase().getStore();
1603 if (store.getMvStore().isClosed()) {
1604 Throwable backgroundException = getDatabase().getBackgroundException();
1605 getDatabase().shutdownImmediately();
1606 throw DbException.get(ErrorCode.DATABASE_IS_CLOSED, backgroundException);
1607 }
1608 transaction = store.getTransactionStore().begin(this, this.lockTimeout, id, isolationLevel);
1609 startStatement = -1;
1610 }
1611 return transaction;
1612 }
1613
1614 private long getStatementSavepoint() {
1615 if (startStatement == -1) {
1616 startStatement = getTransaction().setSavepoint();
1617 }
1618 return startStatement;
1619 }
1620
1621 /**
1622 * Start a new statement within a transaction.
1623 * @param command about to be started
1624 */
1625 @SuppressWarnings("incomplete-switch")
1626 public void startStatementWithinTransaction(Command command) {
1627 Transaction transaction = getTransaction();
1628 if (transaction != null) {
1629 HashSet<MVMap<Object,VersionedValue<Object>>> maps = new HashSet<>();
1630 if (command != null) {
1631 Set<DbObject> dependencies = command.getDependencies();
1632 switch (transaction.getIsolationLevel()) {
1633 case SNAPSHOT:
1634 case SERIALIZABLE:
1635 if (!transaction.hasStatementDependencies()) {
1636 for (Schema schema : getDatabase().getAllSchemasNoMeta()) {
1637 for (Table table : schema.getAllTablesAndViews(null)) {
1638 if (table instanceof MVTable) {
1639 addTableToDependencies((MVTable)table, maps);
1640 }
1641 }
1642 }
1643 break;
1644 }
1645 //$FALL-THROUGH$
1646 case READ_COMMITTED:
1647 case READ_UNCOMMITTED:
1648 for (DbObject dependency : dependencies) {
1649 if (dependency instanceof MVTable) {
1650 addTableToDependencies((MVTable)dependency, maps);
1651 }
1652 }
1653 break;
1654 case REPEATABLE_READ:
1655 HashSet<MVTable> processed = new HashSet<>();
1656 for (DbObject dependency : dependencies) {
1657 if (dependency instanceof MVTable) {
1658 addTableToDependencies((MVTable)dependency, maps, processed);
1659 }
1660 }
1661 break;
1662 }
1663 }
1664 transaction.markStatementStart(maps);
1665 }
1666 startStatement = -1;
1667 if (command != null) {
1668 setCurrentCommand(command);
1669 }
1670 }
1671
1672 @SuppressWarnings({"unchecked", "rawtypes"})
1673 private static void addTableToDependencies(MVTable table, HashSet<MVMap<Object,VersionedValue<Object>>> maps) {
1674 for (Index index : table.getIndexes()) {
1675 if (index instanceof MVIndex) {
1676 maps.add(((MVIndex) index).getMVMap());
1677 }
1678 }
1679 }
1680
1681 private static void addTableToDependencies(MVTable table, HashSet<MVMap<Object,VersionedValue<Object>>> maps,
1682 HashSet<MVTable> processed) {
1683 if (!processed.add(table)) {
1684 return;
1685 }
1686 addTableToDependencies(table, maps);
1687 ArrayList<Constraint> constraints = table.getConstraints();
1688 if (constraints != null) {
1689 for (Constraint constraint : constraints) {
1690 Table ref = constraint.getTable();
1691 if (ref != table && ref instanceof MVTable) {
1692 addTableToDependencies((MVTable) ref, maps, processed);
1693 }
1694 }
1695 }
1696 }
1697
1698 /**
1699 * Mark the statement as completed. This also close all temporary result
1700 * set, and deletes all temporary files held by the result sets.
1701 */
1702 public void endStatement() {
1703 setCurrentCommand(null);
1704 if (hasTransaction()) {
1705 transaction.markStatementEnd();
1706 }
1707 startStatement = -1;
1708 }
1709
1710 /**
1711 * Clear the view cache for this session.
1712 */
1713 public void clearViewIndexCache() {
1714 viewIndexCache = null;
1715 }
1716
1717 @Override
1718 public ValueLob addTemporaryLob(ValueLob v) {
1719 LobData lobData = v.getLobData();
1720 if (lobData instanceof LobDataInMemory) {
1721 return v;
1722 }
1723 int tableId = ((LobDataDatabase) lobData).getTableId();
1724 if (tableId == LobStorageFrontend.TABLE_RESULT || tableId == LobStorageFrontend.TABLE_TEMP) {
1725 if (temporaryResultLobs == null) {
1726 temporaryResultLobs = new LinkedList<>();
1727 }
1728 temporaryResultLobs.add(new TimeoutValue(v));
1729 } else {
1730 if (temporaryLobs == null) {
1731 temporaryLobs = new ArrayList<>();
1732 }
1733 temporaryLobs.add(v);
1734 }
1735 return v;
1736 }
1737
1738 @Override
1739 public boolean isRemote() {
1740 return false;
1741 }
1742
1743 /**
1744 * Mark that the given table needs to be analyzed on commit.
1745 *
1746 * @param table the table
1747 */
1748 public void markTableForAnalyze(Table table) {
1749 if (tablesToAnalyze == null) {
1750 tablesToAnalyze = new HashSet<>();
1751 }
1752 tablesToAnalyze.add(table);
1753 }
1754
1755 public State getState() {
1756 return getBlockingSessionId() != 0 ? State.BLOCKED : state.get();
1757 }
1758
1759 public int getBlockingSessionId() {
1760 return transaction == null ? 0 : transaction.getBlockerId();
1761 }
1762
1763 @Override
1764 public void onRollback(MVMap<Object, VersionedValue<Object>> map, Object key,
1765 VersionedValue<Object> existingValue,
1766 VersionedValue<Object> restoredValue) {
1767 // Here we are relying on the fact that map which backs table's primary index
1768 // has the same name as the table itself
1769 Store store = getDatabase().getStore();
1770 MVTable table = store.getTable(map.getName());
1771 if (table != null) {
1772 Row oldRow = existingValue == null ? null : (Row) existingValue.getCurrentValue();
1773 Row newRow = restoredValue == null ? null : (Row) restoredValue.getCurrentValue();
1774 table.fireAfterRow(this, oldRow, newRow, true);
1775
1776 if (table.getContainsLargeObject()) {
1777 if (oldRow != null) {
1778 for (int i = 0, len = oldRow.getColumnCount(); i < len; i++) {
1779 Value v = oldRow.getValue(i);
1780 if (v instanceof ValueLob) {
1781 removeAtCommit((ValueLob) v);
1782 }
1783 }
1784 }
1785 if (newRow != null) {
1786 for (int i = 0, len = newRow.getColumnCount(); i < len; i++) {
1787 Value v = newRow.getValue(i);
1788 if (v instanceof ValueLob) {
1789 removeAtCommitStop((ValueLob) v);
1790 }
1791 }
1792 }
1793 }
1794 }
1795 }
1796
1797 /**
1798 * Represents a savepoint (a position in a transaction to where one can roll
1799 * back to).
1800 */
1801 public static class Savepoint {
1802
1803 /**
1804 * The undo log index.
1805 */
1806 int logIndex;
1807
1808 /**
1809 * The transaction savepoint id.
1810 */
1811 long transactionSavepoint;
1812 }
1813
1814 /**
1815 * An LOB object with a timeout.
1816 */
1817 public static class TimeoutValue {
1818
1819 /**
1820 * The time when this object was created.
1821 */
1822 final long created = System.nanoTime();
1823
1824 /**
1825 * The value.
1826 */
1827 final ValueLob value;
1828
1829 TimeoutValue(ValueLob v) {
1830 this.value = v;
1831 }
1832
1833 }
1834
1835 /**
1836 * Returns the network connection information, or {@code null}.
1837 *
1838 * @return the network connection information, or {@code null}
1839 */
1840 public NetworkConnectionInfo getNetworkConnectionInfo() {
1841 return networkConnectionInfo;
1842 }
1843
1844 @Override
1845 public void setNetworkConnectionInfo(NetworkConnectionInfo networkConnectionInfo) {
1846 this.networkConnectionInfo = networkConnectionInfo;
1847 }
1848
1849 @Override
1850 public ValueTimestampTimeZone currentTimestamp() {
1851 ValueTimestampTimeZone ts = currentTimestamp;
1852 if (ts == null) {
1853 currentTimestamp = ts = DateTimeUtils.currentTimestamp(timeZone, commandStartOrEnd);
1854 }
1855 return ts;
1856 }
1857
1858 @Override
1859 public Mode getMode() {
1860 return getDatabase().getMode();
1861 }
1862
1863 @Override
1864 public JavaObjectSerializer getJavaObjectSerializer() {
1865 return getDatabase().getJavaObjectSerializer();
1866 }
1867
1868 @Override
1869 public IsolationLevel getIsolationLevel() {
1870 return isolationLevel;
1871 }
1872
1873 @Override
1874 public void setIsolationLevel(IsolationLevel isolationLevel) {
1875 commit(false);
1876 this.isolationLevel = isolationLevel;
1877 }
1878
1879 /**
1880 * Gets bit set of non-keywords.
1881 *
1882 * @return set of non-keywords, or {@code null}
1883 */
1884 public BitSet getNonKeywords() {
1885 return nonKeywords;
1886 }
1887
1888 /**
1889 * Sets bit set of non-keywords.
1890 *
1891 * @param nonKeywords set of non-keywords, or {@code null}
1892 */
1893 public void setNonKeywords(BitSet nonKeywords) {
1894 this.nonKeywords = nonKeywords;
1895 }
1896
1897 @Override
1898 public StaticSettings getStaticSettings() {
1899 StaticSettings settings = staticSettings;
1900 if (settings == null) {
1901 DbSettings dbSettings = getDatabase().getSettings();
1902 staticSettings = settings = new StaticSettings(dbSettings.databaseToUpper, dbSettings.databaseToLower,
1903 dbSettings.caseInsensitiveIdentifiers);
1904 }
1905 return settings;
1906 }
1907
1908 @Override
1909 public DynamicSettings getDynamicSettings() {
1910 return new DynamicSettings(getMode(), timeZone);
1911 }
1912
1913 @Override
1914 public TimeZoneProvider currentTimeZone() {
1915 return timeZone;
1916 }
1917
1918 /**
1919 * Sets current time zone.
1920 *
1921 * @param timeZone time zone
1922 */
1923 public void setTimeZone(TimeZoneProvider timeZone) {
1924 if (!timeZone.equals(this.timeZone)) {
1925 this.timeZone = timeZone;
1926 ValueTimestampTimeZone ts = currentTimestamp;
1927 if (ts != null) {
1928 long dateValue = ts.getDateValue();
1929 long timeNanos = ts.getTimeNanos();
1930 int offsetSeconds = ts.getTimeZoneOffsetSeconds();
1931 currentTimestamp = DateTimeUtils.timestampTimeZoneAtOffset(dateValue, timeNanos, offsetSeconds, //
1932 timeZone.getTimeZoneOffsetUTC(
1933 DateTimeUtils.getEpochSeconds(dateValue, timeNanos, offsetSeconds)));
1934 }
1935 modificationId++;
1936 }
1937 }
1938
1939 /**
1940 * Check if two values are equal with the current comparison mode.
1941 *
1942 * @param a the first value
1943 * @param b the second value
1944 * @return true if both objects are equal
1945 */
1946 public boolean areEqual(Value a, Value b) {
1947 // can not use equals because ValueDecimal 0.0 is not equal to 0.00.
1948 return a.compareTo(b, this, getCompareMode()) == 0;
1949 }
1950
1951 /**
1952 * Compare two values with the current comparison mode. The values may have
1953 * different data types including NULL.
1954 *
1955 * @param a the first value
1956 * @param b the second value
1957 * @return 0 if both values are equal, -1 if the first value is smaller, and
1958 * 1 otherwise
1959 */
1960 public int compare(Value a, Value b) {
1961 return a.compareTo(b, this, getCompareMode());
1962 }
1963
1964 /**
1965 * Compare two values with the current comparison mode. The values may have
1966 * different data types including NULL.
1967 *
1968 * @param a the first value
1969 * @param b the second value
1970 * @param forEquality perform only check for equality (= or &lt;&gt;)
1971 * @return 0 if both values are equal, -1 if the first value is smaller, 1
1972 * if the second value is larger, {@link Integer#MIN_VALUE} if order
1973 * is not defined due to NULL comparison
1974 */
1975 public int compareWithNull(Value a, Value b, boolean forEquality) {
1976 return a.compareWithNull(b, forEquality, this, getCompareMode());
1977 }
1978
1979 /**
1980 * Compare two values with the current comparison mode. The values must be
1981 * of the same type.
1982 *
1983 * @param a the first value
1984 * @param b the second value
1985 * @return 0 if both values are equal, -1 if the first value is smaller, and
1986 * 1 otherwise
1987 */
1988 public int compareTypeSafe(Value a, Value b) {
1989 return a.compareTypeSafe(b, getCompareMode(), this);
1990 }
1991
1992 /**
1993 * Changes parsing mode of data types with too large length.
1994 *
1995 * @param truncateLargeLength
1996 * {@code true} to truncate to valid bound, {@code false} to
1997 * throw an exception
1998 */
1999 public void setTruncateLargeLength(boolean truncateLargeLength) {
2000 this.truncateLargeLength = truncateLargeLength;
2001 }
2002
2003 /**
2004 * Returns parsing mode of data types with too large length.
2005 *
2006 * @return {@code true} if large length is truncated, {@code false} if an
2007 * exception is thrown
2008 */
2009 public boolean isTruncateLargeLength() {
2010 return truncateLargeLength;
2011 }
2012
2013 /**
2014 * Changes parsing of a BINARY data type.
2015 *
2016 * @param variableBinary
2017 * {@code true} to parse BINARY as VARBINARY, {@code false} to
2018 * parse it as is
2019 */
2020 public void setVariableBinary(boolean variableBinary) {
2021 this.variableBinary = variableBinary;
2022 }
2023
2024 /**
2025 * Returns BINARY data type parsing mode.
2026 *
2027 * @return {@code true} if BINARY should be parsed as VARBINARY,
2028 * {@code false} if it should be parsed as is
2029 */
2030 public boolean isVariableBinary() {
2031 return variableBinary;
2032 }
2033
2034 /**
2035 * Changes INFORMATION_SCHEMA content.
2036 *
2037 * @param oldInformationSchema
2038 * {@code true} to have old-style tables in INFORMATION_SCHEMA,
2039 * {@code false} to have modern tables
2040 */
2041 public void setOldInformationSchema(boolean oldInformationSchema) {
2042 this.oldInformationSchema = oldInformationSchema;
2043 }
2044
2045 @Override
2046 public boolean isOldInformationSchema() {
2047 return oldInformationSchema;
2048 }
2049
2050 @Override
2051 public DatabaseMeta getDatabaseMeta() {
2052 return new DatabaseMetaLocal(this);
2053 }
2054
2055 @Override
2056 public boolean zeroBasedEnums() {
2057 return getDatabase().zeroBasedEnums();
2058 }
2059
2060 /**
2061 * Enables or disables the quirks mode.
2062 *
2063 * @param quirksMode
2064 * whether quirks mode should be enabled
2065 */
2066 public void setQuirksMode(boolean quirksMode) {
2067 this.quirksMode = quirksMode;
2068 }
2069
2070 /**
2071 * Returns whether quirks mode is enabled explicitly or implicitly.
2072 *
2073 * @return {@code true} if database is starting or quirks mode was enabled
2074 * explicitly, {@code false} otherwise
2075 */
2076 public boolean isQuirksMode() {
2077 return quirksMode || getDatabase().isStarting();
2078 }
2079
2080 @Override
2081 public Session setThreadLocalSession() {
2082 Session oldSession = THREAD_LOCAL_SESSION.get();
2083 THREAD_LOCAL_SESSION.set(this);
2084 return oldSession;
2085 }
2086
2087 @Override
2088 public void resetThreadLocalSession(Session oldSession) {
2089 if (oldSession == null) {
2090 THREAD_LOCAL_SESSION.remove();
2091 } else {
2092 THREAD_LOCAL_SESSION.set(oldSession);
2093 }
2094 }
2095
2096 private CompareMode getCompareMode() {
2097 return getDatabase().getCompareMode();
2098 }
2099
2100 private <T> HashMap<String,T> newStringsMap() {
2101 return getDatabase().newStringMap();
2102 }
2103 }