com.googlecode.cqengine.attribute.SimpleAttribute Java Examples

The following examples show how to use com.googlecode.cqengine.attribute.SimpleAttribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCountOfDistinctKeys(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MANUFACTURER,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(20), createQueryOptions(connectionManager));

    Assert.assertEquals(Integer.valueOf(4), offHeapIndex.getCountOfDistinctKeys(createQueryOptions(connectionManager)));
}
 
Example #2
Source File: SuffixTreeIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * If a query option specifying logical deduplication was supplied, wrap the given result sets in
 * {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
 * <p/>
 * An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
 * {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
 *
 * @param results Provides the result sets to union
 * @param query The query for which the union is being constructed
 * @param queryOptions Specifies whether or not logical deduplication is required
 * @return A union view over the given result sets
 */
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
    if (DeduplicationOption.isLogicalElimination(queryOptions)
            && !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
        return new ResultSetUnion<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
    else {
        return new ResultSetUnionAll<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
}
 
Example #3
Source File: InvertedRadixTreeIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * If a query option specifying logical deduplication was supplied, wrap the given result sets in
 * {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
 * <p/>
 * An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
 * {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
 *
 * @param results Provides the result sets to union
 * @param query The query for which the union is being constructed
 * @param queryOptions Specifies whether or not logical deduplication is required
 * @return A union view over the given result sets
 */
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
    if (DeduplicationOption.isLogicalElimination(queryOptions)
            && !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
        return new ResultSetUnion<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
    else {
        return new ResultSetUnionAll<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
}
 
Example #4
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetStatisticsForDistinctKeysDescending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MANUFACTURER,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(20), createQueryOptions(connectionManager));

    Set<KeyStatistics<String>> keyStatistics = setOf(offHeapIndex.getStatisticsForDistinctKeysDescending(createQueryOptions(connectionManager)));
    Assert.assertEquals(setOf(
                    new KeyStatistics<String>("Toyota", 6),
                    new KeyStatistics<String>("Honda", 6),
                    new KeyStatistics<String>("Ford", 6),
                    new KeyStatistics<String>("BMW", 2)

            ),
            keyStatistics);
}
 
Example #5
Source File: LongestPrefix.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<O> getMatchesForSimpleAttribute(SimpleAttribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
    List<O> results = new ArrayList<>();
    int currentCount = -1;
    for (O object : objectsInCollection) {
        CharSequence attributeValue = attribute.getValue(object, queryOptions);
        int count = countPrefixChars(value, attributeValue);
        if (count == 0) {
            continue;
        }
        if (count > currentCount) {
            currentCount = count;
            results.clear();
            results.add(object);
        } else if (count == currentCount) {
            results.add(object);
        }
    }
    return results;
}
 
Example #6
Source File: SQLiteIdentityIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
public SQLiteIdentityIndex(final SimpleAttribute<O, A> primaryKeyAttribute) {
    this.sqLiteIndex = new SQLiteIndex<A, O, byte[]>(
            primaryKeyAttribute,
            new SerializingAttribute(primaryKeyAttribute.getObjectType(), byte[].class),
            new DeserializingAttribute(byte[].class, primaryKeyAttribute.getObjectType()),
            "") {
        // Override getEffectiveIndex() in the SQLiteIndex to return a reference to this index...
        @Override
        public Index<O> getEffectiveIndex() {
            return SQLiteIdentityIndex.this.getEffectiveIndex();
        }
    };
    this.objectType = primaryKeyAttribute.getObjectType();
    this.primaryKeyAttribute = primaryKeyAttribute;
    this.foreignKeyAttribute = new ForeignKeyAttribute();
    this.pojoSerializer = createSerializer(objectType);
}
 
Example #7
Source File: CompositePersistence.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method for {@link #validatePersistenceArguments(Persistence, Persistence, List)}. See documentation of
 * that method for details.
 */
static <O, A extends Comparable<A>> SimpleAttribute<O, A> validatePersistenceArgument(Persistence<O, A> persistence, SimpleAttribute<O, A> primaryKeyAttribute) {
    if (persistence == null) {
        throw new NullPointerException("The Persistence argument cannot be null.");
    }
    if (persistence.getPrimaryKeyAttribute() == null) {
        throw new IllegalArgumentException("All Persistence implementations in a CompositePersistence must have a primary key.");
    }
    if (primaryKeyAttribute == null) {
        primaryKeyAttribute = persistence.getPrimaryKeyAttribute();
    }
    else if (!primaryKeyAttribute.equals(persistence.getPrimaryKeyAttribute())) {
        throw new IllegalArgumentException("All Persistence implementations must be on the same primary key.");
    }
    return primaryKeyAttribute;
}
 
Example #8
Source File: SQLiteIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor. Note the index should normally be created via the static factory methods instead.
 *
 * @param attribute The {@link Attribute} on which the index will be built.
 * @param primaryKeyAttribute The {@link SimpleAttribute} with which the index will retrieve the object key.
 * @param foreignKeyAttribute The {@link SimpleAttribute} to map a query result into the domain object.
 * @param tableNameSuffix An optional string to append the end of the table name used by this index;
 *                        This can be an empty string, but cannot be null; If not an empty string, the string
 *                        should only contain characters suitable for use in a SQLite table name; therefore see
 *                        {@link DBUtils#sanitizeForTableName(String)}
 */
public SQLiteIndex(final Attribute<O, A> attribute,
                   final SimpleAttribute<O, K> primaryKeyAttribute,
                   final SimpleAttribute<K, O> foreignKeyAttribute,
                   final String tableNameSuffix) {

    super(attribute, new HashSet<Class<? extends Query>>() {{
        add(Equal.class);
        add(In.class);
        add(LessThan.class);
        add(GreaterThan.class);
        add(Between.class);
        add(StringStartsWith.class);
        add(Has.class);
    }});

    this.tableName = sanitizeForTableName(attribute.getAttributeName()) + tableNameSuffix;
    this.primaryKeyAttribute = primaryKeyAttribute;
    this.foreignKeyAttribute = foreignKeyAttribute;
}
 
Example #9
Source File: ReversedRadixTreeIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * If a query option specifying logical deduplication was supplied, wrap the given result sets in
 * {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
 * <p/>
 * An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
 * {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
 *
 * @param results Provides the result sets to union
 * @param query The query for which the union is being constructed
 * @param queryOptions Specifies whether or not logical deduplication is required
 * @return A union view over the given result sets
 */
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
    if (DeduplicationOption.isLogicalElimination(queryOptions)
            && !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
        return new ResultSetUnion<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
    else {
        return new ResultSetUnionAll<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
}
 
Example #10
Source File: SQLiteIdentityIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerialization() {
    SQLiteIdentityIndex<Integer, Car> index = new SQLiteIdentityIndex<Integer, Car>(
            Car.CAR_ID
    );

    SimpleAttribute<Car, byte[]> serializingAttribute = index.new SerializingAttribute(Car.class, byte[].class);
    SimpleAttribute<byte[], Car> deserializingAttribute = index.new DeserializingAttribute(byte[].class, Car.class);

    Car c1 = CarFactory.createCar(1);
    byte[] s1 = serializingAttribute.getValue(c1, noQueryOptions());
    Car c2 = deserializingAttribute.getValue(s1, noQueryOptions());
    byte[] s2 = serializingAttribute.getValue(c2, noQueryOptions());
    Assert.assertEquals(c1, c2);
    Assert.assertArrayEquals(s1, s2);
}
 
Example #11
Source File: ClusteredConcurrentIndexedCollection.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ClusteredConcurrentIndexedCollection(String name, HazelcastInstance hazelcastInstance, SimpleAttribute<O, K> primaryKeyAttribute,
        ClusteredCollectionEntryListener<O> entryListener) {
    super(OnHeapPersistence.<O, K>onPrimaryKey(primaryKeyAttribute));
    this.primaryKeyAttribute = primaryKeyAttribute;
    this.hazelcastInstance = hazelcastInstance;
    this.clusteredCollectionEntryListener = entryListener;
    if (hazelcastInstance != null) {
        this.map = this.hazelcastInstance.getMap(name);
        this.map.addEntryListener(new HazelcastEntryListener(), true);
        this.member = hazelcastInstance.getCluster().getLocalMember();
        this.lock = this.hazelcastInstance.getLock(name + "_LOCK");
    } else {
        log.debug("No hazelcast instance defined, acting just locally");
        this.map = null;
        this.member = null;
        this.lock = null;
    }
    this.hasRemoteStorage = this.map != null;
    this.requiresNotification = this.clusteredCollectionEntryListener != null;
    this.isLocallyHandled = hasRemoteStorage || requiresNotification;
}
 
Example #12
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_AllAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));

    List<String> expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
    List<String> actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #13
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_AllDescending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));

    List<String> expected = Arrays.asList("Taurus", "Prius", "M6", "Insight", "Hilux", "Fusion", "Focus", "Civic", "Avensis", "Accord");
    List<String> actual = Lists.newArrayList(offHeapIndex.getDistinctKeysDescending(createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #14
Source File: Between.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
    A attributeValue = attribute.getValue(object, queryOptions);
    if (lowerInclusive && upperInclusive) {
        if (lowerValue.compareTo(attributeValue) <= 0 && upperValue.compareTo(attributeValue) >= 0) {
            return true;
        }
    }
    else if (lowerInclusive) {
        if (lowerValue.compareTo(attributeValue) <= 0 && upperValue.compareTo(attributeValue) > 0) {
            return true;
        }
    }
    else if (upperInclusive) {
        if (lowerValue.compareTo(attributeValue) < 0 && upperValue.compareTo(attributeValue) >= 0) {
            return true;
        }
    }
    else {
        if (lowerValue.compareTo(attributeValue) < 0 && upperValue.compareTo(attributeValue) > 0) {
            return true;
        }
    }
    return false;
}
 
Example #15
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetStatisticsForDistinctKeys(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MANUFACTURER,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(20), createQueryOptions(connectionManager));

    Set<KeyStatistics<String>> keyStatistics = setOf(offHeapIndex.getStatisticsForDistinctKeys(createQueryOptions(connectionManager)));
    Assert.assertEquals(setOf(
                    new KeyStatistics<String>("Ford", 6),
                    new KeyStatistics<String>("Honda", 6),
                    new KeyStatistics<String>("Toyota", 6),
                    new KeyStatistics<String>("BMW", 2)

            ),
            keyStatistics);
}
 
Example #16
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_GreaterThanInclusiveAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Accord", true, null, true, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #17
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_LessThanInclusiveAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "Prius", true, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #18
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_BetweenExclusiveAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList("Focus", "Fusion", "Hilux");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Civic", false, "Insight", false, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #19
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_BetweenInclusiveAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList("Civic", "Focus", "Fusion", "Hilux", "Insight");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Civic", true, "Insight", true, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #20
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_BetweenInclusiveDescending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList("Insight", "Hilux", "Fusion", "Focus", "Civic");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeysDescending("Civic", true, "Insight", true, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #21
Source File: MetadataEngineTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testAttemptToAccessMetadataWithIndexOnDifferentAttribute() {
    IndexedCollection<Car> cars = createIndexedCollectionOfCars(5);
    // Add an index on a different attribute...
    cars.addIndex(HashIndex.onAttribute(Car.MODEL));
    // Create a mock (different) attribute we will query...
    @SuppressWarnings("unchecked") Attribute<Car, Integer> ATTRIBUTE = Mockito.mock(SimpleAttribute.class);
    Mockito.when(ATTRIBUTE.toString()).thenReturn("ATTRIBUTE");
    IllegalStateException expected = null;
    try {
        cars.getMetadataEngine().getAttributeMetadata(ATTRIBUTE);
    }
    catch (IllegalStateException e) {
        expected = e;
    }
    assertNotNull(expected);
    assertEquals("A KeyStatisticsAttributeIndex has not been added to the collection, and must be added first, to enable metadata to be examined for attribute: ATTRIBUTE", expected.getMessage());
}
 
Example #22
Source File: PartialSQLiteIndex.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Protected constructor, called by subclasses.
 *
 * @param attribute The {@link Attribute} on which the index will be built.
 * @param primaryKeyAttribute The {@link SimpleAttribute} used to retrieve the primary key.
 * @param foreignKeyAttribute The {@link SimpleAttribute} to map a query result into the domain object.
 * @param filterQuery The filter query which matches the subset of objects to be stored in this index.
 */
protected PartialSQLiteIndex(Attribute<O, A> attribute,
                             SimpleAttribute<O, K> primaryKeyAttribute,
                             SimpleAttribute<K, O> foreignKeyAttribute,
                             Query<O> filterQuery) {
    super(attribute, filterQuery);
    this.primaryKeyAttribute = primaryKeyAttribute;
    this.foreignKeyAttribute = foreignKeyAttribute;
    this.tableNameSuffix = "_partial_" + sanitizeForTableName(filterQuery.toString());
}
 
Example #23
Source File: OffHeapPersistence.java    From cqengine with Apache License 2.0 5 votes vote down vote up
protected OffHeapPersistence(SimpleAttribute<O, A> primaryKeyAttribute, Properties overrideProperties) {
    Properties effectiveProperties = new Properties(DEFAULT_PROPERTIES);
    effectiveProperties.putAll(overrideProperties);
    SQLiteConfig sqLiteConfig = new SQLiteConfig(effectiveProperties);
    SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(sqLiteConfig);
    String instanceName = "cqengine_" + INSTANCE_ID_GENERATOR.incrementAndGet();
    sqLiteDataSource.setUrl("jdbc:sqlite:file:" + instanceName + "?mode=memory&cache=shared");

    this.primaryKeyAttribute = primaryKeyAttribute;
    this.instanceName = instanceName;
    this.sqLiteDataSource = sqLiteDataSource;
    this.persistentConnection = getConnectionInternal(null, noQueryOptions());
}
 
Example #24
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDistinctKeys_GreaterThanExclusiveAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("", false, null, true, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);

    expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("A", false, null, true, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);

    expected = Arrays.asList("Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Accord", false, null, true, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #25
Source File: IndexedCollectionFunctionalTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
private static SimpleAttribute<Integer, Car> createForeignKeyAttribute() {
    return new SimpleAttribute<Integer, Car>() {
        @Override
        public Car getValue(final Integer carId, final QueryOptions queryOptions) {
            return CarFactory.createCar(carId);
        }
    };
}
 
Example #26
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDistinctKeys_LessThanExclusiveAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList();
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "", false, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);

    expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "Z", false, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);

    expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "Prius", false, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #27
Source File: MetadataEngineTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttemptToAccessMetadataWithoutSortedIndex() {
    IndexedCollection<Car> cars = createIndexedCollectionOfCars(5);
    @SuppressWarnings("unchecked") Attribute<Car, Integer> ATTRIBUTE = Mockito.mock(SimpleAttribute.class);
    Mockito.when(ATTRIBUTE.toString()).thenReturn("ATTRIBUTE");
    IllegalStateException expected = null;
    try {
        cars.getMetadataEngine().getSortedAttributeMetadata(ATTRIBUTE);
    }
    catch (IllegalStateException e) {
        expected = e;
    }
    assertNotNull(expected);
    assertEquals("A SortedKeyStatisticsAttributeIndex has not been added to the collection, and must be added first, to enable metadata to be examined for attribute: ATTRIBUTE", expected.getMessage());
}
 
Example #28
Source File: IndexSupport.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * <p> If a query option specifying logical deduplication was supplied, wrap the given result sets in {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
 *
 * <p> There are two exceptions where a {@link ResultSetUnionAll} is used regardless of the logical deduplication query option:
 * <ul>
 *     <li>
 *         If the index is built on a SimpleAttribute which means that the same object could not exist in more than one {@link StoredResultSet}.
 *     </li>
 *     <li>
 *         If the query is an {@link In} query and it is marked as disjoint ( {@link In#isDisjoint()} returns true )
 *     </li>
 * </ul>
 *
 * @param results Provides the result sets to union
 * @param query The query for which the union is being constructed
 * @param queryOptions Specifies whether or not logical deduplication is required
 * @param retrievalCost The resultSet retrieval cost
 * @return A union view over the given result sets
 */
public static <O, A> ResultSet<O> deduplicateIfNecessary(final Iterable<? extends ResultSet<O>> results,
                                                         final Query<O> query,
                                                         final Attribute<O, A> attribute,
                                                         final QueryOptions queryOptions,
                                                         final int retrievalCost) {
    boolean logicalElimination = DeduplicationOption.isLogicalElimination(queryOptions);
    boolean attributeHasAtMostOneValue = (attribute instanceof SimpleAttribute || attribute instanceof SimpleNullableAttribute);
    boolean queryIsADisjointInQuery = query instanceof In && ((In) query).isDisjoint();
    if (!logicalElimination || attributeHasAtMostOneValue || queryIsADisjointInQuery) {
        // No need to deduplicate...
        return new ResultSetUnionAll<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return retrievalCost;
            }
        };
    } else {
        // We need to deduplicate...
        return new ResultSetUnion<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return retrievalCost;
            }
        };
    }
}
 
Example #29
Source File: CompositePersistence.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Validates that all of the given Persistence objects are non-null, and validates that all Persistence objects
 * which have primary keys have the same primary keys.
 *
 * @param primaryPersistence A Persistence object to be validated
 * @param secondaryPersistence A Persistence object to be validated
 * @param additionalPersistences Zero or more Persistence objects to be validated
 */
static <O, A extends Comparable<A>> void validatePersistenceArguments(Persistence<O, A> primaryPersistence, Persistence<O, A> secondaryPersistence, List<? extends Persistence<O, A>> additionalPersistences) {
    SimpleAttribute<O, A> primaryKeyAttribute;
    primaryKeyAttribute = validatePersistenceArgument(primaryPersistence, null);
    primaryKeyAttribute = validatePersistenceArgument(secondaryPersistence, primaryKeyAttribute);
    for (Persistence<O, A> additionalPersistence : additionalPersistences) {
        validatePersistenceArgument(additionalPersistence, primaryKeyAttribute);
    }
}
 
Example #30
Source File: DiskPersistence.java    From cqengine with Apache License 2.0 5 votes vote down vote up
protected DiskPersistence(SimpleAttribute<O, A> primaryKeyAttribute, File file, Properties overrideProperties) {
    Properties effectiveProperties = new Properties();
    effectiveProperties.putAll(DEFAULT_PROPERTIES);
    effectiveProperties.putAll(overrideProperties);
    SQLiteConfig sqLiteConfig = new SQLiteConfig(effectiveProperties);
    SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(sqLiteConfig);
    sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file);

    this.primaryKeyAttribute = primaryKeyAttribute;
    this.file = file.getAbsoluteFile();
    this.sqLiteDataSource = sqLiteDataSource;

    boolean openPersistentConnection = "true".equals(effectiveProperties.getProperty("persistent_connection")); //default false
    boolean useSharedCache = "true".equals(effectiveProperties.getProperty("shared_cache")); // default false
    boolean useReadWriteLock = !"false".equals(effectiveProperties.getProperty("use_read_write_lock")); // default true
    if (useSharedCache) {
        // If shared_cache mode is enabled, by default we also use a read-write lock,
        // unless using the read-write lock has been explicitly disabled...
        sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file + "?cache=shared");
        this.useReadWriteLock = useReadWriteLock;
    }
    else {
        // If we are not using shared_cache mode, we never use a read-write lock...
        sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file);
        this.useReadWriteLock = false;
    }
    if (useSharedCache || openPersistentConnection) {
        // If shared_cache is enabled, we always open a persistent connection regardless...
        this.persistentConnection = getConnectionWithoutRWLock(null, noQueryOptions());
    }
}