Debian Codegraph @

src/main/org/h2/table/Table.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.table;
7
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.Set;
13 import java.util.concurrent.CopyOnWriteArrayList;
14
15 import org.h2.api.ErrorCode;
16 import org.h2.command.Prepared;
17 import org.h2.command.query.AllColumnsForPlan;
18 import org.h2.constraint.Constraint;
19 import org.h2.constraint.Constraint.Type;
20 import org.h2.engine.CastDataProvider;
21 import org.h2.engine.Constants;
22 import org.h2.engine.DbObject;
23 import org.h2.engine.Right;
24 import org.h2.engine.SessionLocal;
25 import org.h2.expression.ExpressionVisitor;
26 import org.h2.index.Index;
27 import org.h2.index.IndexType;
28 import org.h2.message.DbException;
29 import org.h2.message.Trace;
30 import org.h2.result.DefaultRow;
31 import org.h2.result.LocalResult;
32 import org.h2.result.Row;
33 import org.h2.result.RowFactory;
34 import org.h2.result.SearchRow;
35 import org.h2.result.SimpleRowValue;
36 import org.h2.result.SortOrder;
37 import org.h2.schema.Schema;
38 import org.h2.schema.SchemaObject;
39 import org.h2.schema.Sequence;
40 import org.h2.schema.TriggerObject;
41 import org.h2.util.Utils;
42 import org.h2.value.CompareMode;
43 import org.h2.value.Value;
44 import org.h2.value.ValueNull;
45
46 /**
47 * This is the base class for most tables.
48 * A table contains a list of columns and a list of rows.
49 */
50 public abstract class Table extends SchemaObject {
51
52 /**
53 * The table type that means this table is a regular persistent table.
54 */
55 public static final int TYPE_CACHED = 0;
56
57 /**
58 * The table type that means this table is a regular persistent table.
59 */
60 public static final int TYPE_MEMORY = 1;
61
62 /**
63 * Read lock.
64 */
65 public static final int READ_LOCK = 0;
66
67 /**
68 * Write lock.
69 */
70 public static final int WRITE_LOCK = 1;
71
72 /**
73 * Exclusive lock.
74 */
75 public static final int EXCLUSIVE_LOCK = 2;
76
77 /**
78 * The columns of this table.
79 */
80 protected Column[] columns;
81
82 /**
83 * The compare mode used for this table.
84 */
85 protected CompareMode compareMode;
86
87 /**
88 * Protected tables are not listed in the meta data and are excluded when
89 * using the SCRIPT command.
90 */
91 protected boolean isHidden;
92
93 private final HashMap<String, Column> columnMap;
94 private final boolean persistIndexes;
95 private final boolean persistData;
96 private ArrayList<TriggerObject> triggers;
97 private ArrayList<Constraint> constraints;
98 private ArrayList<Sequence> sequences;
99 /**
100 * views that depend on this table
101 */
102 private final CopyOnWriteArrayList<TableView> dependentViews = new CopyOnWriteArrayList<>();
103 /**
104 * materialized views that depend on this table
105 */
106 private final CopyOnWriteArrayList<MaterializedView> dependentMaterializedViews = new CopyOnWriteArrayList<>();
107 private ArrayList<TableSynonym> synonyms;
108 /** Is foreign key constraint checking enabled for this table. */
109 private boolean checkForeignKeyConstraints = true;
110 private boolean onCommitDrop, onCommitTruncate;
111 private volatile Row nullRow;
112 private RowFactory rowFactory = RowFactory.getRowFactory();
113 private boolean tableExpression;
114
115 protected Table(Schema schema, int id, String name, boolean persistIndexes, boolean persistData) {
116 super(schema, id, name, Trace.TABLE);
117 columnMap = schema.getDatabase().newStringMap();
118 this.persistIndexes = persistIndexes;
119 this.persistData = persistData;
120 compareMode = schema.getDatabase().getCompareMode();
121 }
122
123 @Override
124 public void rename(String newName) {
125 super.rename(newName);
126 if (constraints != null) {
127 for (Constraint constraint : constraints) {
128 constraint.rebuild();
129 }
130 }
131 }
132
133 public boolean isView() {
134 return false;
135 }
136
137 /**
138 * Lock the table for the given session.
139 * This method waits until the lock is granted.
140 *
141 * @param session the session
142 * @param lockType the type of lock
143 * @return true if the table was already exclusively locked by this session.
144 * @throws DbException if a lock timeout occurred
145 */
146 public boolean lock(SessionLocal session, int lockType) {
147 return false;
148 }
149
150 /**
151 * Close the table object and flush changes.
152 *
153 * @param session the session
154 */
155 public abstract void close(SessionLocal session);
156
157 /**
158 * Release the lock for this session.
159 *
160 * @param s the session
161 */
162 public void unlock(SessionLocal s) {
163 }
164
165 /**
166 * Create an index for this table
167 *
168 * @param session the session
169 * @param indexName the name of the index
170 * @param indexId the id
171 * @param cols the index columns
172 * @param uniqueColumnCount the count of unique columns
173 * @param indexType the index type
174 * @param create whether this is a new index
175 * @param indexComment the comment
176 * @return the index
177 */
178 public abstract Index addIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols,
179 int uniqueColumnCount, IndexType indexType, boolean create, String indexComment);
180
181 /**
182 * Get the given row.
183 *
184 * @param session the session
185 * @param key the primary key
186 * @return the row
187 */
188 @SuppressWarnings("unused")
189 public Row getRow(SessionLocal session, long key) {
190 return null;
191 }
192
193 /**
194 * Returns whether this table is insertable.
195 *
196 * @return whether this table is insertable
197 */
198 public boolean isInsertable() {
199 return true;
200 }
201
202 /**
203 * Remove a row from the table and all indexes.
204 *
205 * @param session the session
206 * @param row the row
207 */
208 public abstract void removeRow(SessionLocal session, Row row);
209
210 /**
211 * Locks row, preventing any updated to it, except from the session specified.
212 *
213 * @param session the session
214 * @param row to lock
215 * @param timeoutMillis
216 * timeout in milliseconds, {@code -1} for default, {@code -2} to
217 * skip locking if row is already locked by another session
218 * @return locked row, or null if row does not exist anymore or if it was skipped
219 */
220 public Row lockRow(SessionLocal session, Row row, int timeoutMillis) {
221 throw DbException.getUnsupportedException("lockRow()");
222 }
223
224 /**
225 * Remove all rows from the table and indexes.
226 *
227 * @param session the session
228 * @return number of removed rows, possibly including uncommitted rows
229 */
230 public abstract long truncate(SessionLocal session);
231
232 /**
233 * Add a row to the table and all indexes.
234 *
235 * @param session the session
236 * @param row the row
237 * @throws DbException if a constraint was violated
238 */
239 public abstract void addRow(SessionLocal session, Row row);
240
241 /**
242 * Update a row to the table and all indexes.
243 *
244 * @param session the session
245 * @param oldRow the row to update
246 * @param newRow the row with updated values (_rowid_ suppose to be the same)
247 * @throws DbException if a constraint was violated
248 */
249 public void updateRow(SessionLocal session, Row oldRow, Row newRow) {
250 newRow.setKey(oldRow.getKey());
251 removeRow(session, oldRow);
252 addRow(session, newRow);
253 }
254
255 /**
256 * Check if this table supports ALTER TABLE.
257 *
258 * @throws DbException if it is not supported
259 */
260 public abstract void checkSupportAlter();
261
262 /**
263 * Get the table type name
264 *
265 * @return the table type name
266 */
267 public abstract TableType getTableType();
268
269 /**
270 * Return SQL table type for INFORMATION_SCHEMA.
271 *
272 * @return SQL table type for INFORMATION_SCHEMA
273 */
274 public String getSQLTableType() {
275 if (isView()) {
276 return "VIEW";
277 }
278 if (isTemporary()) {
279 return isGlobalTemporary() ? "GLOBAL TEMPORARY" : "LOCAL TEMPORARY";
280 }
281 return "BASE TABLE";
282 }
283
284 /**
285 * Get the scan index to iterate through all rows.
286 *
287 * @param session the session
288 * @return the index
289 */
290 public abstract Index getScanIndex(SessionLocal session);
291
292 /**
293 * Get the scan index for this table.
294 *
295 * @param session the session
296 * @param masks the search mask
297 * @param filters the table filters
298 * @param filter the filter index
299 * @param sortOrder the sort order
300 * @param allColumnsSet all columns
301 * @return the scan index
302 */
303 @SuppressWarnings("unused")
304 public Index getScanIndex(SessionLocal session, int[] masks,
305 TableFilter[] filters, int filter, SortOrder sortOrder,
306 AllColumnsForPlan allColumnsSet) {
307 return getScanIndex(session);
308 }
309
310 /**
311 * Get all indexes for this table.
312 *
313 * @return the list of indexes
314 */
315 public abstract ArrayList<Index> getIndexes();
316
317 /**
318 * Get an index by name.
319 *
320 * @param indexName the index name to search for
321 * @return the found index
322 */
323 public Index getIndex(String indexName) {
324 ArrayList<Index> indexes = getIndexes();
325 if (indexes != null) {
326 for (Index index : indexes) {
327 if (index.getName().equals(indexName)) {
328 return index;
329 }
330 }
331 }
332 throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1, indexName);
333 }
334
335 /**
336 * Check if this table is locked exclusively.
337 *
338 * @return true if it is.
339 */
340 public boolean isLockedExclusively() {
341 return false;
342 }
343
344 /**
345 * Get the last data modification id.
346 *
347 * @return the modification id
348 */
349 public abstract long getMaxDataModificationId();
350
351 /**
352 * Check if the table is deterministic.
353 *
354 * @return true if it is
355 */
356 public abstract boolean isDeterministic();
357
358 /**
359 * Check if the row count can be retrieved quickly.
360 *
361 * @param session the session
362 * @return true if it can
363 */
364 public abstract boolean canGetRowCount(SessionLocal session);
365
366 /**
367 * Check if this table can be referenced.
368 *
369 * @return true if it can
370 */
371 public boolean canReference() {
372 return true;
373 }
374
375 /**
376 * Check if this table can be dropped.
377 *
378 * @return true if it can
379 */
380 public abstract boolean canDrop();
381
382 /**
383 * Get the row count for this table.
384 *
385 * @param session the session
386 * @return the row count
387 */
388 public abstract long getRowCount(SessionLocal session);
389
390 /**
391 * Get the approximated row count for this table.
392 *
393 * @param session the session
394 * @return the approximated row count
395 */
396 public abstract long getRowCountApproximation(SessionLocal session);
397
398 public long getDiskSpaceUsed() {
399 return 0L;
400 }
401
402 /**
403 * Get the row id column if this table has one.
404 *
405 * @return the row id column, or null
406 */
407 public Column getRowIdColumn() {
408 return null;
409 }
410
411 /**
412 * Check whether the table (or view) contains no columns that prevent index
413 * conditions to be used. For example, a view that contains the ROWNUM()
414 * pseudo-column prevents this.
415 *
416 * @return true if the table contains no query-comparable column
417 */
418 public boolean isQueryComparable() {
419 return true;
420 }
421
422 /**
423 * Add all objects that this table depends on to the hash set.
424 *
425 * @param dependencies the current set of dependencies
426 */
427 public void addDependencies(HashSet<DbObject> dependencies) {
428 if (dependencies.contains(this)) {
429 // avoid endless recursion
430 return;
431 }
432 if (sequences != null) {
433 dependencies.addAll(sequences);
434 }
435 ExpressionVisitor visitor = ExpressionVisitor.getDependenciesVisitor(
436 dependencies);
437 for (Column col : columns) {
438 col.isEverything(visitor);
439 }
440 if (constraints != null) {
441 for (Constraint c : constraints) {
442 c.isEverything(visitor);
443 }
444 }
445 dependencies.add(this);
446 }
447
448 @Override
449 public ArrayList<DbObject> getChildren() {
450 ArrayList<DbObject> children = Utils.newSmallArrayList();
451 ArrayList<Index> indexes = getIndexes();
452 if (indexes != null) {
453 children.addAll(indexes);
454 }
455 if (constraints != null) {
456 children.addAll(constraints);
457 }
458 if (triggers != null) {
459 children.addAll(triggers);
460 }
461 if (sequences != null) {
462 children.addAll(sequences);
463 }
464 children.addAll(dependentViews);
465 if (synonyms != null) {
466 children.addAll(synonyms);
467 }
468 ArrayList<Right> rights = database.getAllRights();
469 for (Right right : rights) {
470 if (right.getGrantedObject() == this) {
471 children.add(right);
472 }
473 }
474 return children;
475 }
476
477 protected void setColumns(Column[] columns) {
478 if (columns.length > Constants.MAX_COLUMNS) {
479 throw DbException.get(ErrorCode.TOO_MANY_COLUMNS_1, "" + Constants.MAX_COLUMNS);
480 }
481 this.columns = columns;
482 if (columnMap.size() > 0) {
483 columnMap.clear();
484 }
485 for (int i = 0; i < columns.length; i++) {
486 Column col = columns[i];
487 int dataType = col.getType().getValueType();
488 if (dataType == Value.UNKNOWN) {
489 throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1, col.getTraceSQL());
490 }
491 col.setTable(this, i);
492 String columnName = col.getName();
493 if (columnMap.putIfAbsent(columnName, col) != null) {
494 throw DbException.get(ErrorCode.DUPLICATE_COLUMN_NAME_1, columnName);
495 }
496 }
497 rowFactory = database.getRowFactory().createRowFactory(database, database.getCompareMode(), database, columns,
498 null, false);
499 }
500
501 /**
502 * Rename a column of this table.
503 *
504 * @param column the column to rename
505 * @param newName the new column name
506 */
507 public void renameColumn(Column column, String newName) {
508 for (Column c : columns) {
509 if (c == column) {
510 continue;
511 }
512 if (c.getName().equals(newName)) {
513 throw DbException.get(
514 ErrorCode.DUPLICATE_COLUMN_NAME_1, newName);
515 }
516 }
517 columnMap.remove(column.getName());
518 column.rename(newName);
519 columnMap.put(newName, column);
520 }
521
522 /**
523 * Check if the table is exclusively locked by this session.
524 *
525 * @param session the session
526 * @return true if it is
527 */
528 @SuppressWarnings("unused")
529 public boolean isLockedExclusivelyBy(SessionLocal session) {
530 return false;
531 }
532
533 /**
534 * Update a list of rows in this table.
535 *
536 * @param prepared the prepared statement
537 * @param session the session
538 * @param rows a list of row pairs of the form old row, new row, old row,
539 * new row,...
540 */
541 public void updateRows(Prepared prepared, SessionLocal session, LocalResult rows) {
542 // in case we need to undo the update
543 SessionLocal.Savepoint rollback = session.setSavepoint();
544 // remove the old rows
545 int rowScanCount = 0;
546 while (rows.next()) {
547 if ((++rowScanCount & 127) == 0) {
548 prepared.checkCanceled();
549 }
550 Row o = rows.currentRowForTable();
551 rows.next();
552 try {
553 removeRow(session, o);
554 } catch (DbException e) {
555 if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1
556 || e.getErrorCode() == ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1) {
557 session.rollbackTo(rollback);
558 }
559 throw e;
560 }
561 }
562 // add the new rows
563 rows.reset();
564 while (rows.next()) {
565 if ((++rowScanCount & 127) == 0) {
566 prepared.checkCanceled();
567 }
568 rows.next();
569 Row n = rows.currentRowForTable();
570 try {
571 addRow(session, n);
572 } catch (DbException e) {
573 if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) {
574 session.rollbackTo(rollback);
575 }
576 throw e;
577 }
578 }
579 }
580
581 public CopyOnWriteArrayList<TableView> getDependentViews() {
582 return dependentViews;
583 }
584
585 public CopyOnWriteArrayList<MaterializedView> getDependentMaterializedViews() {
586 return dependentMaterializedViews;
587 }
588
589 @Override
590 public void removeChildrenAndResources(SessionLocal session) {
591 while (!dependentViews.isEmpty()) {
592 TableView view = dependentViews.remove(0);
593 database.removeSchemaObject(session, view);
594 }
595 while (synonyms != null && !synonyms.isEmpty()) {
596 TableSynonym synonym = synonyms.remove(0);
597 database.removeSchemaObject(session, synonym);
598 }
599 while (triggers != null && !triggers.isEmpty()) {
600 TriggerObject trigger = triggers.remove(0);
601 database.removeSchemaObject(session, trigger);
602 }
603 while (constraints != null && !constraints.isEmpty()) {
604 Constraint constraint = constraints.remove(0);
605 database.removeSchemaObject(session, constraint);
606 }
607 for (Right right : database.getAllRights()) {
608 if (right.getGrantedObject() == this) {
609 database.removeDatabaseObject(session, right);
610 }
611 }
612 database.removeMeta(session, getId());
613 // must delete sequences later (in case there is a power failure
614 // before removing the table object)
615 while (sequences != null && !sequences.isEmpty()) {
616 Sequence sequence = sequences.remove(0);
617 // only remove if no other table depends on this sequence
618 // this is possible when calling ALTER TABLE ALTER COLUMN
619 if (database.getDependentTable(sequence, this) == null) {
620 database.removeSchemaObject(session, sequence);
621 }
622 }
623 }
624
625 /**
626 * Check that these columns are not referenced by a multi-column constraint
627 * or multi-column index. If it is, an exception is thrown. Single-column
628 * references and indexes are dropped.
629 *
630 * @param session the session
631 * @param columnsToDrop the columns to drop
632 * @throws DbException if the column is referenced by multi-column
633 * constraints or indexes
634 */
635 public void dropMultipleColumnsConstraintsAndIndexes(SessionLocal session,
636 ArrayList<Column> columnsToDrop) {
637 HashSet<Constraint> constraintsToDrop = new HashSet<>();
638 if (constraints != null) {
639 for (Column col : columnsToDrop) {
640 for (Constraint constraint : constraints) {
641 HashSet<Column> columns = constraint.getReferencedColumns(this);
642 if (!columns.contains(col)) {
643 continue;
644 }
645 if (columns.size() == 1) {
646 constraintsToDrop.add(constraint);
647 } else {
648 throw DbException.get(ErrorCode.COLUMN_IS_REFERENCED_1, constraint.getTraceSQL());
649 }
650 }
651 }
652 }
653 HashSet<Index> indexesToDrop = new HashSet<>();
654 ArrayList<Index> indexes = getIndexes();
655 if (indexes != null) {
656 for (Column col : columnsToDrop) {
657 for (Index index : indexes) {
658 if (index.getCreateSQL() == null) {
659 continue;
660 }
661 if (index.getColumnIndex(col) < 0) {
662 continue;
663 }
664 if (index.getColumns().length == 1) {
665 indexesToDrop.add(index);
666 } else {
667 throw DbException.get(ErrorCode.COLUMN_IS_REFERENCED_1, index.getTraceSQL());
668 }
669 }
670 }
671 }
672 for (Constraint c : constraintsToDrop) {
673 if (c.isValid()) {
674 session.getDatabase().removeSchemaObject(session, c);
675 }
676 }
677 for (Index i : indexesToDrop) {
678 // the index may already have been dropped when dropping the
679 // constraint
680 if (getIndexes().contains(i)) {
681 session.getDatabase().removeSchemaObject(session, i);
682 }
683 }
684 }
685
686 public RowFactory getRowFactory() {
687 return rowFactory;
688 }
689
690 /**
691 * Create a new row for this table.
692 *
693 * @param data the values
694 * @param memory the estimated memory usage in bytes
695 * @return the created row
696 */
697 public Row createRow(Value[] data, int memory) {
698 return rowFactory.createRow(data, memory);
699 }
700
701 public Row getTemplateRow() {
702 return createRow(new Value[getColumns().length], DefaultRow.MEMORY_CALCULATE);
703 }
704
705 /**
706 * Get a new simple row object.
707 *
708 * @param singleColumn if only one value need to be stored
709 * @return the simple row object
710 */
711 public SearchRow getTemplateSimpleRow(boolean singleColumn) {
712 if (singleColumn) {
713 return new SimpleRowValue(columns.length);
714 }
715 return new DefaultRow(new Value[columns.length]);
716 }
717
718 public Row getNullRow() {
719 Row row = nullRow;
720 if (row == null) {
721 // Here can be concurrently produced more than one row, but it must
722 // be ok.
723 Value[] values = new Value[columns.length];
724 Arrays.fill(values, ValueNull.INSTANCE);
725 nullRow = row = createRow(values, 1);
726 }
727 return row;
728 }
729
730 public Column[] getColumns() {
731 return columns;
732 }
733
734 @Override
735 public int getType() {
736 return DbObject.TABLE_OR_VIEW;
737 }
738
739 /**
740 * Get the column at the given index.
741 *
742 * @param index the column index (0, 1,...)
743 * @return the column
744 */
745 public Column getColumn(int index) {
746 return columns[index];
747 }
748
749 /**
750 * Get the column with the given name.
751 *
752 * @param columnName the column name
753 * @return the column
754 * @throws DbException if the column was not found
755 */
756 public Column getColumn(String columnName) {
757 Column column = columnMap.get(columnName);
758 if (column == null) {
759 throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, columnName);
760 }
761 return column;
762 }
763
764 /**
765 * Get the column with the given name.
766 *
767 * @param columnName the column name
768 * @param ifExists if {@code true} return {@code null} if column does not exist
769 * @return the column
770 * @throws DbException if the column was not found
771 */
772 public Column getColumn(String columnName, boolean ifExists) {
773 Column column = columnMap.get(columnName);
774 if (column == null && !ifExists) {
775 throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, columnName);
776 }
777 return column;
778 }
779
780 /**
781 * Get the column with the given name if it exists.
782 *
783 * @param columnName the column name, or {@code null}
784 * @return the column
785 */
786 public Column findColumn(String columnName) {
787 return columnMap.get(columnName);
788 }
789
790 /**
791 * Does the column with the given name exist?
792 *
793 * @param columnName the column name
794 * @return true if the column exists
795 */
796 public boolean doesColumnExist(String columnName) {
797 return columnMap.containsKey(columnName);
798 }
799
800 /**
801 * Returns first identity column, or {@code null}.
802 *
803 * @return first identity column, or {@code null}
804 */
805 public Column getIdentityColumn() {
806 for (Column column : columns) {
807 if (column.isIdentity()) {
808 return column;
809 }
810 }
811 return null;
812 }
813
814 /**
815 * Get the best plan for the given search mask.
816 *
817 * @param session the session
818 * @param masks per-column comparison bit masks, null means 'always false',
819 * see constants in IndexCondition
820 * @param filters all joined table filters
821 * @param filter the current table filter index
822 * @param sortOrder the sort order
823 * @param allColumnsSet the set of all columns
824 * @return the plan item
825 */
826 public PlanItem getBestPlanItem(SessionLocal session, int[] masks,
827 TableFilter[] filters, int filter, SortOrder sortOrder,
828 AllColumnsForPlan allColumnsSet) {
829 PlanItem item = new PlanItem();
830 item.setIndex(getScanIndex(session));
831 item.cost = item.getIndex().getCost(session, null, filters, filter, null, allColumnsSet);
832 Trace t = session.getTrace();
833 if (t.isDebugEnabled()) {
834 t.debug("Table : potential plan item cost {0} index {1}",
835 item.cost, item.getIndex().getPlanSQL());
836 }
837 ArrayList<Index> indexes = getIndexes();
838 IndexHints indexHints = getIndexHints(filters, filter);
839
840 if (indexes != null && masks != null) {
841 for (int i = 1, size = indexes.size(); i < size; i++) {
842 Index index = indexes.get(i);
843
844 if (isIndexExcludedByHints(indexHints, index)) {
845 continue;
846 }
847
848 double cost = index.getCost(session, masks, filters, filter,
849 sortOrder, allColumnsSet);
850 if (t.isDebugEnabled()) {
851 t.debug("Table : potential plan item cost {0} index {1}",
852 cost, index.getPlanSQL());
853 }
854 if (cost < item.cost) {
855 item.cost = cost;
856 item.setIndex(index);
857 }
858 }
859 }
860 return item;
861 }
862
863 private static boolean isIndexExcludedByHints(IndexHints indexHints, Index index) {
864 return indexHints != null && !indexHints.allowIndex(index);
865 }
866
867 private static IndexHints getIndexHints(TableFilter[] filters, int filter) {
868 return filters == null ? null : filters[filter].getIndexHints();
869 }
870
871 /**
872 * Get the primary key index if there is one, or null if there is none.
873 *
874 * @return the primary key index or null
875 */
876 public Index findPrimaryKey() {
877 ArrayList<Index> indexes = getIndexes();
878 if (indexes != null) {
879 for (Index idx : indexes) {
880 if (idx.getIndexType().isPrimaryKey()) {
881 return idx;
882 }
883 }
884 }
885 return null;
886 }
887
888 public Index getPrimaryKey() {
889 Index index = findPrimaryKey();
890 if (index != null) {
891 return index;
892 }
893 throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1,
894 Constants.PREFIX_PRIMARY_KEY);
895 }
896
897 /**
898 * Prepares the specified row for INSERT operation.
899 *
900 * Identity, default, and generated values are evaluated, all values are
901 * converted to target data types and validated. Base value of identity
902 * column is updated when required by compatibility mode.
903 *
904 * @param session the session
905 * @param overridingSystem
906 * {@link Boolean#TRUE} for {@code OVERRIDING SYSTEM VALUES},
907 * {@link Boolean#FALSE} for {@code OVERRIDING USER VALUES},
908 * {@code null} if override clause is not specified
909 * @param row the row
910 */
911 public void convertInsertRow(SessionLocal session, Row row, Boolean overridingSystem) {
912 int length = columns.length, generated = 0;
913 for (int i = 0; i < length; i++) {
914 Value value = row.getValue(i);
915 Column column = columns[i];
916 if (value == ValueNull.INSTANCE && column.isDefaultOnNull()) {
917 value = null;
918 }
919 if (column.isIdentity()) {
920 if (overridingSystem != null) {
921 if (!overridingSystem) {
922 value = null;
923 }
924 } else if (value != null && column.isGeneratedAlways()) {
925 throw DbException.get(ErrorCode.GENERATED_COLUMN_CANNOT_BE_ASSIGNED_1,
926 column.getSQLWithTable(new StringBuilder(), TRACE_SQL_FLAGS).toString());
927 }
928 } else if (column.isGeneratedAlways()) {
929 if (value != null) {
930 throw DbException.get(ErrorCode.GENERATED_COLUMN_CANNOT_BE_ASSIGNED_1,
931 column.getSQLWithTable(new StringBuilder(), TRACE_SQL_FLAGS).toString());
932 }
933 generated++;
934 continue;
935 }
936 Value v2 = column.validateConvertUpdateSequence(session, value, row);
937 if (v2 != value) {
938 row.setValue(i, v2);
939 }
940 }
941 if (generated > 0) {
942 for (int i = 0; i < length; i++) {
943 Value value = row.getValue(i);
944 if (value == null) {
945 row.setValue(i, columns[i].validateConvertUpdateSequence(session, null, row));
946 }
947 }
948 }
949 }
950
951 /**
952 * Prepares the specified row for UPDATE operation.
953 *
954 * Default and generated values are evaluated, all values are converted to
955 * target data types and validated. Base value of identity column is updated
956 * when required by compatibility mode.
957 *
958 * @param session the session
959 * @param row the row
960 * @param fromTrigger {@code true} if row was modified by INSERT or UPDATE trigger
961 */
962 public void convertUpdateRow(SessionLocal session, Row row, boolean fromTrigger) {
963 int length = columns.length, generated = 0;
964 for (int i = 0; i < length; i++) {
965 Value value = row.getValue(i);
966 Column column = columns[i];
967 if (column.isGenerated()) {
968 if (value != null) {
969 if (!fromTrigger) {
970 throw DbException.get(ErrorCode.GENERATED_COLUMN_CANNOT_BE_ASSIGNED_1,
971 column.getSQLWithTable(new StringBuilder(), TRACE_SQL_FLAGS).toString());
972 }
973 row.setValue(i, null);
974 }
975 generated++;
976 continue;
977 }
978 Value v2 = column.validateConvertUpdateSequence(session, value, row);
979 if (v2 != value) {
980 row.setValue(i, v2);
981 }
982 }
983 if (generated > 0) {
984 for (int i = 0; i < length; i++) {
985 Value value = row.getValue(i);
986 if (value == null) {
987 row.setValue(i, columns[i].validateConvertUpdateSequence(session, null, row));
988 }
989 }
990 }
991 }
992
993 private static void remove(ArrayList<? extends DbObject> list, DbObject obj) {
994 if (list != null) {
995 list.remove(obj);
996 }
997 }
998
999 /**
1000 * Remove the given index from the list.
1001 *
1002 * @param index the index to remove
1003 */
1004 public void removeIndex(Index index) {
1005 ArrayList<Index> indexes = getIndexes();
1006 if (indexes != null) {
1007 remove(indexes, index);
1008 if (index.getIndexType().isPrimaryKey()) {
1009 for (Column col : index.getColumns()) {
1010 col.setPrimaryKey(false);
1011 }
1012 }
1013 }
1014 }
1015
1016 /**
1017 * Remove the given view from the dependent views list.
1018 *
1019 * @param view the view to remove
1020 */
1021 public void removeDependentView(TableView view) {
1022 dependentViews.remove(view);
1023 }
1024
1025 /**
1026 * Remove the given view from the dependent views list.
1027 *
1028 * @param view the view to remove
1029 */
1030 public void removeDependentMaterializedView(MaterializedView view) {
1031 dependentMaterializedViews.remove(view);
1032 }
1033
1034 /**
1035 * Remove the given view from the list.
1036 *
1037 * @param synonym the synonym to remove
1038 */
1039 public void removeSynonym(TableSynonym synonym) {
1040 remove(synonyms, synonym);
1041 }
1042
1043 /**
1044 * Remove the given constraint from the list.
1045 *
1046 * @param constraint the constraint to remove
1047 */
1048 public void removeConstraint(Constraint constraint) {
1049 remove(constraints, constraint);
1050 }
1051
1052 /**
1053 * Remove a sequence from the table. Sequences are used as identity columns.
1054 *
1055 * @param sequence the sequence to remove
1056 */
1057 public final void removeSequence(Sequence sequence) {
1058 remove(sequences, sequence);
1059 }
1060
1061 /**
1062 * Remove the given trigger from the list.
1063 *
1064 * @param trigger the trigger to remove
1065 */
1066 public void removeTrigger(TriggerObject trigger) {
1067 remove(triggers, trigger);
1068 }
1069
1070 /**
1071 * Add a view to this table.
1072 *
1073 * @param view the view to add
1074 */
1075 public void addDependentView(TableView view) {
1076 dependentViews.add(view);
1077 }
1078
1079 /**
1080 * Add a materialized view to this table.
1081 *
1082 * @param view the view to add
1083 */
1084 public void addDependentMaterializedView(MaterializedView view) {
1085 this.dependentMaterializedViews.add(view);
1086 }
1087
1088 /**
1089 * Add a synonym to this table.
1090 *
1091 * @param synonym the synonym to add
1092 */
1093 public void addSynonym(TableSynonym synonym) {
1094 synonyms = add(synonyms, synonym);
1095 }
1096
1097 /**
1098 * Add a constraint to the table.
1099 *
1100 * @param constraint the constraint to add
1101 */
1102 public void addConstraint(Constraint constraint) {
1103 if (constraints == null || !constraints.contains(constraint)) {
1104 constraints = add(constraints, constraint);
1105 }
1106 }
1107
1108 public ArrayList<Constraint> getConstraints() {
1109 return constraints;
1110 }
1111
1112 /**
1113 * Add a sequence to this table.
1114 *
1115 * @param sequence the sequence to add
1116 */
1117 public void addSequence(Sequence sequence) {
1118 sequences = add(sequences, sequence);
1119 }
1120
1121 /**
1122 * Add a trigger to this table.
1123 *
1124 * @param trigger the trigger to add
1125 */
1126 public void addTrigger(TriggerObject trigger) {
1127 triggers = add(triggers, trigger);
1128 }
1129
1130 private static <T> ArrayList<T> add(ArrayList<T> list, T obj) {
1131 if (list == null) {
1132 list = Utils.newSmallArrayList();
1133 }
1134 // self constraints are two entries in the list
1135 list.add(obj);
1136 return list;
1137 }
1138
1139 /**
1140 * Fire the triggers for this table.
1141 *
1142 * @param session the session
1143 * @param type the trigger type
1144 * @param beforeAction whether 'before' triggers should be called
1145 */
1146 public void fire(SessionLocal session, int type, boolean beforeAction) {
1147 if (triggers != null) {
1148 for (TriggerObject trigger : triggers) {
1149 trigger.fire(session, type, beforeAction);
1150 }
1151 }
1152 }
1153
1154 /**
1155 * Check whether this table has a select trigger.
1156 *
1157 * @return true if it has
1158 */
1159 public boolean hasSelectTrigger() {
1160 if (triggers != null) {
1161 for (TriggerObject trigger : triggers) {
1162 if (trigger.isSelectTrigger()) {
1163 return true;
1164 }
1165 }
1166 }
1167 return false;
1168 }
1169
1170 /**
1171 * Check if row based triggers or constraints are defined.
1172 * In this case the fire after and before row methods need to be called.
1173 *
1174 * @return if there are any triggers or rows defined
1175 */
1176 public boolean fireRow() {
1177 return (constraints != null && !constraints.isEmpty()) ||
1178 (triggers != null && !triggers.isEmpty());
1179 }
1180
1181 /**
1182 * Fire all triggers that need to be called before a row is updated.
1183 *
1184 * @param session the session
1185 * @param oldRow the old data or null for an insert
1186 * @param newRow the new data or null for a delete
1187 * @return true if no further action is required (for 'instead of' triggers)
1188 */
1189 public boolean fireBeforeRow(SessionLocal session, Row oldRow, Row newRow) {
1190 boolean done = fireRow(session, oldRow, newRow, true, false);
1191 fireConstraints(session, oldRow, newRow, true);
1192 return done;
1193 }
1194
1195 private void fireConstraints(SessionLocal session, Row oldRow, Row newRow,
1196 boolean before) {
1197 if (constraints != null) {
1198 for (Constraint constraint : constraints) {
1199 if (constraint.isBefore() == before) {
1200 constraint.checkRow(session, this, oldRow, newRow);
1201 }
1202 }
1203 }
1204 }
1205
1206 /**
1207 * Fire all triggers that need to be called after a row is updated.
1208 *
1209 * @param session the session
1210 * @param oldRow the old data or null for an insert
1211 * @param newRow the new data or null for a delete
1212 * @param rollback when the operation occurred within a rollback
1213 */
1214 public void fireAfterRow(SessionLocal session, Row oldRow, Row newRow,
1215 boolean rollback) {
1216 fireRow(session, oldRow, newRow, false, rollback);
1217 if (!rollback) {
1218 fireConstraints(session, oldRow, newRow, false);
1219 }
1220 }
1221
1222 private boolean fireRow(SessionLocal session, Row oldRow, Row newRow,
1223 boolean beforeAction, boolean rollback) {
1224 if (triggers != null) {
1225 for (TriggerObject trigger : triggers) {
1226 boolean done = trigger.fireRow(session, this, oldRow, newRow, beforeAction, rollback);
1227 if (done) {
1228 return true;
1229 }
1230 }
1231 }
1232 return false;
1233 }
1234
1235 public boolean isGlobalTemporary() {
1236 return false;
1237 }
1238
1239 /**
1240 * Check if this table can be truncated.
1241 *
1242 * @return true if it can
1243 */
1244 public boolean canTruncate() {
1245 return false;
1246 }
1247
1248 /**
1249 * Enable or disable foreign key constraint checking for this table.
1250 *
1251 * @param session the session
1252 * @param enabled true if checking should be enabled
1253 * @param checkExisting true if existing rows must be checked during this
1254 * call
1255 */
1256 public void setCheckForeignKeyConstraints(SessionLocal session, boolean enabled, boolean checkExisting) {
1257 if (enabled && checkExisting) {
1258 if (constraints != null) {
1259 for (Constraint c : constraints) {
1260 if (c.getConstraintType() == Type.REFERENTIAL) {
1261 c.checkExistingData(session);
1262 }
1263 }
1264 }
1265 }
1266 checkForeignKeyConstraints = enabled;
1267 }
1268
1269 /**
1270 * @return is foreign key constraint checking enabled for this table.
1271 */
1272 public boolean getCheckForeignKeyConstraints() {
1273 return checkForeignKeyConstraints;
1274 }
1275
1276 /**
1277 * Get the index that has the given column as the first element.
1278 * This method returns null if no matching index is found.
1279 *
1280 * @param column the column
1281 * @param needGetFirstOrLast if the returned index must be able
1282 * to do {@link Index#canGetFirstOrLast()}
1283 * @param needFindNext if the returned index must be able to do
1284 * {@link Index#findNext(SessionLocal, SearchRow, SearchRow)}
1285 * @return the index or null
1286 */
1287 public Index getIndexForColumn(Column column,
1288 boolean needGetFirstOrLast, boolean needFindNext) {
1289 ArrayList<Index> indexes = getIndexes();
1290 Index result = null;
1291 if (indexes != null) {
1292 for (int i = 1, size = indexes.size(); i < size; i++) {
1293 Index index = indexes.get(i);
1294 if (needGetFirstOrLast && !index.canGetFirstOrLast()) {
1295 continue;
1296 }
1297 if (needFindNext && !index.canFindNext()) {
1298 continue;
1299 }
1300 // choose the minimal covering index with the needed first
1301 // column to work consistently with execution plan from
1302 // Optimizer
1303 if (index.isFirstColumn(column) && (result == null ||
1304 result.getColumns().length > index.getColumns().length)) {
1305 result = index;
1306 }
1307 }
1308 }
1309 return result;
1310 }
1311
1312 public boolean getOnCommitDrop() {
1313 return onCommitDrop;
1314 }
1315
1316 public void setOnCommitDrop(boolean onCommitDrop) {
1317 this.onCommitDrop = onCommitDrop;
1318 }
1319
1320 public boolean getOnCommitTruncate() {
1321 return onCommitTruncate;
1322 }
1323
1324 public void setOnCommitTruncate(boolean onCommitTruncate) {
1325 this.onCommitTruncate = onCommitTruncate;
1326 }
1327
1328 /**
1329 * If the index is still required by a constraint, transfer the ownership to
1330 * it. Otherwise, the index is removed.
1331 *
1332 * @param session the session
1333 * @param index the index that is no longer required
1334 */
1335 public void removeIndexOrTransferOwnership(SessionLocal session, Index index) {
1336 boolean stillNeeded = false;
1337 if (constraints != null) {
1338 for (Constraint cons : constraints) {
1339 if (cons.usesIndex(index)) {
1340 cons.setIndexOwner(index);
1341 database.updateMeta(session, cons);
1342 stillNeeded = true;
1343 }
1344 }
1345 }
1346 if (!stillNeeded) {
1347 database.removeSchemaObject(session, index);
1348 }
1349 }
1350
1351 /**
1352 * Removes dependencies of column expressions, used for tables with circular
1353 * dependencies.
1354 *
1355 * @param session the session
1356 */
1357 public void removeColumnExpressionsDependencies(SessionLocal session) {
1358 for (Column column : columns) {
1359 column.setDefaultExpression(session, null);
1360 column.setOnUpdateExpression(session, null);
1361 }
1362 }
1363
1364 /**
1365 * Check if a deadlock occurred. This method is called recursively. There is
1366 * a circle if the session to be tested has already being visited. If this
1367 * session is part of the circle (if it is the clash session), the method
1368 * must return an empty object array. Once a deadlock has been detected, the
1369 * methods must add the session to the list. If this session is not part of
1370 * the circle, or if no deadlock is detected, this method returns null.
1371 *
1372 * @param session the session to be tested for
1373 * @param clash set with sessions already visited, and null when starting
1374 * verification
1375 * @param visited set with sessions already visited, and null when starting
1376 * verification
1377 * @return an object array with the sessions involved in the deadlock, or
1378 * null
1379 */
1380 @SuppressWarnings("unused")
1381 public ArrayList<SessionLocal> checkDeadlock(SessionLocal session, SessionLocal clash,
1382 Set<SessionLocal> visited) {
1383 return null;
1384 }
1385
1386 public boolean isPersistIndexes() {
1387 return persistIndexes;
1388 }
1389
1390 public boolean isPersistData() {
1391 return persistData;
1392 }
1393
1394 /**
1395 * Compare two values with the current comparison mode. The values may be of
1396 * different type.
1397 *
1398 * @param provider the cast information provider
1399 * @param a the first value
1400 * @param b the second value
1401 * @return 0 if both values are equal, -1 if the first value is smaller, and
1402 * 1 otherwise
1403 */
1404 public int compareValues(CastDataProvider provider, Value a, Value b) {
1405 return a.compareTo(b, provider, compareMode);
1406 }
1407
1408 public CompareMode getCompareMode() {
1409 return compareMode;
1410 }
1411
1412 /**
1413 * Tests if the table can be written. Usually, this depends on the
1414 * database.checkWritingAllowed method, but some tables (eg. TableLink)
1415 * overwrite this default behaviour.
1416 */
1417 public void checkWritingAllowed() {
1418 database.checkWritingAllowed();
1419 }
1420
1421 @Override
1422 public boolean isHidden() {
1423 return isHidden;
1424 }
1425
1426 public void setHidden(boolean hidden) {
1427 this.isHidden = hidden;
1428 }
1429
1430 /**
1431 * Views, function tables, links, etc. do not support locks
1432 * @return true if table supports row-level locks
1433 */
1434 public boolean isRowLockable() {
1435 return false;
1436 }
1437
1438 public void setTableExpression(boolean tableExpression) {
1439 this.tableExpression = tableExpression;
1440 }
1441
1442 public boolean isTableExpression() {
1443 return tableExpression;
1444 }
1445
1446 /**
1447 * Return list of triggers.
1448 *
1449 * @return list of triggers
1450 */
1451 public ArrayList<TriggerObject> getTriggers() {
1452 return triggers;
1453 }
1454
1455 /**
1456 * Returns ID of main index column, or {@link SearchRow#ROWID_INDEX}.
1457 *
1458 * @return ID of main index column, or {@link SearchRow#ROWID_INDEX}
1459 */
1460 public int getMainIndexColumn() {
1461 return SearchRow.ROWID_INDEX;
1462 }
1463
1464 }