public class NestedExpressionTest { StringPath str1 = Expressions.stringPath("str1"); StringPath str2 = Expressions.stringPath("str2"); StringPath str3 = Expressions.stringPath("str3"); StringPath str4 = Expressions.stringPath("str3"); Concatenation concat1 = new Concatenation(new Concatenation(str1, str2), str3); Concatenation concat2 = new Concatenation(new Concatenation(str1, new Concatenation(str2, str3)), str4); @Test public void wrapped_projection_has_right_arguments() { FactoryExpression<String> wrapped = FactoryExpressionUtils.wrap(concat1); assertEquals(Arrays.asList(str1, str2, str3), wrapped.getArgs()); } @Test public void wrapped_projection_compresses_projection() { FactoryExpression<String> wrapped = FactoryExpressionUtils.wrap(concat1); assertEquals("123", wrapped.newInstance("1", "2", "3")); } @Test public void deeply_wrapped_projection_has_right_arguments() { FactoryExpression<String> wrapped = FactoryExpressionUtils.wrap(concat2); assertEquals(Arrays.asList(str1, str2, str3, str4), wrapped.getArgs()); } @Test public void deeply_wrapped_projection_compresses_projection() { FactoryExpression<String> wrapped = FactoryExpressionUtils.wrap(concat2); assertEquals("1234", wrapped.newInstance("1", "2", "3", "4")); } }
@Test @Override public void booleanTemplate() { assertSerialized(Expressions.booleanPath("b").eq(Expressions.TRUE), "b = true"); assertSerialized(Expressions.booleanPath("b").eq(Expressions.FALSE), "b = false"); query.setUseLiterals(true); query.where(Expressions.booleanPath("b").eq(true)); assertTrue(query.toString(), query.toString().endsWith("where b = true")); }
@Test public void Various1() { StringPath str = Expressions.stringPath("str"); assertEquals( Arrays.asList("a", "ab"), from(str, "a", "ab", "cd", "de").where(str.startsWith("a")).select(str).fetch()); }
@Test public void Serialization() throws IOException, ClassNotFoundException { StringPath expr = Expressions.stringPath("str"); metadata.addJoin(JoinType.DEFAULT, expr); metadata.addFlag(new QueryFlag(Position.AFTER_FILTERS, "")); metadata.addGroupBy(expr); metadata.addHaving(expr.isEmpty()); // metadata.getJoins().get(0).addFlag(new JoinFlag("")); metadata.addJoinCondition(expr.isEmpty()); metadata.addOrderBy(expr.asc()); metadata.setProjection(expr); metadata.addWhere(expr.isEmpty()); QueryMetadata metadata2 = Serialization.serialize(metadata); assertEquals(metadata.getFlags(), metadata2.getFlags()); assertEquals(metadata.getGroupBy().get(0), metadata2.getGroupBy().get(0)); assertEquals(metadata.getGroupBy(), metadata2.getGroupBy()); assertEquals(metadata.getHaving(), metadata2.getHaving()); assertEquals(metadata.getJoins(), metadata2.getJoins()); assertEquals(metadata.getModifiers(), metadata2.getModifiers()); assertEquals(metadata.getOrderBy(), metadata2.getOrderBy()); assertEquals(metadata.getParams(), metadata2.getParams()); assertEquals(metadata.getProjection(), metadata2.getProjection()); assertEquals(metadata.getWhere(), metadata2.getWhere()); }
@Test public void QueryElement() throws Exception { Query query1 = serializer.toQuery(author.like("Michael"), metadata); Query query2 = serializer.toQuery(text.like("Text"), metadata); BooleanExpression query = Expressions.anyOf(new QueryElement(query1), new QueryElement(query2)); testQuery(query, "author:michael text:text", 1); }
/** * Gets a blob with its current version from the database. If an exception or error occures, this * method closes the database connection. * * @param blobId The id of the blob. * @param forUpdate Whether a pessimistic lock should be applied on the blob or not. * @param connection The database connection. * @return The blob and its current version. */ protected ConnectedBlob connectBlob( final long blobId, final boolean forUpdate, final Connection connection) { QBlobstoreBlob qBlob = QBlobstoreBlob.blobstoreBlob; try { SQLQuery<Tuple> query = new SQLQuery<>(connection, querydslConfiguration) .select( qBlob.blobId, qBlob.version_.as("version_"), Expressions.as(blobSelectionExpression, "blob_")) .from(qBlob) .where(qBlob.blobId.eq(blobId)); if (forUpdate) { query.forUpdate(); } else if (lockBlobForShareQueryFlag != null) { query.addFlag(lockBlobForShareQueryFlag); } SQLBindings sqlBindings = query.getSQL(); String sql = sqlBindings.getSQL(); PreparedStatement preparedStatement = connection.prepareStatement(sql); int paramIndex = 0; for (Object binding : (List<Object>) sqlBindings.getBindings()) { paramIndex++; preparedStatement.setObject(paramIndex, binding); } long version; Blob blob; ResultSet resultSet = preparedStatement.executeQuery(); try { if (!resultSet.next()) { throw new NoSuchBlobException(blobId); } version = resultSet.getLong("version_"); blob = resultSet.getBlob("blob_"); } finally { final boolean closeResultSetIsNotNecessaryAsItWillBeClosedByStatement = false; closeResultSet(resultSet, closeResultSetIsNotNecessaryAsItWillBeClosedByStatement); } BlobChannel blobChannel; if (blobAccessMode == BlobAccessMode.BYTES) { blobChannel = new BytesBlobChannel(blob); } else { blobChannel = new StreamBlobChannel(blob); } return new ConnectedBlob(blobId, blobChannel, version, preparedStatement); } catch (SQLException | RuntimeException | Error e) { closeCloseableDueToThrowable(connection, e); // TODO throw unchecked sql exception throw new RuntimeException(e); } }
@Test public void roundtrip() throws Exception { Path<?> path = ExpressionUtils.path(Object.class, "entity"); SimplePath<?> path2 = Expressions.path(Object.class, "entity"); assertEquals(path, serialize(path)); assertEquals(path2, serialize(path2)); assertEquals(path2.isNull(), serialize(path2.isNull())); assertEquals(path.hashCode(), serialize(path).hashCode()); assertEquals(path2.hashCode(), serialize(path2).hashCode()); assertEquals(path2.isNull().hashCode(), serialize(path2.isNull()).hashCode()); }
@SuppressWarnings("unchecked") @Test public void union() { NumberExpression<Integer> one = Expressions.ONE; NumberExpression<Integer> two = Expressions.TWO; NumberExpression<Integer> three = Expressions.THREE; Path<Integer> col1 = Expressions.path(Integer.class, "col1"); Union union = query.union(select(one.as(col1)), select(two), select(three)); assertEquals( "(select 1 as col1)\n" + "union\n" + "(select 2)\n" + "union\n" + "(select 3)", union.toString()); }
/** * Resolves the expression of an empty blob based on the configuration or if it is not available * in the configuration, based on the database type. * * @param configuration The configuration that was passed to the blobstore. * @return The expression of an empty blob that can be used in an insert statement. */ protected Expression<Blob> resolveEmptyBlobExpression( final JdbcBlobstoreConfiguration configuration) { if (configuration != null && configuration.emptyBlobExpression != null) { return configuration.emptyBlobExpression; } DatabaseTypeEnum databaseType = guessDatabaseType(); if (databaseType == DatabaseTypeEnum.ORACLE) { return SQLExpressions.relationalFunctionCall(Blob.class, "empty_blob"); } else { return Expressions.constant(new EmptyReadOnlyBlob()); } }
@Test public void expressions() throws Exception { Map<Class<?>, Object> args = Maps.newHashMap(); args.put(Object.class, "obj"); args.put(BeanPath.class, new EntityPathBase<Object>(Object.class, "obj")); args.put(Class.class, Integer.class); args.put(Class[].class, new Class<?>[] {Object.class, Object.class}); args.put(java.util.Date.class, new java.util.Date(0)); args.put(java.sql.Date.class, new java.sql.Date(0)); args.put(java.sql.Time.class, new java.sql.Time(0)); args.put(java.sql.Timestamp.class, new java.sql.Timestamp(0)); args.put(Expression.class, Expressions.enumPath(Gender.class, "e")); args.put( Expression[].class, new Expression<?>[] {Expressions.enumPath(Gender.class, "e"), Expressions.stringPath("s")}); args.put(FactoryExpression.class, Projections.tuple(Expressions.stringPath("str"))); args.put(GroupExpression.class, GroupBy.avg(Expressions.numberPath(Integer.class, "num"))); args.put(Number.class, 1); args.put(Operator.class, Ops.AND); args.put(Path.class, Expressions.stringPath("str")); args.put(PathBuilderValidator.class, PathBuilderValidator.DEFAULT); args.put(PathMetadata.class, PathMetadataFactory.forVariable("obj")); args.put(PathInits.class, PathInits.DEFAULT); args.put(Predicate.class, Expressions.path(Object.class, "obj").isNull()); args.put(QueryMetadata.class, new DefaultQueryMetadata()); args.put(String.class, "obj"); Reflections reflections = new Reflections(); Set<Class<? extends Expression>> types = reflections.getSubTypesOf(Expression.class); for (Class<?> type : types) { if (!type.isInterface() && !type.isMemberClass() && !Modifier.isAbstract(type.getModifiers())) { for (Constructor<?> c : type.getConstructors()) { Object[] parameters = new Object[c.getParameterTypes().length]; for (int i = 0; i < c.getParameterTypes().length; i++) { parameters[i] = Objects.requireNonNull( args.get(c.getParameterTypes()[i]), c.getParameterTypes()[i].getName()); } c.setAccessible(true); Object o = c.newInstance(parameters); assertEquals(o, Serialization.serialize(o)); } } } }
/** * Resolving the selection expression of the blob based on the configuration or if it is not * available in the configuration, based on the database type. This is necessary as for example if * MySQL is used with remote locator mode, instead of the blob column name, a string constant has * to be used that contains the column name in the SQL expression. * * @param configuration The configuration passed to this blobstore. * @return The selection expression of the blob. */ protected Expression<?> resolveBlobSelectionExpression( final JdbcBlobstoreConfiguration configuration) { if (configuration != null && configuration.blobSelectionExpression != null) { return configuration.blobSelectionExpression; } DatabaseTypeEnum databaseType = guessDatabaseType(); if (databaseType != DatabaseTypeEnum.MYSQL) { return QBlobstoreBlob.blobstoreBlob.blob_; } try (Connection connection = dataSource.getConnection()) { if (!connection.getMetaData().locatorsUpdateCopy()) { return Expressions.constant(QBlobstoreBlob.blobstoreBlob.blob_.getMetadata().getName()); } else { return QBlobstoreBlob.blobstoreBlob.blob_; } } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } }
/** * Returns Y minima of a bounding box 2d or 3d or a geometry. * * @param expr geometry * @return y minima */ public static NumberExpression<Double> ymin(JTSGeometryExpression<?> expr) { return Expressions.numberOperation(Double.class, SpatialOps.YMIN, expr); }
/** * Returns X maxima of a bounding box 2d or 3d or a geometry. * * @param expr geometry * @return x maxima */ public static NumberExpression<Double> xmax(JTSGeometryExpression<?> expr) { return Expressions.numberOperation(Double.class, SpatialOps.XMAX, expr); }
/** * Return a specified ST_Geometry value from Extended Well-Known Text representation (EWKT). * * @param expr geometry * @return EWKT form */ public static StringExpression asEWKT(JTSGeometryExpression<?> expr) { return Expressions.stringOperation(SpatialOps.AS_EWKT, expr); }
/** * Returns true if the geometries are within the specified distance of one another. For geometry * units are in those of spatial reference and For geography units are in meters. * * @param expr1 geometry * @param expr2 other geometry * @param distance distance * @return true, if with distance of each other */ public static BooleanExpression dwithin( Expression<? extends Geometry> expr1, Expression<? extends Geometry> expr2, double distance) { return Expressions.booleanOperation( SpatialOps.DWITHIN, expr1, expr2, ConstantImpl.create(distance)); }
/** * Returns true if the geometries are within the specified distance of one another. For geometry * units are in those of spatial reference and For geography units are in meters. * * @param expr1 geometry * @param expr2 other geometry * @param distance distance * @return true, if with distance of each other */ public static BooleanExpression dwithin( Expression<? extends Geometry> expr1, Expression<? extends Geometry> expr2, Expression<Double> distance) { return Expressions.booleanOperation(SpatialOps.DWITHIN, expr1, expr2, distance); }
/** * The number of Points in this LineString. * * @return number of points */ public NumberExpression<Integer> numPoints() { if (numPoints == null) { numPoints = Expressions.numberOperation(Integer.class, SpatialOps.NUM_POINTS, mixin); } return numPoints; }
/** * Create a new variable path * * @param arg alias * @param <D> * @return expression */ @SuppressWarnings("unchecked") public static <D extends Comparable<?>> ComparablePath<D> var(D arg) { return Expressions.comparablePath((Class<D>) arg.getClass(), "var" + arg); }
/** * Create a new variable path * * @param arg alias * @param <D> * @return expression */ @SuppressWarnings("unchecked") public static <D extends Number & Comparable<D>> NumberPath<D> var(D arg) { return Expressions.numberPath( (Class<D>) arg.getClass(), "var" + arg.getClass().getSimpleName() + arg); }
/** * The area of this MultiSurface, as measured in the spatial reference system of this * MultiSurface. * * @return area */ public NumberExpression<Double> area() { if (area == null) { area = Expressions.numberOperation(Double.class, SpatialOps.AREA, mixin); } return area; }
@Test public void Various3() { NumberPath<Integer> num = Expressions.numberPath(Integer.class, "num"); assertEquals( Arrays.asList(1, 2, 3), from(num, 1, 2, 3, 4).where(num.lt(4)).select(num).fetch()); }
/** * Create a new variable path * * @param arg alias * @return expression */ public static StringPath var(String arg) { return Expressions.stringPath(arg.replace(' ', '_')); }
@Test public void order() { OrderSpecifier<?> order = new OrderSpecifier<String>(Order.ASC, Expressions.stringPath("str")); assertEquals(order, Serialization.serialize(order)); }
/** * {@code Alias} provides alias factory methods * * <p>Example: * * <pre>{@code * Employee e = alias(Employee.class, "e"); * for (String name : query.from($(e),employees) * .where($(e.getDepartment().getId()).eq(1001)) * .list($(e.getName()))) { * System.out.println(name); * } * }</pre> * * <p>using the following static imports * * <pre>{@code * import static com.mysema.query.alias.Alias.$; * import static com.mysema.query.alias.Alias.alias; * }</pre> * * @author tiwe */ @SuppressWarnings("PMD") public final class Alias { private static final AliasFactory aliasFactory = new AliasFactory(new DefaultPathFactory(), new DefaultTypeSystem()); private static final SimplePath<Object> it = Expressions.path(Object.class, "it"); // exclude $-methods from Checkstyle checks // CHECKSTYLE:OFF /** * Convert the given alias to an expression * * @param <D> * @return expression */ public static <D extends Expression<?>> D $() { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <D> * @return expression */ public static <D> ArrayPath<D[], D> $(D[] arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<BigDecimal> $(BigDecimal arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<BigInteger> $(BigInteger arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static BooleanPath $(Boolean arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<Byte> $(Byte arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <T> * @return expression */ public static <T extends Enum<T>> EnumPath<T> $(T arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <D> * @return expression */ public static <D> CollectionPath<D, SimpleExpression<D>> $(Collection<D> arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <D> * @return expression */ public static <D extends Comparable<?>> ComparablePath<D> $(D arg) { return Alias.getPath(arg); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<Double> $(Double arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<Float> $(Float arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<Integer> $(Integer arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static DatePath<java.sql.Date> $(java.sql.Date arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static DateTimePath<java.util.Date> $(java.util.Date arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <D> * @return expression */ public static <D> ListPath<D, SimpleExpression<D>> $(List<D> arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<Long> $(Long arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <K> * @param <V> * @return expression */ public static <K, V> MapPath<K, V, SimpleExpression<V>> $(Map<K, V> arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <D> * @return expression */ public static <D> SetPath<D, SimpleExpression<D>> $(Set<D> arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static NumberPath<Short> $(Short arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static StringPath $(String arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static TimePath<Time> $(Time arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @return expression */ public static DateTimePath<Timestamp> $(Timestamp arg) { return aliasFactory.getCurrentAndReset(); } /** * Convert the given alias to an expression * * @param arg alias * @param <D> * @return expression */ @SuppressWarnings("unchecked") @Nullable public static <D> EntityPathBase<D> $(D arg) { EntityPathBase<D> rv = aliasFactory.getCurrentAndReset(); if (rv != null) { return rv; } else if (arg instanceof EntityPath<?>) { return (EntityPathBase<D>) arg; // NOSONAR } else if (arg instanceof ManagedObject) { return (EntityPathBase<D>) ((ManagedObject) arg).__mappedPath(); } else { return null; } } @SuppressWarnings("unchecked") @Nullable private static <D, P extends Path<D>> P getPath(D arg) { P rv = aliasFactory.getCurrentAndReset(); if (rv != null) { return rv; } else if (arg instanceof Path<?>) { return (P) arg; } else if (arg instanceof ManagedObject) { return (P) ((ManagedObject) arg).__mappedPath(); } else { return null; } } // CHECKSTYLE:ON /** * Create a new alias proxy of the given type * * @param cl type of the alias * @return alias instance */ public static <A> A alias(Class<A> cl) { return alias(cl, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, cl.getSimpleName())); } /** * Create a new alias proxy of the given type for the given expression * * @param cl type of the alias * @param expr underlying expression * @return alias instance */ public static <A> A alias(Class<A> cl, Expression<? extends A> expr) { return aliasFactory.createAliasForExpr(cl, expr); } /** * Create a new alias proxy of the given type for the given variable * * @param cl type of the alias * @param var variable name for the underlying expression * @return alias instance */ public static <A> A alias(Class<A> cl, String var) { return aliasFactory.createAliasForVariable(cl, var); } /** * Convert the given alias to an expression * * @param <D> * @param arg alias instance * @return underlying expression */ @SuppressWarnings("unchecked") public static <D> Expression<D> getAny(D arg) { Expression<D> current = aliasFactory.getCurrentAndReset(); if (current != null) { return current; } else if (arg instanceof ManagedObject) { return (Expression<D>) ((ManagedObject) arg).__mappedPath(); } else { throw new IllegalArgumentException("No path mapped to " + arg); } } /** Reset the alias */ public static void resetAlias() { aliasFactory.reset(); } /** * Return the default variable * * @param <D> * @return expression */ @SuppressWarnings("unchecked") public static <D> SimplePath<D> var() { return (SimplePath<D>) it; } /** * Create a new variable path * * @param arg alias * @param <D> * @return expression */ @SuppressWarnings("unchecked") public static <D extends Comparable<?>> ComparablePath<D> var(D arg) { return Expressions.comparablePath((Class<D>) arg.getClass(), "var" + arg); } /** * Create a new variable path * * @param arg alias * @param <D> * @return expression */ @SuppressWarnings("unchecked") public static <D extends Number & Comparable<D>> NumberPath<D> var(D arg) { return Expressions.numberPath( (Class<D>) arg.getClass(), "var" + arg.getClass().getSimpleName() + arg); } /** * Create a new variable path * * @param arg alias * @param <D> * @return expression */ @SuppressWarnings("unchecked") public static <D> EntityPathBase<D> var(D arg) { String var = "var" + arg.getClass().getSimpleName() + "_" + arg.toString().replace(' ', '_'); return new PathBuilder<D>((Class) arg.getClass(), var); } /** * Create a new variable path * * @param arg alias * @return expression */ public static StringPath var(String arg) { return Expressions.stringPath(arg.replace(' ', '_')); } private Alias() {} }