1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.expression; |
7 | |
8 | import org.h2.engine.Constants; |
9 | import org.h2.engine.Database; |
10 | import org.h2.util.IntIntHashMap; |
11 | import org.h2.value.Value; |
12 | import org.h2.value.ValueInt; |
13 | |
14 | /** |
15 | * Data stored while calculating a SELECTIVITY aggregate. |
16 | */ |
17 | class AggregateDataSelectivity extends AggregateData { |
18 | private long count; |
19 | private IntIntHashMap distinctHashes; |
20 | private double m2; |
21 | |
22 | @Override |
23 | void add(Database database, int dataType, boolean distinct, Value v) { |
24 | count++; |
25 | if (distinctHashes == null) { |
26 | distinctHashes = new IntIntHashMap(); |
27 | } |
28 | int size = distinctHashes.size(); |
29 | if (size > Constants.SELECTIVITY_DISTINCT_COUNT) { |
30 | distinctHashes = new IntIntHashMap(); |
31 | m2 += size; |
32 | } |
33 | int hash = v.hashCode(); |
34 | // the value -1 is not supported |
35 | distinctHashes.put(hash, 1); |
36 | } |
37 | |
38 | @Override |
39 | Value getValue(Database database, int dataType, boolean distinct) { |
40 | if (distinct) { |
41 | count = 0; |
42 | } |
43 | Value v = null; |
44 | int s = 0; |
45 | if (count == 0) { |
46 | s = 0; |
47 | } else { |
48 | m2 += distinctHashes.size(); |
49 | m2 = 100 * m2 / count; |
50 | s = (int) m2; |
51 | s = s <= 0 ? 1 : s > 100 ? 100 : s; |
52 | } |
53 | v = ValueInt.get(s); |
54 | return v.convertTo(dataType); |
55 | } |
56 | } |