Debian Codegraph @

src/main/org/h2/index/Index.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.index;
7
8 import java.util.ArrayList;
9 import java.util.Arrays;
10
11 import org.h2.api.ErrorCode;
12 import org.h2.command.query.AllColumnsForPlan;
13 import org.h2.engine.Constants;
14 import org.h2.engine.DbObject;
15 import org.h2.engine.NullsDistinct;
16 import org.h2.engine.SessionLocal;
17 import org.h2.message.DbException;
18 import org.h2.message.Trace;
19 import org.h2.result.Row;
20 import org.h2.result.RowFactory;
21 import org.h2.result.SearchRow;
22 import org.h2.result.SortOrder;
23 import org.h2.schema.SchemaObject;
24 import org.h2.table.Column;
25 import org.h2.table.IndexColumn;
26 import org.h2.table.Table;
27 import org.h2.table.TableFilter;
28 import org.h2.util.StringUtils;
29 import org.h2.value.CompareMode;
30 import org.h2.value.DataType;
31 import org.h2.value.Value;
32 import org.h2.value.ValueNull;
33
34 /**
35 * An index. Indexes are used to speed up searching data.
36 */
37 public abstract class Index extends SchemaObject {
38
39 /**
40 * Check that the index columns are not CLOB or BLOB.
41 *
42 * @param columns the columns
43 */
44 protected static void checkIndexColumnTypes(IndexColumn[] columns) {
45 for (IndexColumn c : columns) {
46 if (!DataType.isIndexable(c.column.getType())) {
47 throw DbException.getUnsupportedException("Index on column: " + c.column.getCreateSQL());
48 }
49 }
50 }
51
52 /**
53 * Columns of this index.
54 */
55 protected IndexColumn[] indexColumns;
56
57 /**
58 * Table columns used in this index.
59 */
60 protected Column[] columns;
61
62 /**
63 * Identities of table columns.
64 */
65 protected int[] columnIds;
66
67 /**
68 * Count of unique columns. Unique columns, if any, are always first columns
69 * in the lists.
70 */
71 protected final int uniqueColumnColumn;
72
73 /**
74 * The table.
75 */
76 protected final Table table;
77
78 /**
79 * The index type.
80 */
81 protected final IndexType indexType;
82
83 private final RowFactory rowFactory;
84
85 private final RowFactory uniqueRowFactory;
86
87 /**
88 * Initialize the index.
89 *
90 * @param newTable the table
91 * @param id the object id
92 * @param name the index name
93 * @param newIndexColumns the columns that are indexed or null if this is
94 * not yet known
95 * @param uniqueColumnCount count of unique columns
96 * @param newIndexType the index type
97 */
98 protected Index(Table newTable, int id, String name, IndexColumn[] newIndexColumns, int uniqueColumnCount,
99 IndexType newIndexType) {
100 super(newTable.getSchema(), id, name, Trace.INDEX);
101 this.uniqueColumnColumn = uniqueColumnCount;
102 this.indexType = newIndexType;
103 this.table = newTable;
104 if (newIndexColumns != null) {
105 this.indexColumns = newIndexColumns;
106 columns = new Column[newIndexColumns.length];
107 int len = columns.length;
108 columnIds = new int[len];
109 for (int i = 0; i < len; i++) {
110 Column col = newIndexColumns[i].column;
111 columns[i] = col;
112 columnIds[i] = col.getColumnId();
113 }
114 }
115 RowFactory databaseRowFactory = database.getRowFactory();
116 CompareMode compareMode = database.getCompareMode();
117 Column[] tableColumns = table.getColumns();
118 rowFactory = databaseRowFactory.createRowFactory(database, compareMode, database, tableColumns,
119 newIndexType.isScan() ? null : newIndexColumns, true);
120 RowFactory uniqueRowFactory;
121 if (uniqueColumnCount > 0) {
122 if (newIndexColumns == null || uniqueColumnCount == newIndexColumns.length) {
123 uniqueRowFactory = rowFactory;
124 } else {
125 uniqueRowFactory = databaseRowFactory.createRowFactory(database, compareMode, database, tableColumns,
126 Arrays.copyOf(newIndexColumns, uniqueColumnCount), true);
127 }
128 } else {
129 uniqueRowFactory = null;
130 }
131 this.uniqueRowFactory = uniqueRowFactory;
132 }
133
134 @Override
135 public final int getType() {
136 return DbObject.INDEX;
137 }
138
139 @Override
140 public void removeChildrenAndResources(SessionLocal session) {
141 table.removeIndex(this);
142 remove(session);
143 database.removeMeta(session, getId());
144 }
145
146 @Override
147 public final boolean isHidden() {
148 return table.isHidden();
149 }
150
151 @Override
152 public String getCreateSQLForCopy(Table targetTable, String quotedName) {
153 StringBuilder builder = new StringBuilder("CREATE ");
154 builder.append(indexType.getSQL(true));
155 builder.append(' ');
156 if (table.isHidden()) {
157 builder.append("IF NOT EXISTS ");
158 }
159 builder.append(quotedName);
160 builder.append(" ON ");
161 targetTable.getSQL(builder, DEFAULT_SQL_FLAGS);
162 if (comment != null) {
163 builder.append(" COMMENT ");
164 StringUtils.quoteStringSQL(builder, comment);
165 }
166 return getColumnListSQL(builder, DEFAULT_SQL_FLAGS).toString();
167 }
168
169
170 /**
171 * Get the list of columns as a string.
172 *
173 * @param sqlFlags formatting flags
174 * @return the list of columns
175 */
176 private StringBuilder getColumnListSQL(StringBuilder builder, int sqlFlags) {
177 builder.append('(');
178 int length = indexColumns.length;
179 if (uniqueColumnColumn > 0 && uniqueColumnColumn < length) {
180 IndexColumn.writeColumns(builder, indexColumns, 0, uniqueColumnColumn, sqlFlags).append(") INCLUDE(");
181 IndexColumn.writeColumns(builder, indexColumns, uniqueColumnColumn, length, sqlFlags);
182 } else {
183 IndexColumn.writeColumns(builder, indexColumns, 0, length, sqlFlags);
184 }
185 return builder.append(')');
186 }
187
188 @Override
189 public String getCreateSQL() {
190 return getCreateSQLForCopy(table, getSQL(DEFAULT_SQL_FLAGS));
191 }
192
193 /**
194 * Get the message to show in a EXPLAIN statement.
195 *
196 * @return the plan
197 */
198 public String getPlanSQL() {
199 return getSQL(TRACE_SQL_FLAGS | ADD_PLAN_INFORMATION);
200 }
201
202 /**
203 * Close this index.
204 *
205 * @param session the session used to write data
206 */
207 public abstract void close(SessionLocal session);
208
209 /**
210 * Add a row to the index.
211 *
212 * @param session the session to use
213 * @param row the row to add
214 */
215 public abstract void add(SessionLocal session, Row row);
216
217 /**
218 * Remove a row from the index.
219 *
220 * @param session the session
221 * @param row the row
222 */
223 public abstract void remove(SessionLocal session, Row row);
224
225 /**
226 * Update index after row change.
227 *
228 * @param session the session
229 * @param oldRow row before the update
230 * @param newRow row after the update
231 */
232 public void update(SessionLocal session, Row oldRow, Row newRow) {
233 remove(session, oldRow);
234 add(session, newRow);
235 }
236
237 /**
238 * Returns {@code true} if {@code find()} implementation performs scan over all
239 * index, {@code false} if {@code find()} performs the fast lookup.
240 *
241 * @return {@code true} if {@code find()} implementation performs scan over all
242 * index, {@code false} if {@code find()} performs the fast lookup
243 */
244 public boolean isFindUsingFullTableScan() {
245 return false;
246 }
247
248 /**
249 * Find a row or a list of rows and create a cursor to iterate over the
250 * result.
251 *
252 * @param session the session
253 * @param first the first row, or null for no limit
254 * @param last the last row, or null for no limit
255 * @return the cursor to iterate over the results
256 */
257 public abstract Cursor find(SessionLocal session, SearchRow first, SearchRow last);
258
259 /**
260 * Estimate the cost to search for rows given the search mask.
261 * There is one element per column in the search mask.
262 * For possible search masks, see IndexCondition.
263 *
264 * @param session the session
265 * @param masks per-column comparison bit masks, null means 'always false',
266 * see constants in IndexCondition
267 * @param filters all joined table filters
268 * @param filter the current table filter index
269 * @param sortOrder the sort order
270 * @param allColumnsSet the set of all columns
271 * @return the estimated cost
272 */
273 public abstract double getCost(SessionLocal session, int[] masks, TableFilter[] filters, int filter,
274 SortOrder sortOrder, AllColumnsForPlan allColumnsSet);
275
276 /**
277 * Remove the index.
278 *
279 * @param session the session
280 */
281 public abstract void remove(SessionLocal session);
282
283 /**
284 * Remove all rows from the index.
285 *
286 * @param session the session
287 */
288 public abstract void truncate(SessionLocal session);
289
290 /**
291 * Check if the index can directly look up the lowest or highest value of a
292 * column.
293 *
294 * @return true if it can
295 */
296 public boolean canGetFirstOrLast() {
297 return false;
298 }
299
300 /**
301 * Check if the index can get the next higher value.
302 *
303 * @return true if it can
304 */
305 public boolean canFindNext() {
306 return false;
307 }
308
309 /**
310 * Find a row or a list of rows that is larger and create a cursor to
311 * iterate over the result.
312 *
313 * @param session the session
314 * @param higherThan the lower limit (excluding)
315 * @param last the last row, or null for no limit
316 * @return the cursor
317 */
318 public Cursor findNext(SessionLocal session, SearchRow higherThan, SearchRow last) {
319 throw DbException.getInternalError(toString());
320 }
321
322 /**
323 * Find the first (or last) value of this index. The cursor returned is
324 * positioned on the correct row, or on null if no row has been found.
325 *
326 * @param session the session
327 * @param first true if the first (lowest for ascending indexes) or last
328 * value should be returned
329 * @return a cursor (never null)
330 */
331 public Cursor findFirstOrLast(SessionLocal session, boolean first) {
332 throw DbException.getInternalError(toString());
333 }
334
335 /**
336 * Check if the index needs to be rebuilt.
337 * This method is called after opening an index.
338 *
339 * @return true if a rebuild is required.
340 */
341 public abstract boolean needRebuild();
342
343 /**
344 * Get the row count of this table, for the given session.
345 *
346 * @param session the session
347 * @return the row count
348 */
349 public abstract long getRowCount(SessionLocal session);
350
351 /**
352 * Get the approximated row count for this table.
353 *
354 * @param session the session
355 * @return the approximated row count
356 */
357 public abstract long getRowCountApproximation(SessionLocal session);
358
359 /**
360 * Get the used disk space for this index.
361 *
362 * @return the estimated number of bytes
363 */
364 public long getDiskSpaceUsed() {
365 return 0L;
366 }
367
368 /**
369 * Compare two rows.
370 *
371 * @param rowData the first row
372 * @param compare the second row
373 * @return 0 if both rows are equal, -1 if the first row is smaller,
374 * otherwise 1
375 */
376 public final int compareRows(SearchRow rowData, SearchRow compare) {
377 if (rowData == compare) {
378 return 0;
379 }
380 for (int i = 0, len = indexColumns.length; i < len; i++) {
381 int index = columnIds[i];
382 Value v1 = rowData.getValue(index);
383 Value v2 = compare.getValue(index);
384 if (v1 == null || v2 == null) {
385 // can't compare further
386 return 0;
387 }
388 int c = compareValues(v1, v2, indexColumns[i].sortType);
389 if (c != 0) {
390 return c;
391 }
392 }
393 return 0;
394 }
395
396 private int compareValues(Value a, Value b, int sortType) {
397 if (a == b) {
398 return 0;
399 }
400 boolean aNull = a == ValueNull.INSTANCE;
401 if (aNull || b == ValueNull.INSTANCE) {
402 return table.getDatabase().getDefaultNullOrdering().compareNull(aNull, sortType);
403 }
404 int comp = table.compareValues(database, a, b);
405 if ((sortType & SortOrder.DESCENDING) != 0) {
406 comp = -comp;
407 }
408 return comp;
409 }
410
411 /**
412 * Get the index of a column in the list of index columns
413 *
414 * @param col the column
415 * @return the index (0 meaning first column)
416 */
417 public int getColumnIndex(Column col) {
418 for (int i = 0, len = columns.length; i < len; i++) {
419 if (columns[i].equals(col)) {
420 return i;
421 }
422 }
423 return -1;
424 }
425
426 /**
427 * Check if the given column is the first for this index
428 *
429 * @param column the column
430 * @return true if the given columns is the first
431 */
432 public boolean isFirstColumn(Column column) {
433 return column.equals(columns[0]);
434 }
435
436 /**
437 * Get the indexed columns as index columns (with ordering information).
438 *
439 * @return the index columns
440 */
441 public final IndexColumn[] getIndexColumns() {
442 return indexColumns;
443 }
444
445 /**
446 * Get the indexed columns.
447 *
448 * @return the columns
449 */
450 public final Column[] getColumns() {
451 return columns;
452 }
453
454 /**
455 * Returns count of unique columns. Unique columns, if any, are always first
456 * columns in the lists. Unique indexes may have additional indexed
457 * non-unique columns.
458 *
459 * @return count of unique columns, or 0 if index isn't unique
460 */
461 public final int getUniqueColumnCount() {
462 return uniqueColumnColumn;
463 }
464
465 /**
466 * Get the index type.
467 *
468 * @return the index type
469 */
470 public final IndexType getIndexType() {
471 return indexType;
472 }
473
474 /**
475 * Get the table on which this index is based.
476 *
477 * @return the table
478 */
479 public Table getTable() {
480 return table;
481 }
482
483 /**
484 * Get the row with the given key.
485 *
486 * @param session the session
487 * @param key the unique key
488 * @return the row
489 */
490 public Row getRow(SessionLocal session, long key) {
491 throw DbException.getUnsupportedException(toString());
492 }
493
494 /**
495 * Does this index support lookup by row id?
496 *
497 * @return true if it does
498 */
499 public boolean isRowIdIndex() {
500 return false;
501 }
502
503 /**
504 * Can this index iterate over all rows?
505 *
506 * @return true if it can
507 */
508 public boolean canScan() {
509 return true;
510 }
511
512 /**
513 * Create a duplicate key exception with a message that contains the index
514 * name.
515 *
516 * @param key the key values
517 * @return the exception
518 */
519 public DbException getDuplicateKeyException(String key) {
520 StringBuilder builder = new StringBuilder();
521 getSQL(builder, TRACE_SQL_FLAGS).append(" ON ");
522 table.getSQL(builder, TRACE_SQL_FLAGS);
523 getColumnListSQL(builder, TRACE_SQL_FLAGS);
524 if (key != null) {
525 builder.append(" VALUES ").append(key);
526 }
527 DbException e = DbException.get(ErrorCode.DUPLICATE_KEY_1, builder.toString());
528 e.setSource(this);
529 return e;
530 }
531
532 /**
533 * Get "PRIMARY KEY ON &lt;table&gt; [(column)]".
534 *
535 * @param mainIndexColumn the column index
536 * @return the message
537 */
538 protected StringBuilder getDuplicatePrimaryKeyMessage(int mainIndexColumn) {
539 StringBuilder builder = new StringBuilder("PRIMARY KEY ON ");
540 table.getSQL(builder, TRACE_SQL_FLAGS);
541 if (mainIndexColumn >= 0 && mainIndexColumn < indexColumns.length) {
542 builder.append('(');
543 indexColumns[mainIndexColumn].getSQL(builder, TRACE_SQL_FLAGS).append(')');
544 }
545 return builder;
546 }
547
548 /**
549 * Calculate the cost for the given mask as if this index was a typical
550 * b-tree range index. This is the estimated cost required to search one
551 * row, and then iterate over the given number of rows.
552 *
553 * @param masks the IndexCondition search masks, one for each column in the
554 * table
555 * @param rowCount the number of rows in the index
556 * @param filters all joined table filters
557 * @param filter the current table filter index
558 * @param sortOrder the sort order
559 * @param isScanIndex whether this is a "table scan" index
560 * @param allColumnsSet the set of all columns
561 * @return the estimated cost
562 */
563 protected final long getCostRangeIndex(int[] masks, long rowCount, TableFilter[] filters, int filter,
564 SortOrder sortOrder, boolean isScanIndex, AllColumnsForPlan allColumnsSet) {
565 rowCount += Constants.COST_ROW_OFFSET;
566 int totalSelectivity = 0;
567 long rowsCost = rowCount;
568 if (masks != null) {
569 int i = 0, len = columns.length;
570 boolean tryAdditional = false;
571 while (i < len) {
572 Column column = columns[i++];
573 int index = column.getColumnId();
574 int mask = masks[index];
575 if ((mask & IndexCondition.EQUALITY) == IndexCondition.EQUALITY) {
576 if (i > 0 && i == uniqueColumnColumn) {
577 rowsCost = 3;
578 break;
579 }
580 totalSelectivity = 100 - ((100 - totalSelectivity) *
581 (100 - column.getSelectivity()) / 100);
582 long distinctRows = rowCount * totalSelectivity / 100;
583 if (distinctRows <= 0) {
584 distinctRows = 1;
585 }
586 rowsCost = 2 + Math.max(rowCount / distinctRows, 1);
587 } else if ((mask & IndexCondition.RANGE) == IndexCondition.RANGE) {
588 rowsCost = 2 + rowsCost / 4;
589 tryAdditional = true;
590 break;
591 } else if ((mask & IndexCondition.START) == IndexCondition.START) {
592 rowsCost = 2 + rowsCost / 3;
593 tryAdditional = true;
594 break;
595 } else if ((mask & IndexCondition.END) == IndexCondition.END) {
596 rowsCost = rowsCost / 3;
597 tryAdditional = true;
598 break;
599 } else {
600 if (mask == 0) {
601 // Adjust counter of used columns (i)
602 i--;
603 }
604 break;
605 }
606 }
607 // Some additional columns can still be used
608 if (tryAdditional) {
609 while (i < len && masks[columns[i].getColumnId()] != 0) {
610 i++;
611 rowsCost--;
612 }
613 }
614 // Increase cost of indexes with additional unused columns
615 rowsCost += len - i;
616 }
617 // If the ORDER BY clause matches the ordering of this index,
618 // it will be cheaper than another index, so adjust the cost
619 // accordingly.
620 long sortingCost = 0;
621 if (sortOrder != null) {
622 sortingCost = 100 + rowCount / 10;
623 }
624 if (sortOrder != null && !isScanIndex) {
625 boolean sortOrderMatches = true;
626 int coveringCount = 0;
627 int[] sortTypes = sortOrder.getSortTypesWithNullOrdering();
628 TableFilter tableFilter = filters == null ? null : filters[filter];
629 for (int i = 0, len = sortTypes.length; i < len; i++) {
630 if (i >= indexColumns.length) {
631 // We can still use this index if we are sorting by more
632 // than it's columns, it's just that the coveringCount
633 // is lower than with an index that contains
634 // more of the order by columns.
635 break;
636 }
637 Column col = sortOrder.getColumn(i, tableFilter);
638 if (col == null) {
639 sortOrderMatches = false;
640 break;
641 }
642 IndexColumn indexCol = indexColumns[i];
643 if (!col.equals(indexCol.column)) {
644 sortOrderMatches = false;
645 break;
646 }
647 int sortType = sortTypes[i];
648 if (sortType != indexCol.sortType) {
649 sortOrderMatches = false;
650 break;
651 }
652 coveringCount++;
653 }
654 if (sortOrderMatches) {
655 // "coveringCount" makes sure that when we have two
656 // or more covering indexes, we choose the one
657 // that covers more.
658 sortingCost = 100 - coveringCount;
659 }
660 }
661 // If we have two indexes with the same cost, and one of the indexes can
662 // satisfy the query without needing to read from the primary table
663 // (scan index), make that one slightly lower cost.
664 boolean needsToReadFromScanIndex;
665 if (!isScanIndex && allColumnsSet != null) {
666 needsToReadFromScanIndex = false;
667 ArrayList<Column> foundCols = allColumnsSet.get(getTable());
668 if (foundCols != null) {
669 int main = table.getMainIndexColumn();
670 loop: for (Column c : foundCols) {
671 int id = c.getColumnId();
672 if (id == SearchRow.ROWID_INDEX || id == main) {
673 continue;
674 }
675 for (Column c2 : columns) {
676 if (c == c2) {
677 continue loop;
678 }
679 }
680 needsToReadFromScanIndex = true;
681 break;
682 }
683 }
684 } else {
685 needsToReadFromScanIndex = true;
686 }
687 long rc;
688 if (isScanIndex) {
689 rc = rowsCost + sortingCost + 20;
690 } else if (needsToReadFromScanIndex) {
691 rc = rowsCost + rowsCost + sortingCost + 20;
692 } else {
693 // The (20-x) calculation makes sure that when we pick a covering
694 // index, we pick the covering index that has the smallest number of
695 // columns (the more columns we have in index - the higher cost).
696 // This is faster because a smaller index will fit into fewer data
697 // blocks.
698 rc = rowsCost + sortingCost + columns.length;
699 }
700 return rc;
701 }
702
703
704 /**
705 * Check if this row needs to be checked for duplicates.
706 *
707 * @param searchRow
708 * the row to check
709 * @return {@code true} if check for duplicates is required,
710 * {@code false otherwise}
711 */
712 public final boolean needsUniqueCheck(SearchRow searchRow) {
713 NullsDistinct nullsDistinct = indexType.getEffectiveNullsDistinct();
714 return nullsDistinct != null && (nullsDistinct == NullsDistinct.NOT_DISTINCT
715 || needsUniqueCheck(searchRow, nullsDistinct == NullsDistinct.DISTINCT));
716 }
717
718 private boolean needsUniqueCheck(SearchRow searchRow, boolean distinct) {
719 if (distinct) {
720 for (int i = 0; i < uniqueColumnColumn; i++) {
721 int index = columnIds[i];
722 if (searchRow.getValue(index) == ValueNull.INSTANCE) {
723 return false;
724 }
725 }
726 return true;
727 } else {
728 for (int i = 0; i < uniqueColumnColumn; i++) {
729 int index = columnIds[i];
730 if (searchRow.getValue(index) != ValueNull.INSTANCE) {
731 return true;
732 }
733 }
734 return false;
735 }
736 }
737
738 public RowFactory getRowFactory() {
739 return rowFactory;
740 }
741
742 public RowFactory getUniqueRowFactory() {
743 return uniqueRowFactory;
744 }
745
746 }