File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\index\NonUniqueHashIndex.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.index;
8
9 import java.util.ArrayList;
10 import org.h2.engine.Session;
11 import org.h2.message.DbException;
12 import org.h2.result.Row;
13 import org.h2.result.SearchRow;
14 import org.h2.table.IndexColumn;
15 import org.h2.table.RegularTable;
16 import org.h2.util.New;
17 import org.h2.util.ValueHashMap;
18 import org.h2.value.Value;
19
20 /**
21 * A non-unique index based on an in-memory hash map.
22 *
23 * @author Sergi Vladykin
24 */
25 public class NonUniqueHashIndex extends HashIndex {
26
27 private ValueHashMap<ArrayList<Long>> rows;
28 private final RegularTable tableData;
29 private long rowCount;
30
31 public NonUniqueHashIndex(RegularTable table, int id, String indexName, IndexColumn[] columns, IndexType indexType) {
32 super(table, id, indexName, columns, indexType);
33 this.tableData = table;
34 reset();
35 }
36
37 private void reset() {
38 rows = ValueHashMap.newInstance();
39 rowCount = 0;
40 }
41
42 public void truncate(Session session) {
43 reset();
44 }
45
46 public void add(Session session, Row row) {
47 Value key = row.getValue(indexColumn);
48 ArrayList<Long> positions = rows.get(key);
49 if (positions == null) {
50 positions = New.arrayList();
51 rows.put(key, positions);
52 }
53 positions.add(row.getKey());
54 rowCount++;
55 }
56
57 public void remove(Session session, Row row) {
58 if (rowCount == 1) {
59 // last row in table
60 reset();
61 } else {
62 Value key = row.getValue(indexColumn);
63 ArrayList<Long> positions = rows.get(key);
64 if (positions.size() == 1) {
65 // last row with such key
66 rows.remove(key);
67 } else {
68 positions.remove(row.getKey());
69 }
70 rowCount--;
71 }
72 }
73
74 public Cursor find(Session session, SearchRow first, SearchRow last) {
75 if (first == null || last == null) {
76 throw DbException.throwInternalError();
77 }
78 if (first != last) {
79 if (compareKeys(first, last) != 0) {
80 throw DbException.throwInternalError();
81 }
82 }
83 ArrayList<Long> positions = rows.get(first.getValue(indexColumn));
84 return new NonUniqueHashCursor(session, tableData, positions);
85 }
86
87 public long getRowCount(Session session) {
88 return rowCount;
89 }
90
91 public long getRowCountApproximation() {
92 return rowCount;
93 }
94
95 }
96